Files
MP42Foundation/MP42/Sup2Vob/PGS.swift
T
Scott GarrettandClaude Code e02f60b5f6 Import BLU-RAY PGS .sup files via vendored sup2vob
MP42VobSubImporter now claims "sup" alongside "idx": the file is converted up-front to a temp .idx/.sub pair, so the existing VobSub machinery (muxable subp passthrough, tx3g conversion, frame size from the idx size: line) carries everything downstream. The pair lives in a private temp directory until the importer's dealloc; tracks retain the importer through export, so demux can always reopen it.

The converter is sup2vob (https://git.technomancer.com/Scott-Files/sup2vob) vendored under MP42/Sup2Vob, kept identical to upstream apart from provenance headers; the CLI-only globals and main.swift are adapted in Convert.swift, and MP42SupConverter is the new @objc facade the importer calls over the MP42-Shared-Swift.h shim. Vendored output was verified byte-for-byte identical to the upstream CLI, and saved MP4s play back as dvd_subtitle tracks.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 18:18:16 -05:00

296 lines
12 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// PGS.swift
// MP42Foundation
//
// PGS (.sup) segment parser, part of the sup2vob BLU-RAY-PGS → VobSub converter
// vendored from https://git.technomancer.com/Scott-Files/sup2vob. Kept
// identical to upstream apart from this header so upstream fixes re-merge
// cleanly; see MP42SupConverter.swift for the framework entry point.
//
import Foundation
// MARK: - Basic types
struct RGBA: Equatable {
var r: UInt8 = 0
var g: UInt8 = 0
var b: UInt8 = 0
var a: UInt8 = 0
static let transparent = RGBA()
var isOpaque: Bool { a >= 128 }
var isVisible: Bool { a > 0 }
/// A pixel is drawn iff its palette alpha is at
/// least 30% (0.3 × 255 = 76.5 → ≥77). Empirically pinned against the
/// 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 isPainted: Bool { a >= 77 }
/// 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)
}
}
// MARK: - Color conversion (cloned from ColorSpaceUtils.YCbCr2RGB)
enum ColorSpace {
case bt601
case bt709
/// 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
let cr2 = Double(cr) - 128.0
let cb2 = Double(cb) - 128.0
let gain = y2 * 1.164383562
var r: Double
var g: Double
var b: Double
switch self {
case .bt601:
r = gain + 1.596026317 * cr2
g = gain - 0.8129674985 * cr2 - 0.3917615979 * cb2
b = gain + 2.017232218 * cb2
case .bt709:
r = gain + 1.792741071 * cr2
g = gain - 0.5329093286 * cr2 - 0.2132486143 * cb2
b = gain + 2.112401786 * cb2
}
func clamp(_ v: Double) -> UInt8 {
let i = Int(v + 0.5)
return UInt8(min(255, max(0, i)))
}
return (clamp(r), clamp(g), clamp(b))
}
}
// MARK: - PGS segment container (13-byte "PG" envelope, ffmpeg/mkvextract flavor)
struct PGSSegment {
var pts: UInt32 // 90 kHz PTS, written raw by ffmpeg's sup muxer
var type: UInt8
var payload: ArraySlice<UInt8>
var ptsTicks: Int64 { Int64(pts) }
}
enum PGSError: Error, CustomStringConvertible {
case truncated(String)
case badMagic
case noFrames
var description: String {
switch self {
case .truncated(let w): return "unexpected end of file while reading \(w)"
case .badMagic: return "not a PG-framed .sup file (missing \"PG\" magic)"
case .noFrames: return "no subtitle frames found"
}
}
}
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 segments
}
// MARK: - PGS payload parsing (PCS / PDS / ODS / WDS)
struct CompositionObject {
var objectID: Int
var left: Int // position on the composition canvas
var top: Int
var forced: Bool
var width: Int = 0
var height: Int = 0
var pixels: [UInt8] = [] // palette indices, row-major width*height
}
struct Palette {
var entries: [RGBA] = Array(repeating: .transparent, count: 256)
}
struct Composition {
var startTicks: Int64
var canvasWidth: Int
var canvasHeight: Int
var frameRateCode: UInt8
var objectCount: Int
var objects: [CompositionObject] = []
var palette: Palette
var isBlank: Bool { objectCount == 0 }
}
/// Parses one PDS payload: [base_id][version][ (entry_id,Y,Cr,Cb,alpha) xN ].
/// Each entry carries its **own absolute palette id** — sparse/partial updates
/// 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(_ 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)
palette.entries[entryID] = RGBA(r: r, g: g, b: b, a: alpha)
}
cursor += 5
}
}
/// 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;
/// if flags & 0x40: run = (run << 8) + next byte
/// color = (flags & 0x80) ? next byte : 0
/// 0x00 0x00 → end of line (run 0)
/// 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(_ 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 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 cursor < rleEnd else { break }
runLength = (runLength << 8) | Int(rleData[cursor])
cursor += 1
}
if flags & 0x80 != 0 { // explicit color follows the run
guard cursor < rleEnd else { color = 0; break }
color = rleData[cursor]
cursor += 1
} else {
color = 0
}
}
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 indices
}
/// Full read of a .sup file into compositions.
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: (width: Int, height: Int, rle: [UInt8])] = [:]
var pendingComposition: Composition?
var compositions: [Composition] = []
func flush() {
guard var composition = pendingComposition else { return }
pendingComposition = nil
// attach decoded objects
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)
}
}
compositions.append(composition)
}
for seg in segments {
let payload = seg.payload
switch seg.type {
case 0x16: // PCS
flush()
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 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.
cursor += (compositionFlag & 0x80) != 0 ? 16 : 8
}
pendingComposition = composition
case 0x14: // PDS
parsePaletteSegment(payload, space: space, into: &palette)
pendingComposition?.palette = palette
case 0x15: // ODS
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[objectID] != nil {
objectsByID[objectID]!.rle.append(contentsOf: payload[(payload.startIndex + 4)..<payload.endIndex])
}
} else {
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
default:
break
}
}
flush()
return compositions
}