Files
MP42Foundation/MP42/Sup2Vob/Convert.swift
T
Scott GarrettandClaude Code 837aa1c098 Keep the PGS source resolution through the sup2vob conversion
VobSub conversions of PGS material were downscaled to the 720x480/576
DVD frame — a 1080p source came out of the mux at one quarter of its
authored size. The framework's sup2vob façade now always runs the
upstream CLI's `--full` mode: fullFramePassthrough keeps every frame's
object geometry verbatim, and the idx size line (which the VobSub
importer carries into track.width/height and the muxer writes into the
subpic track) is the PGS's own PCS canvas, e.g. 1920x1080. The
frame-rate-derived DVD frame stays as fallback for streams that define
no usable canvas. The conversion output is byte-identical to running
`sup2vob --full` on the same .sup.

The vendored upstream sources stay untouched apart from one comment —
the passthrough is enabled in the adaptation layer, same as the CLI
does with its flag. This applies to both PGS paths, which share the
conversion: .sup drag-import and PGS-from-MKV via
MP42PgsToVobSubConverter.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 21:13:57 -05:00

280 lines
15 KiB
Swift

//
// Convert.swift
// MP42Foundation
//
// PGS composition → DVD subpicture conversion, part of the sup2vob converter
// vendored from https://git.technomancer.com/Scott-Files/sup2vob. Kept
// identical to upstream apart from this header and the two module globals the
// CLI declared in its (not vendored) main.swift; see MP42SupConverter.swift.
//
import Foundation
/// Set by `--debug`: traces per-frame decisions in convertToDVD. Nothing in
/// the framework writes these two CLI globals, hence `nonisolated(unsafe)` —
/// it keeps upstream's plain `var` semantics without the Swift concurrency
/// warning.
nonisolated(unsafe) var debugFrames = false
/// Set by the CLI's `--full`: keep the source frame size with no scaling.
/// Upstream declares this in main.swift; inside the framework
/// MP42SupConverter turns it on for every import — the muxed subpic track
/// keeps the PGS's own canvas size instead of the DVD frame.
nonisolated(unsafe) var fullFramePassthrough = false
// MARK: - DVD subtitle frame (post scale + color reduction)
struct DVDSup {
var width: Int
var height: Int
var left: Int // left offset on the DVD frame
var top: Int // top offset on the DVD frame
var startTicks: Int64 // 90 kHz ticks (real)
var endTicks: Int64 // 90 kHz ticks (real)
var forced: Bool
var paletteIndices: [UInt8] // width*height, 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 majorCode = Int(frameRateCode >> 4)
let minorCode = Int(frameRateCode & 0x0F)
if majorCode == 3 || majorCode == 5 || majorCode == 7 { return .pal }
if minorCode == 2 || minorCode == 4 || minorCode == 6 { return .pal }
return .ntsc
}
}
// MARK: - Frame assembly (objects → RGBA canvas rectangle)
/// Compose the frame's objects onto their bounding rectangle.
func composeRect(_ composition: Composition) -> (left: Int, top: Int, width: Int, height: Int, pixels: [RGBA])? {
var minX = Int.max, minY = Int.max, maxX = Int.min, maxY = Int.min
for object in composition.objects where object.width > 0 && object.height > 0 {
minX = min(minX, object.left); minY = min(minY, object.top)
maxX = max(maxX, object.left + object.width); maxY = max(maxY, object.top + object.height)
}
guard maxX > minX, maxY > minY else { return nil }
let clipLeft = max(0, minX), clipTop = max(0, minY)
let clipRight = min(composition.canvasWidth, maxX), clipBottom = min(composition.canvasHeight, maxY)
let width = clipRight - clipLeft, height = clipBottom - clipTop
guard width > 0, height > 0 else { return nil }
var pixels = Array(repeating: RGBA.transparent, count: width * height)
for object in composition.objects where object.width > 0 && object.height > 0 {
for srcY in 0..<object.height {
let dstY = object.top + srcY - clipTop
guard dstY >= 0 && dstY < height else { continue }
for srcX in 0..<object.width {
let dstX = object.left + srcX - clipLeft
guard dstX >= 0 && dstX < width else { continue }
// No color key in PGS: every index goes through the palette;
// transparency is the palette entry's alpha (undocumented
// entries default to alpha 0).
pixels[dstY * width + dstX] = composition.palette.entries[Int(object.pixels[srcY * object.width + srcX])]
}
}
}
return (clipLeft, clipTop, width, height, pixels)
}
// MARK: - Scaling (area-average filter with alpha coverage)
func scaleBox(_ source: [RGBA], _ sourceWidth: Int, _ sourceHeight: Int,
_ destWidth: Int, _ destHeight: Int) -> [RGBA] {
var output = [RGBA](repeating: .transparent, count: destWidth * destHeight)
guard destWidth > 0, destHeight > 0 else { return output }
let sourcePixelsPerDestX = Double(sourceWidth) / Double(destWidth)
let sourcePixelsPerDestY = Double(sourceHeight) / Double(destHeight)
for destY in 0..<destHeight {
let srcYStart = Int(Double(destY) * sourcePixelsPerDestY)
let srcYEnd = min(sourceHeight, max(srcYStart + 1, Int(ceil(Double(destY + 1) * sourcePixelsPerDestY))))
for destX in 0..<destWidth {
let srcXStart = Int(Double(destX) * sourcePixelsPerDestX)
let srcXEnd = min(sourceWidth, max(srcXStart + 1, Int(ceil(Double(destX + 1) * sourcePixelsPerDestX))))
var alphaWeightSum = 0.0, redSum = 0.0, greenSum = 0.0, blueSum = 0.0
for srcY in srcYStart..<srcYEnd {
let verticalCoverage = min(Double(srcYEnd), Double(srcY + 1)) - max(Double(srcYStart), Double(srcY))
for srcX in srcXStart..<srcXEnd {
let pixel = source[srcY * sourceWidth + srcX]
guard pixel.a > 0 else { continue }
let horizontalCoverage = min(Double(srcXEnd), Double(srcX + 1)) - max(Double(srcXStart), Double(srcX))
let pixelWeight = Double(pixel.a) / 255.0 * horizontalCoverage * verticalCoverage
alphaWeightSum += pixelWeight
redSum += Double(pixel.r) * pixelWeight
greenSum += Double(pixel.g) * pixelWeight
blueSum += Double(pixel.b) * pixelWeight
}
}
let destCellArea = Double(srcXEnd - srcXStart) * Double(srcYEnd - srcYStart)
guard destCellArea > 0, alphaWeightSum / destCellArea * 255.0 >= 128.0 else { continue }
// DVD has no real alpha: keep pixels whose coverage is at least half.
let totalWeight = max(alphaWeightSum, 0.0001)
let r = UInt8(min(255, max(0, Int((redSum / totalWeight).rounded()))))
let g = UInt8(min(255, max(0, Int((greenSum / totalWeight).rounded()))))
let b = UInt8(min(255, max(0, Int((blueSum / totalWeight).rounded()))))
output[destY * destWidth + destX] = RGBA(r: r, g: g, b: b, a: 255)
}
}
return output
}
// MARK: - Color reduction
func nearestColor(_ color: RGBA, among candidates: [RGBA]) -> RGBA {
var best = candidates[0], bestDistance = Int.max
for candidate in candidates {
let rDiff = Int(color.r) - Int(candidate.r)
let gDiff = Int(color.g) - Int(candidate.g)
let bDiff = Int(color.b) - Int(candidate.b)
let squaredDistance = rDiff * rDiff + gDiff * gDiff + bDiff * bDiff
if squaredDistance < bestDistance { bestDistance = squaredDistance; best = candidate }
}
return best
}
struct ConversionResult {
var frames: [DVDSup]
var fourColorPalette: [RGBA] // [0] = transparent, [1..3] = shared colors (also idx0 in the 16-slot file palette)
}
/// PGS compositions → DVD subpictures: end times, scaling, cropping, and a
/// single shared 4-color palette (VobSub's `tridx: 1000` convention makes only
/// 2-bit code 0 transparent, so all frames must share one color set).
func convertToDVD(_ compositions: [Composition], resolution targetRes: DVDResolution) -> ConversionResult {
// Non-blank compositions are frames. The next composition (blank or not)
// closes the previous frame's display time — PGS "clear screen" semantics.
var timedFrames: [(composition: Composition, endTicks: Int64)] = []
for (i, composition) in compositions.enumerated() where !composition.isBlank {
var endTicks: Int64? = nil
for j in (i + 1)..<compositions.count where compositions[j].startTicks > composition.startTicks {
endTicks = compositions[j].startTicks
break
}
timedFrames.append((composition, endTicks ?? (composition.startTicks + 2 * 90000)))
}
// pass 1: geometry + opaque pixels per frame, counting colors globally
struct PreppedFrame {
var left, top, width, height: Int
var startTicks, endTicks: Int64
var forced: Bool
var pixels: [RGBA]
}
var preppedFrames: [PreppedFrame] = []
var colorCounts: [Int: Int] = [:]
for (composition, endTicks) in timedFrames {
guard let (rectLeft, rectTop, rectWidth, rectHeight, canvasPixels) = composeRect(composition) else {
if debugFrames {
let objectWidths = composition.objects.map { String($0.width) }.joined(separator: ",")
FileHandle.standardError.write("drop t=\(composition.startTicks): composeRect nil (objs=\(composition.objects.count) widths=[\(objectWidths)])\n".data(using: .utf8)!)
}
continue
}
if fullFramePassthrough {
// Passthrough: keep the object rect verbatim — no downscale, no transparent-edge crop (its
// output frames match the source object geometry exactly).
var paddedPixels = canvasPixels
var paddedHeight = rectHeight
if rectHeight < 2 { paddedPixels += Array(repeating: .transparent, count: rectWidth); paddedHeight = 2 }
for pixel in paddedPixels where pixel.isPainted { colorCounts[pixel.packedARGB, default: 0] += 1 }
preppedFrames.append(PreppedFrame(left: rectLeft, top: rectTop, width: rectWidth, height: paddedHeight,
startTicks: composition.startTicks, endTicks: endTicks,
forced: composition.objects.contains { $0.forced }, pixels: paddedPixels))
continue
}
let scaleX = Double(targetRes.width) / Double(composition.canvasWidth)
let scaleY = Double(targetRes.height) / Double(composition.canvasHeight)
var destLeft = Int((Double(rectLeft) * scaleX).rounded())
var destTop = Int((Double(rectTop) * scaleY).rounded())
// ffmpeg's decoder needs h ≥ 2 (`w > 0 && h > 1`), so the scale target
// can never be a single row tall.
destLeft = min(max(0, destLeft), targetRes.width - 2)
destTop = min(max(0, destTop), targetRes.height - 2)
let destWidth = min(max(2, Int((Double(rectWidth) * scaleX).rounded())), targetRes.width - destLeft)
let destHeight = min(max(2, Int((Double(rectHeight) * scaleY).rounded())), targetRes.height - destTop)
guard destWidth > 0, destHeight > 0 else {
if debugFrames { FileHandle.standardError.write("drop t=\(composition.startTicks): rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight)\n".data(using: .utf8)!) }
continue
}
let scaled = scaleBox(canvasPixels, rectWidth, rectHeight, destWidth, destHeight)
// crop to the opaque bounding box
var bboxLeft = destWidth, bboxTop = destHeight, bboxRight = -1, bboxBottom = -1
for row in 0..<destHeight {
for col in 0..<destWidth where scaled[row * destWidth + col].isOpaque {
bboxLeft = min(bboxLeft, col); bboxTop = min(bboxTop, row)
bboxRight = max(bboxRight, col); bboxBottom = max(bboxBottom, row)
}
}
if bboxBottom == bboxTop { // keep ≥ 2 rows; an extra row is empty because
if bboxTop == destHeight - 1 { bboxTop -= 1 } else { bboxBottom += 1 } // bbox covered all opaque rows
}
guard bboxRight >= bboxLeft else {
if debugFrames {
let visibleCount = scaled.filter { $0.isVisible }.count
let canvasOpaqueCount = canvasPixels.filter { $0.isOpaque }.count
let objectIndexHistogram = composition.objects.map { object -> String in
var indexCounts: [Int: Int] = [:]
for pixelValue in object.pixels { indexCounts[Int(pixelValue), default: 0] += 1 }
let topEntries = indexCounts.sorted { $0.key < $1.key }.prefix(12)
.map { "\($0.key):\($0.value)" }.joined(separator: " ")
return "obj\(object.objectID)(\(object.width)x\(object.height)) [\(topEntries)]"
}.joined(separator: " ")
FileHandle.standardError.write("drop t=\(composition.startTicks): no opaque after scale (rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight), scaledVis=\(visibleCount) canvasOpaque=\(canvasOpaqueCount))\n \(objectIndexHistogram)\n".data(using: .utf8)!)
}
continue
}
let cropWidth = bboxRight - bboxLeft + 1, cropHeight = bboxBottom - bboxTop + 1
var croppedPixels = [RGBA](repeating: .transparent, count: cropWidth * cropHeight)
for row in 0..<cropHeight {
for col in 0..<cropWidth {
croppedPixels[row * cropWidth + col] = scaled[(row + bboxTop) * destWidth + (col + bboxLeft)]
}
}
destLeft += bboxLeft; destTop += bboxTop
for pixel in croppedPixels where pixel.isOpaque { colorCounts[pixel.packedARGB, default: 0] += 1 }
preppedFrames.append(PreppedFrame(left: destLeft, top: destTop, width: cropWidth, height: cropHeight,
startTicks: composition.startTicks, endTicks: endTicks,
forced: composition.objects.contains { $0.forced }, pixels: croppedPixels))
}
// pass 2: shared palette = 3 most-used colors overall
let rankedColors = colorCounts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
var colors = rankedColors.prefix(3).map { colorCount -> RGBA in
RGBA(r: UInt8((colorCount.key >> 16) & 0xFF), g: UInt8((colorCount.key >> 8) & 0xFF),
b: UInt8(colorCount.key & 0xFF), a: 255)
}
while colors.count < 3 { colors.append(.transparent) }
var frames: [DVDSup] = []
for prepped in preppedFrames {
var colorCodeByRGB: [Int: UInt8] = [:]
for (slot, color) in colors.enumerated() where color.isVisible { colorCodeByRGB[color.packedARGB] = UInt8(slot + 1) }
var paletteIndices = [UInt8](repeating: 0, count: prepped.pixels.count)
// The paint set is RGBA.isPainted (alpha-≥77 rule — see
// the fullFramePassthrough branch). The DVD path never sees sub-128 pixels here
// because scaleBox already resolved coverage to 0/255, so the
// predicates agree in both modes.
for (pixelPos, pixel) in prepped.pixels.enumerated() where pixel.isPainted {
if let code = colorCodeByRGB[pixel.packedARGB] { paletteIndices[pixelPos] = code }
else { paletteIndices[pixelPos] = UInt8((colors.firstIndex(of: nearestColor(pixel, among: colors)) ?? 0) + 1) }
}
frames.append(DVDSup(width: prepped.width, height: prepped.height, left: prepped.left, top: prepped.top,
startTicks: prepped.startTicks, endTicks: prepped.endTicks,
forced: prepped.forced, paletteIndices: paletteIndices))
}
return ConversionResult(frames: frames, fourColorPalette: [RGBA.transparent] + colors)
}