More variable renaming and comment cleanup.

This commit is contained in:
Scott Garrett committed 2026-11-24 13:04:37 -05:00
1 parent 5c40c7d7e7
commit 51120481e2
5 files changed
+512 -496

No files matched your search

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