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

+117 -113
View File
@@ -13,15 +13,15 @@ struct RGBA: Equatable {
var isOpaque: Bool { a >= 128 }
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
/// 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
/// proven inside (76, 80]).
var jarPainted: Bool { a >= 77 }
var isPainted: Bool { a >= 77 }
/// 0xAARRGGBB, the layout Java ints use (Bitmap.getRGB)
var javaRGB: Int {
/// 0xAARRGGBB packed into an Int — stable color key for the histograms/maps
var packedARGB: Int {
(Int(a) << 24) | (Int(r) << 16) | (Int(g) << 8) | Int(b)
}
}
@@ -32,7 +32,7 @@ enum ColorSpace {
case bt601
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.
func ycbcrToRGB(_ y: Int, _ cr: Int, _ cb: Int) -> (r: UInt8, g: UInt8, b: UInt8) {
let y2 = Double(y) - 16.0
@@ -65,9 +65,9 @@ enum ColorSpace {
struct PGSSegment {
var pts: UInt32 // 90 kHz PTS, written raw by ffmpeg's sup muxer
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 {
@@ -84,33 +84,34 @@ enum PGSError: Error, CustomStringConvertible {
}
}
func readPGSSegments(_ buf: [UInt8]) throws -> [PGSSegment] {
var segs: [PGSSegment] = []
var off = 0
while off < buf.count {
guard off + 13 <= buf.count else { throw PGSError.truncated("segment header") }
guard buf[off] == 0x50, buf[off + 1] == 0x47 else { throw PGSError.badMagic }
let pts = (UInt32(buf[off + 2]) << 24) | (UInt32(buf[off + 3]) << 16)
| (UInt32(buf[off + 4]) << 8) | UInt32(buf[off + 5])
let type = buf[off + 10]
let len = Int(buf[off + 11]) << 8 | Int(buf[off + 12])
guard off + 13 + len <= buf.count else { throw PGSError.truncated("segment body") }
segs.append(PGSSegment(pts: pts, type: type, data: buf[(off + 13)..<(off + 13 + len)]))
off += 13 + len
func readPGSSegments(_ fileBytes: [UInt8]) throws -> [PGSSegment] {
var segments: [PGSSegment] = []
var offset = 0
while offset < fileBytes.count {
guard offset + 13 <= fileBytes.count else { throw PGSError.truncated("segment header") }
guard fileBytes[offset] == 0x50, fileBytes[offset + 1] == 0x47 else { throw PGSError.badMagic }
let pts = (UInt32(fileBytes[offset + 2]) << 24) | (UInt32(fileBytes[offset + 3]) << 16)
| (UInt32(fileBytes[offset + 4]) << 8) | UInt32(fileBytes[offset + 5])
let segmentType = fileBytes[offset + 10]
let payloadLength = Int(fileBytes[offset + 11]) << 8 | Int(fileBytes[offset + 12])
guard offset + 13 + payloadLength <= fileBytes.count else { throw PGSError.truncated("segment body") }
segments.append(PGSSegment(pts: pts, type: segmentType,
payload: fileBytes[(offset + 13)..<(offset + 13 + payloadLength)]))
offset += 13 + payloadLength
}
return segs
return segments
}
// MARK: - PGS payload parsing (PCS / PDS / ODS / WDS)
struct CompositionObject {
var objectID: Int
var x: Int
var y: Int
var left: Int // position on the composition canvas
var top: Int
var forced: Bool
var w: Int = 0
var h: Int = 0
var pixels: [UInt8] = [] // palette indices, row-major w*h
var width: Int = 0
var height: Int = 0
var pixels: [UInt8] = [] // palette indices, row-major width*height
}
struct Palette {
@@ -119,8 +120,8 @@ struct Palette {
struct Composition {
var startTicks: Int64
var canvasW: Int
var canvasH: Int
var canvasWidth: Int
var canvasHeight: Int
var frameRateCode: UInt8
var objectCount: Int
var objects: [CompositionObject] = []
@@ -133,23 +134,23 @@ struct Composition {
/// are common, so entries must be written at their id, not packed sequentially
/// (that bug mapped glyph colors onto uninitialized slots and blanked frames).
/// Entries below the segment's base id are skipped, matching ffmpeg.
func parsePaletteSegment(_ d: ArraySlice<UInt8>, space: ColorSpace, into pal: inout Palette) {
guard d.count >= 2 else { return }
let base = Int(d[d.startIndex])
var i = d.startIndex + 2
while i + 4 < d.endIndex {
let id = Int(d[i])
if id >= base, id < 256 {
let y = Int(d[i + 1]), cr = Int(d[i + 2]), cb = Int(d[i + 3])
let alpha = d[i + 4]
func parsePaletteSegment(_ segmentData: ArraySlice<UInt8>, space: ColorSpace, into palette: inout Palette) {
guard segmentData.count >= 2 else { return }
let baseEntryID = Int(segmentData[segmentData.startIndex])
var cursor = segmentData.startIndex + 2
while cursor + 4 < segmentData.endIndex {
let entryID = Int(segmentData[cursor])
if entryID >= baseEntryID, entryID < 256 {
let y = Int(segmentData[cursor + 1]), cr = Int(segmentData[cursor + 2]), cb = Int(segmentData[cursor + 3])
let alpha = segmentData[cursor + 4]
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:
/// color byte 0xNN (NN != 0) → 1 pixel of color NN
/// 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
/// low indices. Filling is LINEAR (ffmpeg does not snap to line starts on EOL
/// markers; it only counts them), so a miscounted row cannot cascade.
func decodePGSORLE(_ d: ArraySlice<UInt8>, w: Int, h: Int) -> [UInt8] {
let total = w * h
var out = [UInt8](repeating: 0, count: total)
var i = d.startIndex
let end = d.endIndex
var n = 0 // ffmpeg's pixel_count (linear position in the bitmap)
var line = 0
while i < end, line < h {
var color = d[i]
i += 1
var run = 1
func decodePGSORLE(_ rleData: ArraySlice<UInt8>, width: Int, height: Int) -> [UInt8] {
let pixelCount = width * height
var indices = [UInt8](repeating: 0, count: pixelCount)
var cursor = rleData.startIndex
let rleEnd = rleData.endIndex
var linearPos = 0 // ffmpeg's pixel_count (linear position in the bitmap)
var endOfLineCount = 0
while cursor < rleEnd, endOfLineCount < height {
var color = rleData[cursor]
cursor += 1
var runLength = 1
if color == 0 {
guard i < end else { break }
let flags = d[i]
i += 1
run = Int(flags & 0x3F)
guard cursor < rleEnd else { break }
let flags = rleData[cursor]
cursor += 1
runLength = Int(flags & 0x3F)
if flags & 0x40 != 0 { // 14-bit run: low 6 in flags, high 8 next
guard i < end else { break }
run = (run << 8) | Int(d[i])
i += 1
guard cursor < rleEnd else { break }
runLength = (runLength << 8) | Int(rleData[cursor])
cursor += 1
}
if flags & 0x80 != 0 { // explicit color follows the run
guard i < end else { color = 0; break }
color = d[i]
i += 1
guard cursor < rleEnd else { color = 0; break }
color = rleData[cursor]
cursor += 1
} else {
color = 0
}
}
if run > 0, n + run <= total {
for k in n..<(n + run) { out[k] = color }
n += run
} else if run == 0 {
line += 1 // end of line; ffmpeg keeps the linear write head
if runLength > 0, linearPos + runLength <= pixelCount {
for pos in linearPos..<(linearPos + runLength) { indices[pos] = color }
linearPos += runLength
} else if runLength == 0 {
endOfLineCount += 1 // end of line; ffmpeg keeps the linear write head
}
}
return out
return indices
}
/// Full read of a .sup file into compositions.
func readPGS(_ buf: [UInt8], space: ColorSpace) throws -> [Composition] {
let segs = try readPGSSegments(buf)
func readPGS(_ fileBytes: [UInt8], space: ColorSpace) throws -> [Composition] {
let segments = try readPGSSegments(fileBytes)
var palette = Palette()
// Raw RLE per object id — objects can arrive split across several ODS
// segments (continuations append payload), so decoding is deferred to
// composition time, exactly like ffmpeg's object buffering.
var objectsByID: [Int: (w: Int, h: Int, rle: [UInt8])] = [:]
var pending: Composition?
var frames: [Composition] = []
var objectsByID: [Int: (width: Int, height: Int, rle: [UInt8])] = [:]
var pendingComposition: Composition?
var compositions: [Composition] = []
func flush() {
guard var c = pending else { return }
pending = nil
guard var composition = pendingComposition else { return }
pendingComposition = nil
// attach decoded objects
for i in c.objects.indices {
if let o = objectsByID[c.objects[i].objectID] {
c.objects[i].w = o.w
c.objects[i].h = o.h
c.objects[i].pixels = decodePGSORLE(ArraySlice(o.rle), w: o.w, h: o.h)
for i in composition.objects.indices {
if let stored = objectsByID[composition.objects[i].objectID] {
composition.objects[i].width = stored.width
composition.objects[i].height = stored.height
composition.objects[i].pixels = decodePGSORLE(ArraySlice(stored.rle),
width: stored.width, height: stored.height)
}
}
frames.append(c)
compositions.append(composition)
}
for seg in segs {
let d = seg.data
for seg in segments {
let payload = seg.payload
switch seg.type {
case 0x16: // PCS
flush()
guard d.count >= 11 else { break }
let w = Int(d[d.startIndex]) << 8 | Int(d[d.startIndex + 1])
let h = Int(d[d.startIndex + 2]) << 8 | Int(d[d.startIndex + 3])
let fps = d[d.startIndex + 4]
let objCount = Int(d[d.startIndex + 10])
var c = Composition(startTicks: seg.realTicks, canvasW: w, canvasH: h,
frameRateCode: fps, objectCount: objCount, palette: palette)
var i = d.startIndex + 11
for _ in 0..<objCount where i + 7 < d.endIndex {
let id = Int(d[i]) << 8 | Int(d[i + 1])
// (d[i+2] is window_id) composition_flag at d[i+3]:
guard payload.count >= 11 else { break }
let canvasWidth = Int(payload[payload.startIndex]) << 8 | Int(payload[payload.startIndex + 1])
let canvasHeight = Int(payload[payload.startIndex + 2]) << 8 | Int(payload[payload.startIndex + 3])
let frameRateCode = payload[payload.startIndex + 4]
let objectCount = Int(payload[payload.startIndex + 10])
var composition = Composition(startTicks: seg.ptsTicks, canvasWidth: canvasWidth, canvasHeight: canvasHeight,
frameRateCode: frameRateCode, objectCount: objectCount, palette: palette)
var cursor = payload.startIndex + 11
for _ in 0..<objectCount where cursor + 7 < payload.endIndex {
let objectID = Int(payload[cursor]) << 8 | Int(payload[cursor + 1])
// (payload[cursor+2] is window_id) composition_flag at cursor+3:
// 0x80 crop fields follow, 0x40 forced
let flag = Int(d[i + 3])
let forced = (flag & 0x40) != 0
let x = Int(d[i + 4]) << 8 | Int(d[i + 5])
let y = Int(d[i + 6]) << 8 | Int(d[i + 7])
c.objects.append(CompositionObject(objectID: id, x: x, y: y, forced: forced))
let compositionFlag = Int(payload[cursor + 3])
let forced = (compositionFlag & 0x40) != 0
let objectX = Int(payload[cursor + 4]) << 8 | Int(payload[cursor + 5])
let objectY = Int(payload[cursor + 6]) << 8 | Int(payload[cursor + 7])
composition.objects.append(CompositionObject(objectID: objectID, left: objectX, top: objectY,
forced: forced))
// ffmpeg draws the whole object regardless of the crop rect,
// but a cropped entry's record is 12 bytes and must be skipped
// 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
parsePaletteSegment(d, space: space, into: &palette)
pending?.palette = palette
parsePaletteSegment(payload, space: space, into: &palette)
pendingComposition?.palette = palette
case 0x15: // ODS
guard d.count > 4 else { break }
let id = Int(d[d.startIndex]) << 8 | Int(d[d.startIndex + 1])
if d[d.startIndex + 3] & 0x80 == 0 {
guard payload.count > 4 else { break }
let objectID = Int(payload[payload.startIndex]) << 8 | Int(payload[payload.startIndex + 1])
if payload[payload.startIndex + 3] & 0x80 == 0 {
// Continuation segment (seqdesc high bit clear): payload
// starts at +4 and extends the object's stored RLE data —
// exactly ffmpeg's parse_object_segment append path.
if objectsByID[id] != nil {
objectsByID[id]!.rle.append(contentsOf: d[(d.startIndex + 4)..<d.endIndex])
if objectsByID[objectID] != nil {
objectsByID[objectID]!.rle.append(contentsOf: payload[(payload.startIndex + 4)..<payload.endIndex])
}
} else {
guard d.count >= 11 else { break }
let w = Int(d[d.startIndex + 7]) << 8 | Int(d[d.startIndex + 8])
let h = Int(d[d.startIndex + 9]) << 8 | Int(d[d.startIndex + 10])
objectsByID[id] = (w, h, Array(d[(d.startIndex + 11)..<d.endIndex]))
guard payload.count >= 11 else { break }
let objectWidth = Int(payload[payload.startIndex + 7]) << 8 | Int(payload[payload.startIndex + 8])
let objectHeight = Int(payload[payload.startIndex + 9]) << 8 | Int(payload[payload.startIndex + 10])
objectsByID[objectID] = (objectWidth, objectHeight,
Array(payload[(payload.startIndex + 11)..<payload.endIndex]))
}
case 0x17, 0x80: // WDS, END — positions come from PCS entries; ignore
break
@@ -277,5 +281,5 @@ func readPGS(_ buf: [UInt8], space: ColorSpace) throws -> [Composition] {
}
}
flush()
return frames
return compositions
}