251 lines
11 KiB
Swift
251 lines
11 KiB
Swift
import Foundation
|
|
|
|
/// Set by `--debug`: traces per-frame decisions in convertToDVD.
|
|
var debugFrames = false
|
|
|
|
// MARK: - DVD subtitle frame (post scale + color reduction)
|
|
|
|
struct DVDSup {
|
|
var w: Int
|
|
var h: Int
|
|
var x: Int // left offset on the DVD frame
|
|
var y: Int // top offset on the DVD frame
|
|
var start: Int64 // 90 kHz ticks (real)
|
|
var end: Int64 // 90 kHz ticks (real)
|
|
var forced: Bool
|
|
var idx: [UInt8] // w*h, values 0..3 (index into the shared 4-color palette)
|
|
}
|
|
|
|
struct DVDResolution {
|
|
var width: Int
|
|
var height: Int
|
|
static let ntsc = DVDResolution(width: 720, height: 480)
|
|
static let pal = DVDResolution(width: 720, height: 576)
|
|
|
|
/// Picks NTSC/PAL from the PGS composition frame-rate code:
|
|
/// 0x10=23.976p 0x20=24p 0x30=25p 0x40=29.97p 0x50=50i 0x60=59.94i
|
|
/// 0x70=50p 0x80=59.94p; low codes 0x02/0x04/0x06 are 25/50-family formats.
|
|
static func from(frameRateCode: UInt8) -> DVDResolution {
|
|
let hi = Int(frameRateCode >> 4)
|
|
let lo = Int(frameRateCode & 0x0F)
|
|
if hi == 3 || hi == 5 || hi == 7 { return .pal }
|
|
if lo == 2 || lo == 4 || lo == 6 { return .pal }
|
|
return .ntsc
|
|
}
|
|
}
|
|
|
|
// MARK: - Frame assembly (objects → RGBA canvas rectangle)
|
|
|
|
/// Compose the frame's objects onto their bounding rectangle.
|
|
func composeRect(_ c: Composition) -> (x: Int, y: Int, w: Int, h: Int, rgba: [RGBA])? {
|
|
var minX = Int.max, minY = Int.max, maxX = Int.min, maxY = Int.min
|
|
for o in c.objects where o.w > 0 && o.h > 0 {
|
|
minX = min(minX, o.x); minY = min(minY, o.y)
|
|
maxX = max(maxX, o.x + o.w); maxY = max(maxY, o.y + o.h)
|
|
}
|
|
guard maxX > minX, maxY > minY else { return nil }
|
|
let x0 = max(0, minX), y0 = max(0, minY)
|
|
let x1 = min(c.canvasW, maxX), y1 = min(c.canvasH, maxY)
|
|
let w = x1 - x0, h = y1 - y0
|
|
guard w > 0, h > 0 else { return nil }
|
|
|
|
var rgba = Array(repeating: RGBA.transparent, count: w * h)
|
|
for o in c.objects where o.w > 0 && o.h > 0 {
|
|
for sy in 0..<o.h {
|
|
let dy = o.y + sy - y0
|
|
guard dy >= 0 && dy < h else { continue }
|
|
for sx in 0..<o.w {
|
|
let dx = o.x + sx - x0
|
|
guard dx >= 0 && dx < w else { continue }
|
|
// No color key in PGS: every index goes through the palette;
|
|
// transparency is the palette entry's alpha (undocumented
|
|
// entries default to alpha 0).
|
|
rgba[dy * w + dx] = c.palette.entries[Int(o.pixels[sy * o.w + sx])]
|
|
}
|
|
}
|
|
}
|
|
return (x0, y0, w, h, rgba)
|
|
}
|
|
|
|
// MARK: - Scaling (area-average filter with alpha coverage)
|
|
|
|
func scaleBox(_ src: [RGBA], _ sw: Int, _ sh: Int, _ dw: Int, _ dh: Int) -> [RGBA] {
|
|
var out = [RGBA](repeating: .transparent, count: dw * dh)
|
|
guard dw > 0, dh > 0 else { return out }
|
|
let fx = Double(sw) / Double(dw)
|
|
let fy = Double(sh) / Double(dh)
|
|
for oy in 0..<dh {
|
|
let y0 = Int(Double(oy) * fy)
|
|
let y1 = min(sh, max(y0 + 1, Int(ceil(Double(oy + 1) * fy))))
|
|
for ox in 0..<dw {
|
|
let x0 = Int(Double(ox) * fx)
|
|
let x1 = min(sw, max(x0 + 1, Int(ceil(Double(ox + 1) * fx))))
|
|
var aSum = 0.0, rSum = 0.0, gSum = 0.0, bSum = 0.0
|
|
for sy in y0..<y1 {
|
|
let wgtY = min(Double(y1), Double(sy + 1)) - max(Double(y0), Double(sy))
|
|
for sx in x0..<x1 {
|
|
let p = src[sy * sw + sx]
|
|
guard p.a > 0 else { continue }
|
|
let wgtX = min(Double(x1), Double(sx + 1)) - max(Double(x0), Double(sx))
|
|
let wa = Double(p.a) / 255.0 * wgtX * wgtY
|
|
aSum += wa
|
|
rSum += Double(p.r) * wa
|
|
gSum += Double(p.g) * wa
|
|
bSum += Double(p.b) * wa
|
|
}
|
|
}
|
|
let area = Double(x1 - x0) * Double(y1 - y0)
|
|
guard area > 0, aSum / area * 255.0 >= 128.0 else { continue }
|
|
// DVD has no real alpha: keep pixels whose coverage is at least half.
|
|
let wgt = max(aSum, 0.0001)
|
|
let r = UInt8(min(255, max(0, Int((rSum / wgt).rounded()))))
|
|
let g = UInt8(min(255, max(0, Int((gSum / wgt).rounded()))))
|
|
let b = UInt8(min(255, max(0, Int((bSum / wgt).rounded()))))
|
|
out[oy * dw + ox] = RGBA(r: r, g: g, b: b, a: 255)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// MARK: - Color reduction
|
|
|
|
func nearestColor(_ c: RGBA, among set: [RGBA]) -> RGBA {
|
|
var best = set[0], bestD = Int.max
|
|
for p in set {
|
|
let dr = Int(c.r) - Int(p.r), dg = Int(c.g) - Int(p.g), db = Int(c.b) - Int(p.b)
|
|
let d = dr * dr + dg * dg + db * db
|
|
if d < bestD { bestD = d; best = p }
|
|
}
|
|
return best
|
|
}
|
|
|
|
struct ConversionResult {
|
|
var subs: [DVDSup]
|
|
var palette4: [RGBA] // [0] = transparent, [1..3] = shared colors (also idx0 in the 16-slot file palette)
|
|
}
|
|
|
|
/// PGS compositions → DVD subpictures: end times, scaling, cropping, and a
|
|
/// single shared 4-color palette (VobSub's `tridx: 1000` convention makes only
|
|
/// 2-bit code 0 transparent, so all frames must share one color set).
|
|
func convertToDVD(_ comps: [Composition], resolution pal: DVDResolution) -> ConversionResult {
|
|
// Non-blank compositions are frames. The next composition (blank or not)
|
|
// closes the previous frame's display time — PGS "clear screen" semantics.
|
|
var frames: [(c: Composition, end: Int64)] = []
|
|
for (i, c) in comps.enumerated() where !c.isBlank {
|
|
var end: Int64? = nil
|
|
for j in (i + 1)..<comps.count where comps[j].startTicks > c.startTicks {
|
|
end = comps[j].startTicks
|
|
break
|
|
}
|
|
frames.append((c, end ?? (c.startTicks + 2 * 90000)))
|
|
}
|
|
|
|
// pass 1: geometry + opaque pixels per frame, counting colors globally
|
|
struct Prepped { var x, y, w, h: Int; var start, end: Int64; var forced: Bool; var px: [RGBA] }
|
|
var prepped: [Prepped] = []
|
|
var counts: [Int: Int] = [:]
|
|
for (c, end) in frames {
|
|
guard let (rx, ry, rw, rh, canvas) = composeRect(c) else {
|
|
if debugFrames {
|
|
let att = c.objects.map { String($0.w) }.joined(separator: ",")
|
|
FileHandle.standardError.write("drop t=\(c.startTicks): composeRect nil (objs=\(c.objects.count) widths=[\(att)])\n".data(using: .utf8)!)
|
|
}
|
|
continue
|
|
}
|
|
if fullFrame {
|
|
// Passthrough, as BDSup2Sub does at the source resolution: keep the
|
|
// object rect verbatim — no downscale, no transparent-edge crop (its
|
|
// output frames match the source object geometry exactly).
|
|
var padded = canvas
|
|
var ch = rh
|
|
if rh < 2 { padded += Array(repeating: .transparent, count: rw); ch = 2 }
|
|
// BDSup2Sub paints at alpha ≥~30% only (RGBA.jarPainted): the
|
|
// fainter half of a PGS plate (alpha ≤76) vanishes from every jar
|
|
// frame while alpha-80 gradient entries are drawn.
|
|
for p in padded where p.jarPainted { counts[p.javaRGB, default: 0] += 1 }
|
|
prepped.append(Prepped(x: rx, y: ry, w: rw, h: ch, start: c.startTicks, end: end,
|
|
forced: c.objects.contains { $0.forced }, px: padded))
|
|
continue
|
|
}
|
|
let sx = Double(pal.width) / Double(c.canvasW)
|
|
let sy = Double(pal.height) / Double(c.canvasH)
|
|
var dx = Int((Double(rx) * sx).rounded())
|
|
var dy = Int((Double(ry) * sy).rounded())
|
|
// ffmpeg's decoder needs h ≥ 2 (`w > 0 && h > 1`), so the scale target
|
|
// can never be a single row tall.
|
|
dx = min(max(0, dx), pal.width - 2)
|
|
dy = min(max(0, dy), pal.height - 2)
|
|
let dw = min(max(2, Int((Double(rw) * sx).rounded())), pal.width - dx)
|
|
let dh = min(max(2, Int((Double(rh) * sy).rounded())), pal.height - dy)
|
|
guard dw > 0, dh > 0 else {
|
|
if debugFrames { FileHandle.standardError.write("drop t=\(c.startTicks): rect=\(rx),\(ry) \(rw)x\(rh) → \(dx),\(dy) \(dw)x\(dh)\n".data(using: .utf8)!) }
|
|
continue
|
|
}
|
|
let scaled = scaleBox(canvas, rw, rh, dw, dh)
|
|
|
|
// crop to the opaque bounding box
|
|
var bx0 = dw, by0 = dh, bx1 = -1, by1 = -1
|
|
for yy in 0..<dh {
|
|
for xx in 0..<dw where scaled[yy * dw + xx].isOpaque {
|
|
bx0 = min(bx0, xx); by0 = min(by0, yy)
|
|
bx1 = max(bx1, xx); by1 = max(by1, yy)
|
|
}
|
|
}
|
|
if by1 == by0 { // keep ≥ 2 rows; an extra row is empty because
|
|
if by0 == dh - 1 { by0 -= 1 } else { by1 += 1 } // bbox covered all opaque rows
|
|
}
|
|
guard bx1 >= bx0 else {
|
|
if debugFrames {
|
|
let vis = scaled.filter { $0.isVisible }.count
|
|
let cop = canvas.filter { $0.isOpaque }.count
|
|
let hist = c.objects.map { o -> String in
|
|
var h: [Int: Int] = [:]
|
|
for v in o.pixels { h[Int(v), default: 0] += 1 }
|
|
let top = h.sorted { $0.key < $1.key }.prefix(12)
|
|
.map { "\($0.key):\($0.value)" }.joined(separator: " ")
|
|
return "obj\(o.objectID)(\(o.w)x\(o.h)) [\(top)]"
|
|
}.joined(separator: " ")
|
|
FileHandle.standardError.write("drop t=\(c.startTicks): no opaque after scale (rect=\(rx),\(ry) \(rw)x\(rh) → \(dx),\(dy) \(dw)x\(dh), scaledVis=\(vis) canvasOpaque=\(cop))\n \(hist)\n".data(using: .utf8)!)
|
|
}
|
|
continue
|
|
}
|
|
let cw = bx1 - bx0 + 1, ch = by1 - by0 + 1
|
|
var cropped = [RGBA](repeating: .transparent, count: cw * ch)
|
|
for yy in 0..<ch {
|
|
for xx in 0..<cw {
|
|
cropped[yy * cw + xx] = scaled[(yy + by0) * dw + (xx + bx0)]
|
|
}
|
|
}
|
|
dx += bx0; dy += by0
|
|
for p in cropped where p.isOpaque { counts[p.javaRGB, default: 0] += 1 }
|
|
prepped.append(Prepped(x: dx, y: dy, w: cw, h: ch, start: c.startTicks, end: end,
|
|
forced: c.objects.contains { $0.forced }, px: cropped))
|
|
}
|
|
|
|
// 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 }
|
|
var colors = sorted.prefix(3).map { kv -> RGBA in
|
|
RGBA(r: UInt8((kv.key >> 16) & 0xFF), g: UInt8((kv.key >> 8) & 0xFF),
|
|
b: UInt8(kv.key & 0xFF), a: 255)
|
|
}
|
|
while colors.count < 3 { colors.append(.transparent) }
|
|
|
|
var subs: [DVDSup] = []
|
|
for f in prepped {
|
|
var map: [Int: UInt8] = [:]
|
|
for (k, col) in colors.enumerated() where col.isVisible { map[col.javaRGB] = UInt8(k + 1) }
|
|
var idx = [UInt8](repeating: 0, count: f.px.count)
|
|
// The paint set is RGBA.jarPainted (BDSup2Sub's alpha-≥77 rule — see
|
|
// the fullFrame branch). The DVD path never sees sub-128 pixels here
|
|
// because scaleBox already resolved coverage to 0/255, so the
|
|
// predicates agree in both modes.
|
|
for (j, p) in f.px.enumerated() where p.jarPainted {
|
|
if let v = map[p.javaRGB] { idx[j] = v }
|
|
else { idx[j] = UInt8((colors.firstIndex(of: nearestColor(p, among: colors)) ?? 0) + 1) }
|
|
}
|
|
subs.append(DVDSup(w: f.w, h: f.h, x: f.x, y: f.y, start: f.start, end: f.end,
|
|
forced: f.forced, idx: idx))
|
|
}
|
|
return ConversionResult(subs: subs, palette4: [RGBA.transparent] + colors)
|
|
}
|