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 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..= 0 && dstY < height else { continue } for srcX in 0..= 0 && dstX < width else { continue } // No color key in PGS: every index goes through the palette; // transparency is the palette entry's alpha (undocumented // entries default to alpha 0). 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.. 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).. 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..= 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.. $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) }