diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea78d7e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# build artifact (see Makefile) +/sup2vob +CLAUDE.md diff --git a/Convert.swift b/Convert.swift index 2a1a6d7..7d1abb1 100644 --- a/Convert.swift +++ b/Convert.swift @@ -6,14 +6,14 @@ var debugFrames = false // MARK: - DVD subtitle frame (post scale + color reduction) struct DVDSup { - var w: Int - var h: Int - var x: Int // left offset on the DVD frame - var y: Int // top offset on the DVD frame - var start: Int64 // 90 kHz ticks (real) - var end: Int64 // 90 kHz ticks (real) + var width: Int + var height: Int + var left: Int // left offset on the DVD frame + var top: Int // top offset on the DVD frame + var startTicks: Int64 // 90 kHz ticks (real) + var endTicks: Int64 // 90 kHz ticks (real) var forced: Bool - var idx: [UInt8] // w*h, values 0..3 (index into the shared 4-color palette) + var paletteIndices: [UInt8] // width*height, values 0..3 (index into the shared 4-color palette) } struct DVDResolution { @@ -26,10 +26,10 @@ struct DVDResolution { /// 0x10=23.976p 0x20=24p 0x30=25p 0x40=29.97p 0x50=50i 0x60=59.94i /// 0x70=50p 0x80=59.94p; low codes 0x02/0x04/0x06 are 25/50-family formats. static func from(frameRateCode: UInt8) -> DVDResolution { - let hi = Int(frameRateCode >> 4) - let lo = Int(frameRateCode & 0x0F) - if hi == 3 || hi == 5 || hi == 7 { return .pal } - if lo == 2 || lo == 4 || lo == 6 { return .pal } + let majorCode = Int(frameRateCode >> 4) + let minorCode = Int(frameRateCode & 0x0F) + if majorCode == 3 || majorCode == 5 || majorCode == 7 { return .pal } + if minorCode == 2 || minorCode == 4 || minorCode == 6 { return .pal } return .ntsc } } @@ -37,214 +37,224 @@ struct DVDResolution { // MARK: - Frame assembly (objects → RGBA canvas rectangle) /// Compose the frame's objects onto their bounding rectangle. -func composeRect(_ c: Composition) -> (x: Int, y: Int, w: Int, h: Int, rgba: [RGBA])? { +func composeRect(_ composition: Composition) -> (left: Int, top: Int, width: Int, height: Int, pixels: [RGBA])? { var minX = Int.max, minY = Int.max, maxX = Int.min, maxY = Int.min - for o in c.objects where o.w > 0 && o.h > 0 { - minX = min(minX, o.x); minY = min(minY, o.y) - maxX = max(maxX, o.x + o.w); maxY = max(maxY, o.y + o.h) + for object in composition.objects where object.width > 0 && object.height > 0 { + minX = min(minX, object.left); minY = min(minY, object.top) + maxX = max(maxX, object.left + object.width); maxY = max(maxY, object.top + object.height) } guard maxX > minX, maxY > minY else { return nil } - let x0 = max(0, minX), y0 = max(0, minY) - let x1 = min(c.canvasW, maxX), y1 = min(c.canvasH, maxY) - let w = x1 - x0, h = y1 - y0 - guard w > 0, h > 0 else { return nil } + let clipLeft = max(0, minX), clipTop = max(0, minY) + let clipRight = min(composition.canvasWidth, maxX), clipBottom = min(composition.canvasHeight, maxY) + let width = clipRight - clipLeft, height = clipBottom - clipTop + guard width > 0, height > 0 else { return nil } - var rgba = Array(repeating: RGBA.transparent, count: w * h) - for o in c.objects where o.w > 0 && o.h > 0 { - for sy in 0..= 0 && dy < h else { continue } - for sx in 0..= 0 && dx < w else { continue } + var pixels = Array(repeating: RGBA.transparent, count: width * height) + for object in composition.objects where object.width > 0 && object.height > 0 { + for srcY in 0..= 0 && dstY < height else { continue } + for srcX in 0..= 0 && dstX < width else { continue } // No color key in PGS: every index goes through the palette; // transparency is the palette entry's alpha (undocumented // entries default to alpha 0). - rgba[dy * w + dx] = c.palette.entries[Int(o.pixels[sy * o.w + sx])] + pixels[dstY * width + dstX] = composition.palette.entries[Int(object.pixels[srcY * object.width + srcX])] } } } - return (x0, y0, w, h, rgba) + return (clipLeft, clipTop, width, height, pixels) } // MARK: - Scaling (area-average filter with alpha coverage) -func scaleBox(_ src: [RGBA], _ sw: Int, _ sh: Int, _ dw: Int, _ dh: Int) -> [RGBA] { - var out = [RGBA](repeating: .transparent, count: dw * dh) - guard dw > 0, dh > 0 else { return out } - let fx = Double(sw) / Double(dw) - let fy = Double(sh) / Double(dh) - for oy in 0.. 0 else { continue } - let wgtX = min(Double(x1), Double(sx + 1)) - max(Double(x0), Double(sx)) - let wa = Double(p.a) / 255.0 * wgtX * wgtY - aSum += wa - rSum += Double(p.r) * wa - gSum += Double(p.g) * wa - bSum += Double(p.b) * wa +func scaleBox(_ source: [RGBA], _ sourceWidth: Int, _ sourceHeight: Int, + _ destWidth: Int, _ destHeight: Int) -> [RGBA] { + var output = [RGBA](repeating: .transparent, count: destWidth * destHeight) + guard destWidth > 0, destHeight > 0 else { return output } + let sourcePixelsPerDestX = Double(sourceWidth) / Double(destWidth) + let sourcePixelsPerDestY = Double(sourceHeight) / Double(destHeight) + for destY in 0.. 0 else { continue } + let horizontalCoverage = min(Double(srcXEnd), Double(srcX + 1)) - max(Double(srcXStart), Double(srcX)) + let pixelWeight = Double(pixel.a) / 255.0 * horizontalCoverage * verticalCoverage + alphaWeightSum += pixelWeight + redSum += Double(pixel.r) * pixelWeight + greenSum += Double(pixel.g) * pixelWeight + blueSum += Double(pixel.b) * pixelWeight } } - let area = Double(x1 - x0) * Double(y1 - y0) - guard area > 0, aSum / area * 255.0 >= 128.0 else { continue } + let destCellArea = Double(srcXEnd - srcXStart) * Double(srcYEnd - srcYStart) + guard destCellArea > 0, alphaWeightSum / destCellArea * 255.0 >= 128.0 else { continue } // DVD has no real alpha: keep pixels whose coverage is at least half. - let wgt = max(aSum, 0.0001) - let r = UInt8(min(255, max(0, Int((rSum / wgt).rounded())))) - let g = UInt8(min(255, max(0, Int((gSum / wgt).rounded())))) - let b = UInt8(min(255, max(0, Int((bSum / wgt).rounded())))) - out[oy * dw + ox] = RGBA(r: r, g: g, b: b, a: 255) + let totalWeight = max(alphaWeightSum, 0.0001) + let r = UInt8(min(255, max(0, Int((redSum / totalWeight).rounded())))) + let g = UInt8(min(255, max(0, Int((greenSum / totalWeight).rounded())))) + let b = UInt8(min(255, max(0, Int((blueSum / totalWeight).rounded())))) + output[destY * destWidth + destX] = RGBA(r: r, g: g, b: b, a: 255) } } - return out + return output } // MARK: - Color reduction -func nearestColor(_ c: RGBA, among set: [RGBA]) -> RGBA { - var best = set[0], bestD = Int.max - for p in set { - let dr = Int(c.r) - Int(p.r), dg = Int(c.g) - Int(p.g), db = Int(c.b) - Int(p.b) - let d = dr * dr + dg * dg + db * db - if d < bestD { bestD = d; best = p } +func nearestColor(_ color: RGBA, among candidates: [RGBA]) -> RGBA { + var best = candidates[0], bestDistance = Int.max + for candidate in candidates { + let rDiff = Int(color.r) - Int(candidate.r) + let gDiff = Int(color.g) - Int(candidate.g) + let bDiff = Int(color.b) - Int(candidate.b) + let squaredDistance = rDiff * rDiff + gDiff * gDiff + bDiff * bDiff + if squaredDistance < bestDistance { bestDistance = squaredDistance; best = candidate } } return best } struct ConversionResult { - var subs: [DVDSup] - var palette4: [RGBA] // [0] = transparent, [1..3] = shared colors (also idx0 in the 16-slot file palette) + var frames: [DVDSup] + var fourColorPalette: [RGBA] // [0] = transparent, [1..3] = shared colors (also idx0 in the 16-slot file palette) } /// PGS compositions → DVD subpictures: end times, scaling, cropping, and a /// single shared 4-color palette (VobSub's `tridx: 1000` convention makes only /// 2-bit code 0 transparent, so all frames must share one color set). -func convertToDVD(_ comps: [Composition], resolution pal: DVDResolution) -> ConversionResult { +func convertToDVD(_ compositions: [Composition], resolution targetRes: DVDResolution) -> ConversionResult { // Non-blank compositions are frames. The next composition (blank or not) // closes the previous frame's display time — PGS "clear screen" semantics. - var frames: [(c: Composition, end: Int64)] = [] - for (i, c) in comps.enumerated() where !c.isBlank { - var end: Int64? = nil - for j in (i + 1).. c.startTicks { - end = comps[j].startTicks + var timedFrames: [(composition: Composition, endTicks: Int64)] = [] + for (i, composition) in compositions.enumerated() where !composition.isBlank { + var endTicks: Int64? = nil + for j in (i + 1).. composition.startTicks { + endTicks = compositions[j].startTicks break } - frames.append((c, end ?? (c.startTicks + 2 * 90000))) + timedFrames.append((composition, endTicks ?? (composition.startTicks + 2 * 90000))) } // pass 1: geometry + opaque pixels per frame, counting colors globally - struct Prepped { var x, y, w, h: Int; var start, end: Int64; var forced: Bool; var px: [RGBA] } - var prepped: [Prepped] = [] - var counts: [Int: Int] = [:] - for (c, end) in frames { - guard let (rx, ry, rw, rh, canvas) = composeRect(c) else { + struct PreppedFrame { + var left, top, width, height: Int + var startTicks, endTicks: Int64 + var forced: Bool + var pixels: [RGBA] + } + var preppedFrames: [PreppedFrame] = [] + var colorCounts: [Int: Int] = [:] + for (composition, endTicks) in timedFrames { + guard let (rectLeft, rectTop, rectWidth, rectHeight, canvasPixels) = composeRect(composition) else { if debugFrames { - let att = c.objects.map { String($0.w) }.joined(separator: ",") - FileHandle.standardError.write("drop t=\(c.startTicks): composeRect nil (objs=\(c.objects.count) widths=[\(att)])\n".data(using: .utf8)!) + let objectWidths = composition.objects.map { String($0.width) }.joined(separator: ",") + FileHandle.standardError.write("drop t=\(composition.startTicks): composeRect nil (objs=\(composition.objects.count) widths=[\(objectWidths)])\n".data(using: .utf8)!) } continue } - if fullFrame { - // Passthrough, as BDSup2Sub does at the source resolution: keep the - // object rect verbatim — no downscale, no transparent-edge crop (its + if fullFramePassthrough { + // Passthrough: keep the object rect verbatim — no downscale, no transparent-edge crop (its // output frames match the source object geometry exactly). - var padded = canvas - var ch = rh - if rh < 2 { padded += Array(repeating: .transparent, count: rw); ch = 2 } - // BDSup2Sub paints at alpha ≥~30% only (RGBA.jarPainted): the - // fainter half of a PGS plate (alpha ≤76) vanishes from every jar - // frame while alpha-80 gradient entries are drawn. - for p in padded where p.jarPainted { counts[p.javaRGB, default: 0] += 1 } - prepped.append(Prepped(x: rx, y: ry, w: rw, h: ch, start: c.startTicks, end: end, - forced: c.objects.contains { $0.forced }, px: padded)) + var paddedPixels = canvasPixels + var paddedHeight = rectHeight + if rectHeight < 2 { paddedPixels += Array(repeating: .transparent, count: rectWidth); paddedHeight = 2 } + + for pixel in paddedPixels where pixel.isPainted { colorCounts[pixel.packedARGB, default: 0] += 1 } + preppedFrames.append(PreppedFrame(left: rectLeft, top: rectTop, width: rectWidth, height: paddedHeight, + startTicks: composition.startTicks, endTicks: endTicks, + forced: composition.objects.contains { $0.forced }, pixels: paddedPixels)) continue } - let sx = Double(pal.width) / Double(c.canvasW) - let sy = Double(pal.height) / Double(c.canvasH) - var dx = Int((Double(rx) * sx).rounded()) - var dy = Int((Double(ry) * sy).rounded()) + let scaleX = Double(targetRes.width) / Double(composition.canvasWidth) + let scaleY = Double(targetRes.height) / Double(composition.canvasHeight) + var destLeft = Int((Double(rectLeft) * scaleX).rounded()) + var destTop = Int((Double(rectTop) * scaleY).rounded()) // ffmpeg's decoder needs h ≥ 2 (`w > 0 && h > 1`), so the scale target // can never be a single row tall. - dx = min(max(0, dx), pal.width - 2) - dy = min(max(0, dy), pal.height - 2) - let dw = min(max(2, Int((Double(rw) * sx).rounded())), pal.width - dx) - let dh = min(max(2, Int((Double(rh) * sy).rounded())), pal.height - dy) - guard dw > 0, dh > 0 else { - if debugFrames { FileHandle.standardError.write("drop t=\(c.startTicks): rect=\(rx),\(ry) \(rw)x\(rh) → \(dx),\(dy) \(dw)x\(dh)\n".data(using: .utf8)!) } + destLeft = min(max(0, destLeft), targetRes.width - 2) + destTop = min(max(0, destTop), targetRes.height - 2) + let destWidth = min(max(2, Int((Double(rectWidth) * scaleX).rounded())), targetRes.width - destLeft) + let destHeight = min(max(2, Int((Double(rectHeight) * scaleY).rounded())), targetRes.height - destTop) + guard destWidth > 0, destHeight > 0 else { + if debugFrames { FileHandle.standardError.write("drop t=\(composition.startTicks): rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight)\n".data(using: .utf8)!) } continue } - let scaled = scaleBox(canvas, rw, rh, dw, dh) + let scaled = scaleBox(canvasPixels, rectWidth, rectHeight, destWidth, destHeight) // crop to the opaque bounding box - var bx0 = dw, by0 = dh, bx1 = -1, by1 = -1 - for yy in 0..= bx0 else { + guard bboxRight >= bboxLeft else { if debugFrames { - let vis = scaled.filter { $0.isVisible }.count - let cop = canvas.filter { $0.isOpaque }.count - let hist = c.objects.map { o -> String in - var h: [Int: Int] = [:] - for v in o.pixels { h[Int(v), default: 0] += 1 } - let top = h.sorted { $0.key < $1.key }.prefix(12) + let visibleCount = scaled.filter { $0.isVisible }.count + let canvasOpaqueCount = canvasPixels.filter { $0.isOpaque }.count + let objectIndexHistogram = composition.objects.map { object -> String in + var indexCounts: [Int: Int] = [:] + for pixelValue in object.pixels { indexCounts[Int(pixelValue), default: 0] += 1 } + let topEntries = indexCounts.sorted { $0.key < $1.key }.prefix(12) .map { "\($0.key):\($0.value)" }.joined(separator: " ") - return "obj\(o.objectID)(\(o.w)x\(o.h)) [\(top)]" + return "obj\(object.objectID)(\(object.width)x\(object.height)) [\(topEntries)]" }.joined(separator: " ") - FileHandle.standardError.write("drop t=\(c.startTicks): no opaque after scale (rect=\(rx),\(ry) \(rw)x\(rh) → \(dx),\(dy) \(dw)x\(dh), scaledVis=\(vis) canvasOpaque=\(cop))\n \(hist)\n".data(using: .utf8)!) + FileHandle.standardError.write("drop t=\(composition.startTicks): no opaque after scale (rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight), scaledVis=\(visibleCount) canvasOpaque=\(canvasOpaqueCount))\n \(objectIndexHistogram)\n".data(using: .utf8)!) } continue } - let cw = bx1 - bx0 + 1, ch = by1 - by0 + 1 - var cropped = [RGBA](repeating: .transparent, count: cw * ch) - for yy in 0.. $1.value : $0.key < $1.key } - var colors = sorted.prefix(3).map { kv -> RGBA in - RGBA(r: UInt8((kv.key >> 16) & 0xFF), g: UInt8((kv.key >> 8) & 0xFF), - b: UInt8(kv.key & 0xFF), a: 255) + let rankedColors = colorCounts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key } + var colors = rankedColors.prefix(3).map { colorCount -> RGBA in + RGBA(r: UInt8((colorCount.key >> 16) & 0xFF), g: UInt8((colorCount.key >> 8) & 0xFF), + b: UInt8(colorCount.key & 0xFF), a: 255) } while colors.count < 3 { colors.append(.transparent) } - var subs: [DVDSup] = [] - for f in prepped { - var map: [Int: UInt8] = [:] - for (k, col) in colors.enumerated() where col.isVisible { map[col.javaRGB] = UInt8(k + 1) } - var idx = [UInt8](repeating: 0, count: f.px.count) - // The paint set is RGBA.jarPainted (BDSup2Sub's alpha-≥77 rule — see - // the fullFrame branch). The DVD path never sees sub-128 pixels here + var frames: [DVDSup] = [] + for prepped in preppedFrames { + var colorCodeByRGB: [Int: UInt8] = [:] + for (slot, color) in colors.enumerated() where color.isVisible { colorCodeByRGB[color.packedARGB] = UInt8(slot + 1) } + var paletteIndices = [UInt8](repeating: 0, count: prepped.pixels.count) + + // The paint set is RGBA.isPainted (alpha-≥77 rule — see + // the fullFramePassthrough branch). The DVD path never sees sub-128 pixels here // because scaleBox already resolved coverage to 0/255, so the // predicates agree in both modes. - for (j, p) in f.px.enumerated() where p.jarPainted { - if let v = map[p.javaRGB] { idx[j] = v } - else { idx[j] = UInt8((colors.firstIndex(of: nearestColor(p, among: colors)) ?? 0) + 1) } + + for (pixelPos, pixel) in prepped.pixels.enumerated() where pixel.isPainted { + if let code = colorCodeByRGB[pixel.packedARGB] { paletteIndices[pixelPos] = code } + else { paletteIndices[pixelPos] = UInt8((colors.firstIndex(of: nearestColor(pixel, among: colors)) ?? 0) + 1) } } - subs.append(DVDSup(w: f.w, h: f.h, x: f.x, y: f.y, start: f.start, end: f.end, - forced: f.forced, idx: idx)) + frames.append(DVDSup(width: prepped.width, height: prepped.height, left: prepped.left, top: prepped.top, + startTicks: prepped.startTicks, endTicks: prepped.endTicks, + forced: prepped.forced, paletteIndices: paletteIndices)) } - return ConversionResult(subs: subs, palette4: [RGBA.transparent] + colors) + return ConversionResult(frames: frames, fourColorPalette: [RGBA.transparent] + colors) } diff --git a/PGS.swift b/PGS.swift index 86bf867..2ed0605 100644 --- a/PGS.swift +++ b/PGS.swift @@ -13,15 +13,15 @@ struct RGBA: Equatable { var isOpaque: Bool { a >= 128 } var isVisible: Bool { a > 0 } - /// BDSup2Sub's paint rule: a pixel is drawn iff its palette alpha is at + /// A pixel is drawn iff its palette alpha is at /// least 30% (0.3 × 255 = 76.5 → ≥77). Empirically pinned against the - /// jar's own full-res frames: every alpha-≤76 pixel absent, every + /// full-res frames: every alpha-≤76 pixel absent, every /// alpha-≥80 pixel present (the file's ladder steps by 4, so the cut is /// proven inside (76, 80]). - var jarPainted: Bool { a >= 77 } + var isPainted: Bool { a >= 77 } - /// 0xAARRGGBB, the layout Java ints use (Bitmap.getRGB) - var javaRGB: Int { + /// 0xAARRGGBB packed into an Int — stable color key for the histograms/maps + var packedARGB: Int { (Int(a) << 24) | (Int(r) << 16) | (Int(g) << 8) | Int(b) } } @@ -32,7 +32,7 @@ enum ColorSpace { case bt601 case bt709 - /// Verbatim arithmetic of the jar: Y-16, C-128, 1.164… gain, + /// Arithmetic: Y-16, C-128, 1.164… gain, /// +0.5-then-truncate rounding, clamp to 0..255. func ycbcrToRGB(_ y: Int, _ cr: Int, _ cb: Int) -> (r: UInt8, g: UInt8, b: UInt8) { let y2 = Double(y) - 16.0 @@ -65,9 +65,9 @@ enum ColorSpace { struct PGSSegment { var pts: UInt32 // 90 kHz PTS, written raw by ffmpeg's sup muxer var type: UInt8 - var data: ArraySlice + var payload: ArraySlice - var realTicks: Int64 { Int64(pts) } + var ptsTicks: Int64 { Int64(pts) } } enum PGSError: Error, CustomStringConvertible { @@ -84,33 +84,34 @@ enum PGSError: Error, CustomStringConvertible { } } -func readPGSSegments(_ buf: [UInt8]) throws -> [PGSSegment] { - var segs: [PGSSegment] = [] - var off = 0 - while off < buf.count { - guard off + 13 <= buf.count else { throw PGSError.truncated("segment header") } - guard buf[off] == 0x50, buf[off + 1] == 0x47 else { throw PGSError.badMagic } - let pts = (UInt32(buf[off + 2]) << 24) | (UInt32(buf[off + 3]) << 16) - | (UInt32(buf[off + 4]) << 8) | UInt32(buf[off + 5]) - let type = buf[off + 10] - let len = Int(buf[off + 11]) << 8 | Int(buf[off + 12]) - guard off + 13 + len <= buf.count else { throw PGSError.truncated("segment body") } - segs.append(PGSSegment(pts: pts, type: type, data: buf[(off + 13)..<(off + 13 + len)])) - off += 13 + len +func readPGSSegments(_ fileBytes: [UInt8]) throws -> [PGSSegment] { + var segments: [PGSSegment] = [] + var offset = 0 + while offset < fileBytes.count { + guard offset + 13 <= fileBytes.count else { throw PGSError.truncated("segment header") } + guard fileBytes[offset] == 0x50, fileBytes[offset + 1] == 0x47 else { throw PGSError.badMagic } + let pts = (UInt32(fileBytes[offset + 2]) << 24) | (UInt32(fileBytes[offset + 3]) << 16) + | (UInt32(fileBytes[offset + 4]) << 8) | UInt32(fileBytes[offset + 5]) + let segmentType = fileBytes[offset + 10] + let payloadLength = Int(fileBytes[offset + 11]) << 8 | Int(fileBytes[offset + 12]) + guard offset + 13 + payloadLength <= fileBytes.count else { throw PGSError.truncated("segment body") } + segments.append(PGSSegment(pts: pts, type: segmentType, + payload: fileBytes[(offset + 13)..<(offset + 13 + payloadLength)])) + offset += 13 + payloadLength } - return segs + return segments } // MARK: - PGS payload parsing (PCS / PDS / ODS / WDS) struct CompositionObject { var objectID: Int - var x: Int - var y: Int + var left: Int // position on the composition canvas + var top: Int var forced: Bool - var w: Int = 0 - var h: Int = 0 - var pixels: [UInt8] = [] // palette indices, row-major w*h + var width: Int = 0 + var height: Int = 0 + var pixels: [UInt8] = [] // palette indices, row-major width*height } struct Palette { @@ -119,8 +120,8 @@ struct Palette { struct Composition { var startTicks: Int64 - var canvasW: Int - var canvasH: Int + var canvasWidth: Int + var canvasHeight: Int var frameRateCode: UInt8 var objectCount: Int var objects: [CompositionObject] = [] @@ -133,23 +134,23 @@ struct Composition { /// are common, so entries must be written at their id, not packed sequentially /// (that bug mapped glyph colors onto uninitialized slots and blanked frames). /// Entries below the segment's base id are skipped, matching ffmpeg. -func parsePaletteSegment(_ d: ArraySlice, space: ColorSpace, into pal: inout Palette) { - guard d.count >= 2 else { return } - let base = Int(d[d.startIndex]) - var i = d.startIndex + 2 - while i + 4 < d.endIndex { - let id = Int(d[i]) - if id >= base, id < 256 { - let y = Int(d[i + 1]), cr = Int(d[i + 2]), cb = Int(d[i + 3]) - let alpha = d[i + 4] +func parsePaletteSegment(_ segmentData: ArraySlice, space: ColorSpace, into palette: inout Palette) { + guard segmentData.count >= 2 else { return } + let baseEntryID = Int(segmentData[segmentData.startIndex]) + var cursor = segmentData.startIndex + 2 + while cursor + 4 < segmentData.endIndex { + let entryID = Int(segmentData[cursor]) + if entryID >= baseEntryID, entryID < 256 { + let y = Int(segmentData[cursor + 1]), cr = Int(segmentData[cursor + 2]), cb = Int(segmentData[cursor + 3]) + let alpha = segmentData[cursor + 4] let (r, g, b) = space.ycbcrToRGB(y, cr, cb) - pal.entries[id] = RGBA(r: r, g: g, b: b, a: alpha) + palette.entries[entryID] = RGBA(r: r, g: g, b: b, a: alpha) } - i += 5 + cursor += 5 } } -/// Decodes one PGS RLE object body into `w*h` palette indices — the exact +/// Decodes one PGS RLE object body into `width*height` palette indices — the exact /// grammar of ffmpeg's pgssubdec.c decode_rle: /// color byte 0xNN (NN != 0) → 1 pixel of color NN /// 0x00 flags → run = flags & 0x3F; @@ -159,116 +160,119 @@ func parsePaletteSegment(_ d: ArraySlice, space: ColorSpace, into pal: in /// Any palette index 0..255 is a legal color — 4-/2-bit objects simply use /// low indices. Filling is LINEAR (ffmpeg does not snap to line starts on EOL /// markers; it only counts them), so a miscounted row cannot cascade. -func decodePGSORLE(_ d: ArraySlice, w: Int, h: Int) -> [UInt8] { - let total = w * h - var out = [UInt8](repeating: 0, count: total) - var i = d.startIndex - let end = d.endIndex - var n = 0 // ffmpeg's pixel_count (linear position in the bitmap) - var line = 0 - while i < end, line < h { - var color = d[i] - i += 1 - var run = 1 +func decodePGSORLE(_ rleData: ArraySlice, width: Int, height: Int) -> [UInt8] { + let pixelCount = width * height + var indices = [UInt8](repeating: 0, count: pixelCount) + var cursor = rleData.startIndex + let rleEnd = rleData.endIndex + var linearPos = 0 // ffmpeg's pixel_count (linear position in the bitmap) + var endOfLineCount = 0 + while cursor < rleEnd, endOfLineCount < height { + var color = rleData[cursor] + cursor += 1 + var runLength = 1 if color == 0 { - guard i < end else { break } - let flags = d[i] - i += 1 - run = Int(flags & 0x3F) + guard cursor < rleEnd else { break } + let flags = rleData[cursor] + cursor += 1 + runLength = Int(flags & 0x3F) if flags & 0x40 != 0 { // 14-bit run: low 6 in flags, high 8 next - guard i < end else { break } - run = (run << 8) | Int(d[i]) - i += 1 + guard cursor < rleEnd else { break } + runLength = (runLength << 8) | Int(rleData[cursor]) + cursor += 1 } if flags & 0x80 != 0 { // explicit color follows the run - guard i < end else { color = 0; break } - color = d[i] - i += 1 + guard cursor < rleEnd else { color = 0; break } + color = rleData[cursor] + cursor += 1 } else { color = 0 } } - if run > 0, n + run <= total { - for k in n..<(n + run) { out[k] = color } - n += run - } else if run == 0 { - line += 1 // end of line; ffmpeg keeps the linear write head + if runLength > 0, linearPos + runLength <= pixelCount { + for pos in linearPos..<(linearPos + runLength) { indices[pos] = color } + linearPos += runLength + } else if runLength == 0 { + endOfLineCount += 1 // end of line; ffmpeg keeps the linear write head } } - return out + return indices } /// Full read of a .sup file into compositions. -func readPGS(_ buf: [UInt8], space: ColorSpace) throws -> [Composition] { - let segs = try readPGSSegments(buf) +func readPGS(_ fileBytes: [UInt8], space: ColorSpace) throws -> [Composition] { + let segments = try readPGSSegments(fileBytes) var palette = Palette() // Raw RLE per object id — objects can arrive split across several ODS // segments (continuations append payload), so decoding is deferred to // composition time, exactly like ffmpeg's object buffering. - var objectsByID: [Int: (w: Int, h: Int, rle: [UInt8])] = [:] - var pending: Composition? - var frames: [Composition] = [] + var objectsByID: [Int: (width: Int, height: Int, rle: [UInt8])] = [:] + var pendingComposition: Composition? + var compositions: [Composition] = [] func flush() { - guard var c = pending else { return } - pending = nil + guard var composition = pendingComposition else { return } + pendingComposition = nil // attach decoded objects - for i in c.objects.indices { - if let o = objectsByID[c.objects[i].objectID] { - c.objects[i].w = o.w - c.objects[i].h = o.h - c.objects[i].pixels = decodePGSORLE(ArraySlice(o.rle), w: o.w, h: o.h) + for i in composition.objects.indices { + if let stored = objectsByID[composition.objects[i].objectID] { + composition.objects[i].width = stored.width + composition.objects[i].height = stored.height + composition.objects[i].pixels = decodePGSORLE(ArraySlice(stored.rle), + width: stored.width, height: stored.height) } } - frames.append(c) + compositions.append(composition) } - for seg in segs { - let d = seg.data + for seg in segments { + let payload = seg.payload switch seg.type { case 0x16: // PCS flush() - guard d.count >= 11 else { break } - let w = Int(d[d.startIndex]) << 8 | Int(d[d.startIndex + 1]) - let h = Int(d[d.startIndex + 2]) << 8 | Int(d[d.startIndex + 3]) - let fps = d[d.startIndex + 4] - let objCount = Int(d[d.startIndex + 10]) - var c = Composition(startTicks: seg.realTicks, canvasW: w, canvasH: h, - frameRateCode: fps, objectCount: objCount, palette: palette) - var i = d.startIndex + 11 - for _ in 0..= 11 else { break } + let canvasWidth = Int(payload[payload.startIndex]) << 8 | Int(payload[payload.startIndex + 1]) + let canvasHeight = Int(payload[payload.startIndex + 2]) << 8 | Int(payload[payload.startIndex + 3]) + let frameRateCode = payload[payload.startIndex + 4] + let objectCount = Int(payload[payload.startIndex + 10]) + var composition = Composition(startTicks: seg.ptsTicks, canvasWidth: canvasWidth, canvasHeight: canvasHeight, + frameRateCode: frameRateCode, objectCount: objectCount, palette: palette) + var cursor = payload.startIndex + 11 + for _ in 0.. 4 else { break } - let id = Int(d[d.startIndex]) << 8 | Int(d[d.startIndex + 1]) - if d[d.startIndex + 3] & 0x80 == 0 { + guard payload.count > 4 else { break } + let objectID = Int(payload[payload.startIndex]) << 8 | Int(payload[payload.startIndex + 1]) + if payload[payload.startIndex + 3] & 0x80 == 0 { // Continuation segment (seqdesc high bit clear): payload // starts at +4 and extends the object's stored RLE data — // exactly ffmpeg's parse_object_segment append path. - if objectsByID[id] != nil { - objectsByID[id]!.rle.append(contentsOf: d[(d.startIndex + 4)..= 11 else { break } - let w = Int(d[d.startIndex + 7]) << 8 | Int(d[d.startIndex + 8]) - let h = Int(d[d.startIndex + 9]) << 8 | Int(d[d.startIndex + 10]) - objectsByID[id] = (w, h, Array(d[(d.startIndex + 11)..= 11 else { break } + let objectWidth = Int(payload[payload.startIndex + 7]) << 8 | Int(payload[payload.startIndex + 8]) + let objectHeight = Int(payload[payload.startIndex + 9]) << 8 | Int(payload[payload.startIndex + 10]) + objectsByID[objectID] = (objectWidth, objectHeight, + Array(payload[(payload.startIndex + 11).. [Composition] { } } flush() - return frames + return compositions } diff --git a/VobSub.swift b/VobSub.swift index e7284aa..3cbbb52 100644 --- a/VobSub.swift +++ b/VobSub.swift @@ -19,23 +19,23 @@ import Foundation struct NibbleWriter { private(set) var bytes: [UInt8] = [] - private var pending: UInt8? // high nibble awaiting its low nibble + private var pendingHighNibble: UInt8? // high nibble awaiting its low nibble - mutating func nibble(_ n: UInt8) { - if let hi = pending { - bytes.append((hi << 4) | (n & 0x0F)) - pending = nil + mutating func nibble(_ value: UInt8) { + if let high = pendingHighNibble { + bytes.append((high << 4) | (value & 0x0F)) + pendingHighNibble = nil } else { - pending = n & 0x0F + pendingHighNibble = value & 0x0F } } /// Pad the stream to a whole byte (only meaningful once every line has /// been terminated, i.e. at the end of the RLE stream). mutating func padToByte() { - if let hi = pending { - bytes.append(hi << 4) - pending = nil + if let high = pendingHighNibble { + bytes.append(high << 4) + pendingHighNibble = nil } } @@ -43,31 +43,31 @@ struct NibbleWriter { /// of line, so a dangling half byte would desynchronize the next line. /// Matches ffmpeg's encoder `if (ncnt & 1) PUTNIBBLE(0)`. mutating func alignLine() { - if pending != nil { nibble(0) } + if pendingHighNibble != nil { nibble(0) } } - private mutating func emitRunValue(_ v: Int) { - precondition(v >= 4 && v <= 1023) - if v <= 15 { - nibble(UInt8(v)) - } else if v <= 63 { - nibble(UInt8(v >> 4)); nibble(UInt8(v & 15)) - } else if v <= 255 { - nibble(0); nibble(UInt8(v >> 4)); nibble(UInt8(v & 15)) + private mutating func emitRunValue(_ encodedValue: Int) { + precondition(encodedValue >= 4 && encodedValue <= 1023) + if encodedValue <= 15 { + nibble(UInt8(encodedValue)) + } else if encodedValue <= 63 { + nibble(UInt8(encodedValue >> 4)); nibble(UInt8(encodedValue & 15)) + } else if encodedValue <= 255 { + nibble(0); nibble(UInt8(encodedValue >> 4)); nibble(UInt8(encodedValue & 15)) } else { - nibble(0); nibble(UInt8(v >> 8)); nibble(UInt8((v >> 4) & 15)); nibble(UInt8(v & 15)) + nibble(0); nibble(UInt8(encodedValue >> 8)); nibble(UInt8((encodedValue >> 4) & 15)); nibble(UInt8(encodedValue & 15)) } } - mutating func run(_ r: Int, color c: Int) { - var r = r - while r > 255 { emitRunValue(255 * 4 + c); r -= 255 } - emitRunValue(r * 4 + c) + mutating func run(_ runLength: Int, color colorIndex: Int) { + var remaining = runLength + while remaining > 255 { emitRunValue(255 * 4 + colorIndex); remaining -= 255 } + emitRunValue(remaining * 4 + colorIndex) } /// End of line: fill the remainder (possibly zero pixels) with color c. - mutating func endLine(color c: Int) { - nibble(0); nibble(0); nibble(0); nibble(UInt8(c & 3)) + mutating func endLine(color colorIndex: Int) { + nibble(0); nibble(0); nibble(0); nibble(UInt8(colorIndex & 3)) } } @@ -77,29 +77,29 @@ struct NibbleWriter { /// terminator — because the decoder treats the fill code as "paint the rest of /// the line", so an unconditional fill would be mistaken for the next line's /// first run. Short runs that end the line just use their normal code. -func encodeField(_ s: DVDSup, rows: [Int]) -> [UInt8] { - var w = NibbleWriter() +func encodeField(_ frame: DVDSup, rows: [Int]) -> [UInt8] { + var writer = NibbleWriter() for row in rows { - var x = 0 - let base = row * s.w - while x < s.w { - let c = Int(s.idx[base + x]) - var run = 1 - while x + run < s.w && Int(s.idx[base + x + run]) == c { run += 1 } - if run >= 64 && x + run == s.w { - w.endLine(color: c) // EOL fill paints the remaining pixels + var col = 0 + let rowStart = row * frame.width + while col < frame.width { + let colorIndex = Int(frame.paletteIndices[rowStart + col]) + var runLength = 1 + while col + runLength < frame.width && Int(frame.paletteIndices[rowStart + col + runLength]) == colorIndex { runLength += 1 } + if runLength >= 64 && col + runLength == frame.width { + writer.endLine(color: colorIndex) // EOL fill paints the remaining pixels } else { - w.run(run, color: c) + writer.run(runLength, color: colorIndex) } - x += run + col += runLength } - w.alignLine() + writer.alignLine() } - w.padToByte() - return w.bytes + writer.padToByte() + return writer.bytes } -// MARK: - Classic VobSub SPU (the byte-for-byte format BDSup2Sub/mkvmerge emit) +// MARK: - Classic VobSub SPU // // One SPU (this is exactly what mkvmerge stores per MKV block after stripping // the 0x20 sub-packet IDs, and what libavcodec's dvdsub decoder consumes): @@ -120,73 +120,73 @@ func encodeField(_ s: DVDSup, rows: [Int]) -> [UInt8] { // spec convention every consumer implements by ADDING them to the packet's // own timestamp (VLC parse.c: `i_start = i_pts + GetWBE(date) * 11ms`; // ffmpeg dvdsubdec: `(date << 10) / 90` ms as ASS-style relative times; -// ffmpeg dvdsubenc feeds back the relative ASS display time; BDSup2Sub's own -// output carries date 0 on the start block and the duration on the end one). +// ffmpeg dvdsubenc feeds back the relative ASS display time) // An absolute `startTicks >> 10` here re-adds the PTS to itself: VLC queues // every caption minutes past its real slot (nothing shows on screen) and // MPlayer-derived renderers clamp/drop the late ones outright. -func createSupFrame(_ s: DVDSup) -> [UInt8] { - let evenRows = stride(from: 0, to: s.h, by: 2).map { $0 } - let oddRows = stride(from: 1, to: s.h, by: 2).map { $0 } - let even = encodeField(s, rows: evenRows) - let odd = encodeField(s, rows: oddRows) - func be16(_ v: Int) -> [UInt8] { - let u = UInt16(truncatingIfNeeded: v) - return [UInt8(u >> 8), UInt8(u & 0xFF)] +func createSupFrame(_ frame: DVDSup) -> [UInt8] { + let evenRows = stride(from: 0, to: frame.height, by: 2).map { $0 } + let oddRows = stride(from: 1, to: frame.height, by: 2).map { $0 } + let evenFieldRLE = encodeField(frame, rows: evenRows) + let oddFieldRLE = encodeField(frame, rows: oddRows) + + func bigEndian16(_ value: Int) -> [UInt8] { + let bits = UInt16(truncatingIfNeeded: value) + return [UInt8(bits >> 8), UInt8(bits & 0xFF)] } - let off1 = 4 // even-field RLE start - let off2 = 4 + even.count // odd-field RLE start - let cmdPos = 4 + even.count + odd.count - let block2 = cmdPos + 24 + (s.forced ? 1 : 0) - let total = block2 + 6 - precondition(total <= 0xFFFF, "SPU larger than 64 KiB") + let evenFieldOffset = 4 // even-field RLE start + let oddFieldOffset = 4 + evenFieldRLE.count // odd-field RLE start + let commandsOffset = 4 + evenFieldRLE.count + oddFieldRLE.count + let endBlockOffset = commandsOffset + 24 + (frame.forced ? 1 : 0) + let totalSize = endBlockOffset + 6 + precondition(totalSize <= 0xFFFF, "SPU larger than 64 KiB") - var out: [UInt8] = [] - out.append(contentsOf: be16(total)) - out.append(contentsOf: be16(cmdPos)) - out.append(contentsOf: even) - out.append(contentsOf: odd) + var spuBytes: [UInt8] = [] + spuBytes.append(contentsOf: bigEndian16(totalSize)) + spuBytes.append(contentsOf: bigEndian16(commandsOffset)) + spuBytes.append(contentsOf: evenFieldRLE) + spuBytes.append(contentsOf: oddFieldRLE) // command block 1: start date = 0 (relative to packet PTS) + display params - out.append(contentsOf: be16(0)) - out.append(contentsOf: be16(block2)) // next → block 2 - out.append(0x01) // set start date + spuBytes.append(contentsOf: bigEndian16(0)) + spuBytes.append(contentsOf: bigEndian16(endBlockOffset)) // next → block 2 + spuBytes.append(0x01) // set start date // colormap identity (color n → palette row n). ffmpeg's dvdsubenc emits - // this same 32/10 layout; the jar's 03/20 is DirectVobSub's permuted + // this same 32/10 layout; the 03/20 variant is DirectVobSub's permuted // dialect (its palette rows are ordered for that). Both decode to the // intended colors in VLC/ffmpeg, which read the 32/10 form as identity. - out.append(0x03); out.append(0x32); out.append(0x10) - out.append(0x04); out.append(0xFF); out.append(0xF0) // alpha: 0 clear, 1-3 opaque - out.append(0x05) // position, 12-bit x1/x2/y1/y2 - let x2 = s.x + s.w - 1, y2 = s.y + s.h - 1 - out.append(UInt8(s.x >> 4)) - out.append(UInt8((s.x << 4) & 0xF0) | UInt8((x2 >> 8) & 0x0F)) - out.append(UInt8(x2 & 0xFF)) - out.append(UInt8(s.y >> 4)) - out.append(UInt8((s.y << 4) & 0xF0) | UInt8((y2 >> 8) & 0x0F)) - out.append(UInt8(y2 & 0xFF)) - out.append(0x06) // RLE field offsets - out.append(contentsOf: be16(off1)) - out.append(contentsOf: be16(off2)) - if s.forced { out.append(0x00) } // menu → forced flag - out.append(0xFF) // end of block + spuBytes.append(0x03); spuBytes.append(0x32); spuBytes.append(0x10) + spuBytes.append(0x04); spuBytes.append(0xFF); spuBytes.append(0xF0) // alpha: 0 clear, 1-3 opaque + spuBytes.append(0x05) // position, 12-bit x1/x2/y1/y2 + let rightEdge = frame.left + frame.width - 1, bottomEdge = frame.top + frame.height - 1 + spuBytes.append(UInt8(frame.left >> 4)) + spuBytes.append(UInt8((frame.left << 4) & 0xF0) | UInt8((rightEdge >> 8) & 0x0F)) + spuBytes.append(UInt8(rightEdge & 0xFF)) + spuBytes.append(UInt8(frame.top >> 4)) + spuBytes.append(UInt8((frame.top << 4) & 0xF0) | UInt8((bottomEdge >> 8) & 0x0F)) + spuBytes.append(UInt8(bottomEdge & 0xFF)) + spuBytes.append(0x06) // RLE field offsets + spuBytes.append(contentsOf: bigEndian16(evenFieldOffset)) + spuBytes.append(contentsOf: bigEndian16(oddFieldOffset)) + if frame.forced { spuBytes.append(0x00) } // menu → forced flag + spuBytes.append(0xFF) // end of block // command block 2: end date as display DURATION (relative to the packet // PTS, like the start word); next == own start → clean decoder exit - out.append(contentsOf: be16(Int((s.end - s.start) >> 10))) - out.append(contentsOf: be16(block2)) // self-reference - out.append(0x02) // set end date - out.append(0xFF) - precondition(out.count == total) - return out + spuBytes.append(contentsOf: bigEndian16(Int((frame.endTicks - frame.startTicks) >> 10))) + spuBytes.append(contentsOf: bigEndian16(endBlockOffset)) // self-reference + spuBytes.append(0x02) // set end date + spuBytes.append(0xFF) + precondition(spuBytes.count == totalSize) + return spuBytes } // MARK: - MPEG program-stream wrapper (.sub file container) // -// Each SPU becomes one or more 0x800-byte sectors, laid out exactly like -// BDSup2Sub's output (which mkvmerge's VobSub demuxer accepts verbatim): +// Each SPU becomes one or more 0x800-byte sectors +// (which mkvmerge's VobSub demuxer accepts verbatim): // // every sector: PACK header (14 B, constant) + PES packet // PES, 1st chunk: '00 00 01 BD' len '81 80' hdrlen=5 + 5 B PTS (payload ≤ 2020) @@ -197,19 +197,19 @@ func createSupFrame(_ s: DVDSup) -> [UInt8] { // mkvmerge strips the leading 0x20 of every payload and concatenates the rest // into the MKV block, so the SPU reassembles exactly. -let kPackHeader: [UInt8] = [0x00, 0x00, 0x01, 0xBA, 0x44, 0x02, 0xC4, 0x82, - 0x04, 0xA9, 0x01, 0x89, 0xC3, 0xF8] +let packHeaderBytes: [UInt8] = [0x00, 0x00, 0x01, 0xBA, 0x44, 0x02, 0xC4, 0x82, + 0x04, 0xA9, 0x01, 0x89, 0xC3, 0xF8] /// Standard 40-bit MPEG-2 PTS, '0011' prefix. mkvmerge cross-checks the PES /// PTS against the .idx timestamp and warns on any difference, so ticks are -/// rounded through the same milliseconds value `timeStrIdx` prints (BDSup2Sub -/// does the same: its PTS words are always ms × 90). +/// rounded through the same milliseconds value `idxTimestamp` prints +/// (its PTS words are always ms × 90). func encodePTS(_ ticks: Int64) -> [UInt8] { - let ms = (ticks + 45) / 90 - let pts = UInt64(ms * 90) & 0x1_FFFF_FFFF + let wholeMs = (ticks + 45) / 90 + let pts = UInt64(wholeMs * 90) & 0x1_FFFF_FFFF return [ // '0010' prefix nibble — mkvmerge's VobSub reader flags the textually - // correct '0011' as "PTS error" but accepts BDSup2Sub's '0010' dialect. + // correct '0011' as "PTS error" but accepts '0010' dialect. 0x21 | UInt8((pts >> 30) & 7) << 1, UInt8((pts >> 22) & 0xFF), UInt8(((pts >> 15) & 0x7F) << 1 | 1), @@ -220,127 +220,127 @@ func encodePTS(_ ticks: Int64) -> [UInt8] { struct VobSubFile { var bytes: [UInt8] - var filepos: [Int] // byte offset of each record's first sector (→ .idx) + var filePositions: [Int] // byte offset of each record's first sector (→ .idx filepos:) } -func wrapPS(_ subs: [DVDSup]) -> VobSubFile { - var out: [UInt8] = [] - var positions: [Int] = [] - for s in subs { - let spu = createSupFrame(s) +func wrapPS(_ frames: [DVDSup]) -> VobSubFile { + var fileBytes: [UInt8] = [] + var filePositions: [Int] = [] + for frame in frames { + let spu = createSupFrame(frame) // Slice the SPU into PES payloads: the first payload is 2020 bytes // (2048 − PACK 14 − PES header 14 with PTS), later ones 2025. - var chunks: [[UInt8]] = [] - var i = 0 - var maxFrag = 2020 - 1 - while i < spu.count { - chunks.append([0x20] + Array(spu[i..> 8); sec[19] = UInt8(pesLen & 0xFF) - sec[20] = 0x81 - sec[21] = ci == 0 ? 0x80 : 0x00 // PTS present only first - sec[22] = UInt8(hdrlen) - var o = 23 - if ci == 0 { - sec.replaceSubrange(o..> 8); sector[19] = UInt8(pesFieldLength & 0xFF) + sector[20] = 0x81 + sector[21] = payloadIndex == 0 ? 0x80 : 0x00 // PTS present only first + sector[22] = UInt8(headerLength) + var cursor = 23 + if payloadIndex == 0 { + sector.replaceSubrange(cursor..= 6 { - let padLen = left - 6 - sec[o] = 0x00; sec[o + 1] = 0x00; sec[o + 2] = 0x01; sec[o + 3] = 0xBE - sec[o + 4] = UInt8(padLen >> 8); sec[o + 5] = UInt8(padLen & 0xFF) + let bytesLeft = 0x800 - cursor + if bytesLeft >= 6 { + let padFieldLength = bytesLeft - 6 + sector[cursor] = 0x00; sector[cursor + 1] = 0x00; sector[cursor + 2] = 0x01; sector[cursor + 3] = 0xBE + sector[cursor + 4] = UInt8(padFieldLength >> 8); sector[cursor + 5] = UInt8(padFieldLength & 0xFF) } - out.append(contentsOf: sec) + fileBytes.append(contentsOf: sector) } } - return VobSubFile(bytes: out, filepos: positions) + return VobSubFile(bytes: fileBytes, filePositions: filePositions) } // MARK: - .idx writer -func hex6(_ c: RGBA) -> String { String(format: "%02x%02x%02x", c.r, c.g, c.b) } +func rgbHex(_ color: RGBA) -> String { String(format: "%02x%02x%02x", color.r, color.g, color.b) } -func timeStrIdx(_ ticks: Int64) -> String { - let ms = (ticks + 45) / 90 - let h = ms / 3_600_000 - let m = (ms % 3_600_000) / 60_000 - let s = (ms % 60_000) / 1000 - let mm = ms % 1000 - return String(format: "%02d:%02d:%02d:%03d", h, m, s, mm) +func idxTimestamp(_ ticks: Int64) -> String { + let totalMs = (ticks + 45) / 90 + let hours = totalMs / 3_600_000 + let minutes = (totalMs % 3_600_000) / 60_000 + let seconds = (totalMs % 60_000) / 1000 + let millis = totalMs % 1000 + return String(format: "%02d:%02d:%02d:%03d", hours, minutes, seconds, millis) } -func writeIdx(resolution: DVDResolution, palette4: [RGBA], subs: [DVDSup], - filepos: [Int], lang: String, langName: String) -> String { - var L: [String] = [] - L.append("# VobSub index file, v7 (do not modify this line!)") - L.append("# Created by sup2vob (BDSup2Sub-compatible output)") - L.append("") - L.append("# Frame size") - L.append("size: \(resolution.width)x\(resolution.height)") - L.append("") - L.append("# Origin - upper-left corner") - L.append("org: 0, 0") - L.append("") - L.append("# Scaling") - L.append("scale: 100%, 100%") - L.append("") - L.append("# Alpha blending") - L.append("alpha: 100%") - L.append("") - L.append("# Smoothing") - L.append("smooth: OFF") - L.append("") - L.append("# Fade in/out in milliseconds") - L.append("fadein/out: 0, 0") - L.append("") - L.append("# Force subtitle placement relative to (org.x, org.y)") - L.append("align: OFF at LEFT TOP") - L.append("") - L.append("# For correcting non-progressive desync. (in millisecs or hh:mm:ss:ms)") - L.append("time offset: 0") - L.append("") - L.append("# ON: displays only forced subtitles, OFF: shows everything") - L.append("forced subs: OFF") - L.append("") - L.append("# The palette of the generated file") - var pal16 = Array(repeating: RGBA.transparent, count: 16) - for (i, c) in palette4.prefix(4).enumerated() { pal16[i] = c } - L.append("palette: " + pal16.map { hex6($0) }.joined(separator: ", ")) - L.append("") - L.append("# Custom colors (transp idxs and the four colors)") - L.append("custom colors: OFF, tridx: 1000, colors: 000000, 444444, 888888, cccccc") - L.append("") - L.append("# Language index in use") - L.append("langidx: 0") - L.append("") - L.append("# \(langName)") - L.append("id: \(lang), index: 0") - L.append("# Decomment next line to activate alternative name in DirectVobSub / Windows Media Player 6.x") - L.append("# alt: \(langName)") - L.append("# Vob/Cell ID: 1, 1 (PTS: 0)") - for (k, s) in subs.enumerated() { - L.append("timestamp: \(timeStrIdx(s.start)), filepos: \(String(format: "%09x", filepos[k]))") +func writeIdx(resolution: DVDResolution, fourColorPalette: [RGBA], frames: [DVDSup], + filePositions: [Int], lang: String, langName: String) -> String { + var lines: [String] = [] + lines.append("# VobSub index file, v7 (do not modify this line!)") + lines.append("# Created by sup2vob") + lines.append("") + lines.append("# Frame size") + lines.append("size: \(resolution.width)x\(resolution.height)") + lines.append("") + lines.append("# Origin - upper-left corner") + lines.append("org: 0, 0") + lines.append("") + lines.append("# Scaling") + lines.append("scale: 100%, 100%") + lines.append("") + lines.append("# Alpha blending") + lines.append("alpha: 100%") + lines.append("") + lines.append("# Smoothing") + lines.append("smooth: OFF") + lines.append("") + lines.append("# Fade in/out in milliseconds") + lines.append("fadein/out: 0, 0") + lines.append("") + lines.append("# Force subtitle placement relative to (org.x, org.y)") + lines.append("align: OFF at LEFT TOP") + lines.append("") + lines.append("# For correcting non-progressive desync. (in millisecs or hh:mm:ss:ms)") + lines.append("time offset: 0") + lines.append("") + lines.append("# ON: displays only forced subtitles, OFF: shows everything") + lines.append("forced subs: OFF") + lines.append("") + lines.append("# The palette of the generated file") + var palette16 = Array(repeating: RGBA.transparent, count: 16) + for (slot, color) in fourColorPalette.prefix(4).enumerated() { palette16[slot] = color } + lines.append("palette: " + palette16.map { rgbHex($0) }.joined(separator: ", ")) + lines.append("") + lines.append("# Custom colors (transp idxs and the four colors)") + lines.append("custom colors: OFF, tridx: 1000, colors: 000000, 444444, 888888, cccccc") + lines.append("") + lines.append("# Language index in use") + lines.append("langidx: 0") + lines.append("") + lines.append("# \(langName)") + lines.append("id: \(lang), index: 0") + lines.append("# Decomment next line to activate alternative name in DirectVobSub / Windows Media Player 6.x") + lines.append("# alt: \(langName)") + lines.append("# Vob/Cell ID: 1, 1 (PTS: 0)") + for (frameIndex, frame) in frames.enumerated() { + lines.append("timestamp: \(idxTimestamp(frame.startTicks)), filepos: \(String(format: "%09x", filePositions[frameIndex]))") } - return L.joined(separator: "\n") + "\n" + return lines.joined(separator: "\n") + "\n" } -func writeSub(_ subs: [DVDSup]) -> VobSubFile { - wrapPS(subs) +func writeSub(_ frames: [DVDSup]) -> VobSubFile { + wrapPS(frames) } diff --git a/main.swift b/main.swift index 96a8db6..007e67f 100644 --- a/main.swift +++ b/main.swift @@ -3,8 +3,7 @@ import Foundation let usage = """ usage: sup2vob [options] -Converts a Blu-ray PGS .sup file to VobSub (.sub + .idx), the same output -shape BDSup2Sub produces — no Java required. +Converts a Blu-ray PGS .sup file to VobSub (.sub + .idx) options: -o output .sub path (a matching .idx is written beside it); @@ -12,7 +11,7 @@ options: --ntsc force a 720x480 DVD frame (default: auto from the PGS rate) --pal force a 720x576 DVD frame (default: auto from the PGS rate) --full pass through the source frame size (e.g. 1920x1080) with - no scaling — what BDSup2Sub does in HD passthrough mode + no scaling --lang two-letter language id for the .idx (default: en) --langname alternative language name for the commented alt: line (default: English) @@ -21,42 +20,42 @@ options: -h, --help show this help """ -var outPath: String? = nil +var outputPath: String? = nil var input: String? = nil -var forceRes: DVDResolution? = nil -var fullFrame = false +var forcedResolution: DVDResolution? = nil +var fullFramePassthrough = false var lang = "en" var langName = "English" -var space: ColorSpace = .bt709 +var colorSpace: ColorSpace = .bt709 var args = Array(CommandLine.arguments.dropFirst()) while !args.isEmpty { - let a = args.removeFirst() - switch a { + let arg = args.removeFirst() + switch arg { case "-h", "--help": print(usage) exit(0) case "-o": guard !args.isEmpty else { FileHandle.standardError.write("missing argument for -o\n".data(using: .utf8)!); exit(1) } - outPath = args.removeFirst() - case "--ntsc": forceRes = .ntsc - case "--pal": forceRes = .pal - case "--full": fullFrame = true + outputPath = args.removeFirst() + case "--ntsc": forcedResolution = .ntsc + case "--pal": forcedResolution = .pal + case "--full": fullFramePassthrough = true case "--lang": guard !args.isEmpty else { FileHandle.standardError.write("missing argument for --lang\n".data(using: .utf8)!); exit(1) } lang = args.removeFirst() case "--langname": guard !args.isEmpty else { FileHandle.standardError.write("missing argument for --langname\n".data(using: .utf8)!); exit(1) } langName = args.removeFirst() - case "--bt601": space = .bt601 - case "-bt601", "--bt709": space = .bt709 + case "--bt601": colorSpace = .bt601 + case "-bt601", "--bt709": colorSpace = .bt709 case "--debug": debugFrames = true default: - if a.hasPrefix("-") { - FileHandle.standardError.write("unknown option: \(a)\n".data(using: .utf8)!) + if arg.hasPrefix("-") { + FileHandle.standardError.write("unknown option: \(arg)\n".data(using: .utf8)!) exit(1) } - if input == nil { input = a } + if input == nil { input = arg } } } @@ -65,15 +64,15 @@ guard let input else { exit(1) } -guard let data = FileManager.default.contents(atPath: input) else { +guard let fileData = FileManager.default.contents(atPath: input) else { FileHandle.standardError.write("cannot read \(input)\n".data(using: .utf8)!) exit(1) } -let buf = [UInt8](data) +let fileBytes = [UInt8](fileData) -let comps: [Composition] +let compositions: [Composition] do { - comps = try readPGS(buf, space: space) + compositions = try readPGS(fileBytes, space: colorSpace) } catch let e as PGSError { FileHandle.standardError.write("\(input): \(e)\n".data(using: .utf8)!) exit(1) @@ -81,47 +80,47 @@ do { FileHandle.standardError.write("\(input): \(error)\n".data(using: .utf8)!) exit(1) } -guard !comps.isEmpty else { +guard !compositions.isEmpty else { FileHandle.standardError.write("\(input): no compositions found\n".data(using: .utf8)!) exit(1) } -let resolution = forceRes ?? (fullFrame - ? DVDResolution(width: comps[0].canvasW, height: comps[0].canvasH) - : DVDResolution.from(frameRateCode: comps[0].frameRateCode)) -let result = convertToDVD(comps, resolution: resolution) -if debugFrames, let f = result.subs.first { - let lut: [UInt8] = [0, 85, 170, 255] - var pgm = "P5\n\(f.w) \(f.h)\n255\n".data(using: .ascii)! - pgm.append(contentsOf: f.idx.map { lut[Int($0)] }) +let resolution = forcedResolution ?? (fullFramePassthrough + ? DVDResolution(width: compositions[0].canvasWidth, height: compositions[0].canvasHeight) + : DVDResolution.from(frameRateCode: compositions[0].frameRateCode)) +let result = convertToDVD(compositions, resolution: resolution) +if debugFrames, let frame = result.frames.first { + let indexToGrayLUT: [UInt8] = [0, 85, 170, 255] + var pgm = "P5\n\(frame.width) \(frame.height)\n255\n".data(using: .ascii)! + pgm.append(contentsOf: frame.paletteIndices.map { indexToGrayLUT[Int($0)] }) try? pgm.write(to: URL(fileURLWithPath: "/tmp/suptest/dbg_frame0.pgm")) - FileHandle.standardError.write("debug: frame0 idx → /tmp/suptest/dbg_frame0.pgm (\(f.w)x\(f.h) x=\(f.x) y=\(f.y))\n".data(using: .utf8)!) + FileHandle.standardError.write("debug: frame0 idx → /tmp/suptest/dbg_frame0.pgm (\(frame.width)x\(frame.height) x=\(frame.left) y=\(frame.top))\n".data(using: .utf8)!) } -guard !result.subs.isEmpty else { +guard !result.frames.isEmpty else { FileHandle.standardError.write("\(input): no displayable subtitle frames\n".data(using: .utf8)!) exit(1) } -let subPath = outPath ?? (input.hasSuffix(".sup") ? String(input.dropLast(4)) + ".sub" : input + ".sub") +let subPath = outputPath ?? (input.hasSuffix(".sup") ? String(input.dropLast(4)) + ".sub" : input + ".sub") let idxPath = (subPath as NSString).deletingPathExtension + ".idx" -let subBytes = writeSub(result.subs) -let idxText = writeIdx(resolution: resolution, palette4: result.palette4, - subs: result.subs, filepos: subBytes.filepos, +let subFile = writeSub(result.frames) +let idxText = writeIdx(resolution: resolution, fourColorPalette: result.fourColorPalette, + frames: result.frames, filePositions: subFile.filePositions, lang: lang, langName: langName) do { - try Data(subBytes.bytes).write(to: URL(fileURLWithPath: subPath)) + try Data(subFile.bytes).write(to: URL(fileURLWithPath: subPath)) try idxText.write(toFile: idxPath, atomically: true, encoding: .ascii) } catch { FileHandle.standardError.write("write failed: \(error)\n".data(using: .utf8)!) exit(1) } -let pal = result.palette4.dropFirst().filter { $0.isVisible } +let visiblePaletteHex = result.fourColorPalette.dropFirst().filter { $0.isVisible } .map { String(format: "#%02x%02x%02x", $0.r, $0.g, $0.b) }.joined(separator: " ") FileHandle.standardError.write(""" -sup2vob: \(result.subs.count) frames → \(subPath) (\(subBytes.bytes.count) bytes) + \(idxPath) - frame size \(resolution.width)x\(resolution.height), palette: \(pal) +sup2vob: \(result.frames.count) frames → \(subPath) (\(subFile.bytes.count) bytes) + \(idxPath) + frame size \(resolution.width)x\(resolution.height), palette: \(visiblePaletteHex) """.data(using: .utf8)!)