From 5c40c7d7e7f3e58582216192c3d0374c47addf01 Mon Sep 17 00:00:00 2001 From: Scott Garrett Date: Tue, 24 Nov 2026 12:27:57 -0500 Subject: [PATCH] Initial checkin --- Convert.swift | 250 ++++++++++++++++++++++++++++++++++++ Makefile | 27 ++++ PGS.swift | 281 ++++++++++++++++++++++++++++++++++++++++ VobSub.swift | 346 ++++++++++++++++++++++++++++++++++++++++++++++++++ main.swift | 127 ++++++++++++++++++ 5 files changed, 1031 insertions(+) create mode 100644 Convert.swift create mode 100644 Makefile create mode 100644 PGS.swift create mode 100644 VobSub.swift create mode 100644 main.swift diff --git a/Convert.swift b/Convert.swift new file mode 100644 index 0000000..2a1a6d7 --- /dev/null +++ b/Convert.swift @@ -0,0 +1,250 @@ +import Foundation + +/// Set by `--debug`: traces per-frame decisions in convertToDVD. +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 forced: Bool + var idx: [UInt8] // w*h, values 0..3 (index into the shared 4-color palette) +} + +struct DVDResolution { + var width: Int + var height: Int + static let ntsc = DVDResolution(width: 720, height: 480) + static let pal = DVDResolution(width: 720, height: 576) + + /// Picks NTSC/PAL from the PGS composition frame-rate code: + /// 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 } + return .ntsc + } +} + +// 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])? { + 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) + } + 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 } + + 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 } + // 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])] + } + } + } + return (x0, y0, w, h, rgba) +} + +// 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 + } + } + let area = Double(x1 - x0) * Double(y1 - y0) + guard area > 0, aSum / area * 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) + } + } + return out +} + +// 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 } + } + return best +} + +struct ConversionResult { + var subs: [DVDSup] + var palette4: [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 { + // 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 + break + } + frames.append((c, end ?? (c.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 { + 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)!) + } + continue + } + if fullFrame { + // Passthrough, as BDSup2Sub does at the source resolution: 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)) + 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()) + // 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)!) } + continue + } + let scaled = scaleBox(canvas, rw, rh, dw, dh) + + // crop to the opaque bounding box + var bx0 = dw, by0 = dh, bx1 = -1, by1 = -1 + for yy in 0..= bx0 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) + .map { "\($0.key):\($0.value)" }.joined(separator: " ") + return "obj\(o.objectID)(\(o.w)x\(o.h)) [\(top)]" + }.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)!) + } + 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) + } + 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 + // 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) } + } + 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)) + } + return ConversionResult(subs: subs, palette4: [RGBA.transparent] + colors) +} diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3f0f629 --- /dev/null +++ b/Makefile @@ -0,0 +1,27 @@ +# sup2vob — PGS (.sup) -> VobSub (.sub/.idx) converter +# +# Build: make -> ./sup2vob +# Clean: make clean + +SWIFTC ?= swiftc +OPTFLAGS ?= -O +TARGET := sup2vob +PREFIX ?= /usr/local +SOURCES := $(wildcard *.swift) + +.PHONY: all clean rebuild install + +all: $(TARGET) + +$(TARGET): $(SOURCES) + $(SWIFTC) $(OPTFLAGS) -o $(TARGET) $(SOURCES) + +clean: + rm -f $(TARGET) + +rebuild: clean all + +# extractsubs resolves sup2vob from PATH, so a rebuild only takes effect once +# installed (usually: sudo make install). +install: $(TARGET) + install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin/$(TARGET) diff --git a/PGS.swift b/PGS.swift new file mode 100644 index 0000000..86bf867 --- /dev/null +++ b/PGS.swift @@ -0,0 +1,281 @@ +import Foundation + +// MARK: - Basic types + +struct RGBA: Equatable { + var r: UInt8 = 0 + var g: UInt8 = 0 + var b: UInt8 = 0 + var a: UInt8 = 0 + + static let transparent = RGBA() + + var isOpaque: Bool { a >= 128 } + var isVisible: Bool { a > 0 } + + /// BDSup2Sub's paint rule: 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 + /// alpha-≥80 pixel present (the file's ladder steps by 4, so the cut is + /// proven inside (76, 80]). + var jarPainted: Bool { a >= 77 } + + /// 0xAARRGGBB, the layout Java ints use (Bitmap.getRGB) + var javaRGB: Int { + (Int(a) << 24) | (Int(r) << 16) | (Int(g) << 8) | Int(b) + } +} + +// MARK: - Color conversion (cloned from ColorSpaceUtils.YCbCr2RGB) + +enum ColorSpace { + case bt601 + case bt709 + + /// Verbatim arithmetic of the jar: 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 + let cr2 = Double(cr) - 128.0 + let cb2 = Double(cb) - 128.0 + let gain = y2 * 1.164383562 + var r: Double + var g: Double + var b: Double + switch self { + case .bt601: + r = gain + 1.596026317 * cr2 + g = gain - 0.8129674985 * cr2 - 0.3917615979 * cb2 + b = gain + 2.017232218 * cb2 + case .bt709: + r = gain + 1.792741071 * cr2 + g = gain - 0.5329093286 * cr2 - 0.2132486143 * cb2 + b = gain + 2.112401786 * cb2 + } + func clamp(_ v: Double) -> UInt8 { + let i = Int(v + 0.5) + return UInt8(min(255, max(0, i))) + } + return (clamp(r), clamp(g), clamp(b)) + } +} + +// MARK: - PGS segment container (13-byte "PG" envelope, ffmpeg/mkvextract flavor) + +struct PGSSegment { + var pts: UInt32 // 90 kHz PTS, written raw by ffmpeg's sup muxer + var type: UInt8 + var data: ArraySlice + + var realTicks: Int64 { Int64(pts) } +} + +enum PGSError: Error, CustomStringConvertible { + case truncated(String) + case badMagic + case noFrames + + var description: String { + switch self { + case .truncated(let w): return "unexpected end of file while reading \(w)" + case .badMagic: return "not a PG-framed .sup file (missing \"PG\" magic)" + case .noFrames: return "no subtitle frames found" + } + } +} + +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 + } + return segs +} + +// MARK: - PGS payload parsing (PCS / PDS / ODS / WDS) + +struct CompositionObject { + var objectID: Int + var x: Int + var y: Int + var forced: Bool + var w: Int = 0 + var h: Int = 0 + var pixels: [UInt8] = [] // palette indices, row-major w*h +} + +struct Palette { + var entries: [RGBA] = Array(repeating: .transparent, count: 256) +} + +struct Composition { + var startTicks: Int64 + var canvasW: Int + var canvasH: Int + var frameRateCode: UInt8 + var objectCount: Int + var objects: [CompositionObject] = [] + var palette: Palette + var isBlank: Bool { objectCount == 0 } +} + +/// Parses one PDS payload: [base_id][version][ (entry_id,Y,Cr,Cb,alpha) xN ]. +/// Each entry carries its **own absolute palette id** — sparse/partial updates +/// 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] + let (r, g, b) = space.ycbcrToRGB(y, cr, cb) + pal.entries[id] = RGBA(r: r, g: g, b: b, a: alpha) + } + i += 5 + } +} + +/// Decodes one PGS RLE object body into `w*h` 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; +/// if flags & 0x40: run = (run << 8) + next byte +/// color = (flags & 0x80) ? next byte : 0 +/// 0x00 0x00 → end of line (run 0) +/// 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 + if color == 0 { + guard i < end else { break } + let flags = d[i] + i += 1 + run = 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 + } + if flags & 0x80 != 0 { // explicit color follows the run + guard i < end else { color = 0; break } + color = d[i] + i += 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 + } + } + return out +} + +/// Full read of a .sup file into compositions. +func readPGS(_ buf: [UInt8], space: ColorSpace) throws -> [Composition] { + let segs = try readPGSSegments(buf) + 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] = [] + + func flush() { + guard var c = pending else { return } + pending = 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) + } + } + frames.append(c) + } + + for seg in segs { + let d = seg.data + 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.. 4 else { break } + let id = Int(d[d.startIndex]) << 8 | Int(d[d.startIndex + 1]) + if d[d.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).. "fill rest of line with color v&3"; else run = v >> 2, color = v & 3. +// The loop consumes at most FOUR nibbles (t reaches 0x100 and stops), so a run +// r with color c (value v = r*4+c) must be emitted exactly like ffmpeg's +// dvdsubenc (dvd_encode_rle): +// v <= 15 : 1 nibble (v) — run 1..3 +// v <= 63 : 2 nibbles (v>>4, v&15) — run 4..15 +// v <= 255 : 3 nibbles (0, v>>4, v&15) — run 16..63 +// v <= 1023 : 4 nibbles (0, v>>8, (v>>4)&15, v&15) — run 64..255 +// and the end-of-line fill with color c is the 4-nibble code (0,0,0,c). +// (A 5-nibble form would desynchronize: the decoder stops before the last one.) + +struct NibbleWriter { + private(set) var bytes: [UInt8] = [] + private var pending: UInt8? // high nibble awaiting its low nibble + + mutating func nibble(_ n: UInt8) { + if let hi = pending { + bytes.append((hi << 4) | (n & 0x0F)) + pending = nil + } else { + pending = n & 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 + } + } + + /// Byte-align after a line: the decoder calls align_get_bits at every end + /// 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) } + } + + 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)) + } else { + nibble(0); nibble(UInt8(v >> 8)); nibble(UInt8((v >> 4) & 15)); nibble(UInt8(v & 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) + } + + /// 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)) + } +} + +/// Encode one interlaced field of an indexed bitmap (`rows` = source row numbers). +/// Per-run emission mirrors ffmpeg's dvd_encode_rle exactly: the end-of-line +/// fill code REPLACES a long (≥64) run that ends the line — it is not an extra +/// 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() + 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 + } else { + w.run(run, color: c) + } + x += run + } + w.alignLine() + } + w.padToByte() + return w.bytes +} + +// MARK: - Classic VobSub SPU (the byte-for-byte format BDSup2Sub/mkvmerge emit) +// +// 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): +// +// [0:2] BE16 size = total SPU length +// [2:4] BE16 cmd_pos = offset of the command area (RLE data ends there) +// [4:] even-field RLE (offset1 in cmd 0x06 = 4, ffmpeg reads +// [...] odd-field RLE the fields at buf+offsetN, buf = SPU start) +// cmd_pos: [BE16 date][BE16 next] cmds… FF (next → block 2) +// next: [BE16 date][BE16 next = self] 02 FF (self-reference ends the walk) +// +// Commands mirror ffmpeg's dvdsubdec.c grammar with no length-prefixed data: +// 0x01 start time (from the block's date word), 0x03 colormap, 0x04 alpha, +// 0x05 position (12-bit x1/x2/y1/y2), 0x06 BE16 RLE field offsets, 0x00 menu +// (forced), 0xFF end. +// +// The date words are 90 kHz ticks >> 10 RELATIVE to the packet PTS — the SPU +// 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). +// 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)] + } + + 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") + + var out: [UInt8] = [] + out.append(contentsOf: be16(total)) + out.append(contentsOf: be16(cmdPos)) + out.append(contentsOf: even) + out.append(contentsOf: odd) + + // 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 + // 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 + // 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 + + // 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 +} + +// 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): +// +// 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) +// PES, rest: '00 00 01 BD' len '81 00' hdrlen=0 (payload ≤ 2025) +// payload = 0x20 sub-packet ID + the next slice of the SPU +// last sector: '00 00 01 BE' len + 0xFF fill to the sector end +// +// 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] + +/// 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). +func encodePTS(_ ticks: Int64) -> [UInt8] { + let ms = (ticks + 45) / 90 + let pts = UInt64(ms * 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. + 0x21 | UInt8((pts >> 30) & 7) << 1, + UInt8((pts >> 22) & 0xFF), + UInt8(((pts >> 15) & 0x7F) << 1 | 1), + UInt8((pts >> 7) & 0xFF), + UInt8((pts & 0x7F) << 1 | 1), + ] +} + +struct VobSubFile { + var bytes: [UInt8] + var filepos: [Int] // byte offset of each record's first sector (→ .idx) +} + +func wrapPS(_ subs: [DVDSup]) -> VobSubFile { + var out: [UInt8] = [] + var positions: [Int] = [] + for s in subs { + let spu = createSupFrame(s) + + // 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..= 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) + } + out.append(contentsOf: sec) + } + } + return VobSubFile(bytes: out, filepos: positions) +} + +// MARK: - .idx writer + +func hex6(_ c: RGBA) -> String { String(format: "%02x%02x%02x", c.r, c.g, c.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 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]))") + } + return L.joined(separator: "\n") + "\n" +} + +func writeSub(_ subs: [DVDSup]) -> VobSubFile { + wrapPS(subs) +} diff --git a/main.swift b/main.swift new file mode 100644 index 0000000..96a8db6 --- /dev/null +++ b/main.swift @@ -0,0 +1,127 @@ +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. + +options: + -o output .sub path (a matching .idx is written beside it); + default: with .sup replaced by .sub + --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 + --lang two-letter language id for the .idx (default: en) + --langname alternative language name for the commented alt: line + (default: English) + --bt601 interpret the PGS palette as BT.601 (default: BT.709) + --debug trace per-frame conversion decisions on stderr + -h, --help show this help +""" + +var outPath: String? = nil +var input: String? = nil +var forceRes: DVDResolution? = nil +var fullFrame = false +var lang = "en" +var langName = "English" +var space: ColorSpace = .bt709 + +var args = Array(CommandLine.arguments.dropFirst()) +while !args.isEmpty { + let a = args.removeFirst() + switch a { + 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 + 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 "--debug": debugFrames = true + default: + if a.hasPrefix("-") { + FileHandle.standardError.write("unknown option: \(a)\n".data(using: .utf8)!) + exit(1) + } + if input == nil { input = a } + } +} + +guard let input else { + FileHandle.standardError.write(usage.data(using: .utf8)!) + exit(1) +} + +guard let data = FileManager.default.contents(atPath: input) else { + FileHandle.standardError.write("cannot read \(input)\n".data(using: .utf8)!) + exit(1) +} +let buf = [UInt8](data) + +let comps: [Composition] +do { + comps = try readPGS(buf, space: space) +} catch let e as PGSError { + FileHandle.standardError.write("\(input): \(e)\n".data(using: .utf8)!) + exit(1) +} catch { + FileHandle.standardError.write("\(input): \(error)\n".data(using: .utf8)!) + exit(1) +} +guard !comps.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)] }) + 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)!) +} +guard !result.subs.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 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, + lang: lang, langName: langName) + +do { + try Data(subBytes.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 } + .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) + +""".data(using: .utf8)!)