Initial checkin
This commit is contained in:
commit
5c40c7d7e7
5 files changed
+1031
No files matched your search
@@ -0,0 +1,281 @@
|
||||
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 }
|
||||
|
||||
/// BDSup2Sub's paint rule: 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
|
||||
/// alpha-≥80 pixel present (the file's ladder steps by 4, so the cut is
|
||||
/// proven inside (76, 80]).
|
||||
var jarPainted: Bool { a >= 77 }
|
||||
|
||||
/// 0xAARRGGBB, the layout Java ints use (Bitmap.getRGB)
|
||||
var javaRGB: 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
|
||||
|
||||
/// Verbatim arithmetic of the jar: 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 data: ArraySlice<UInt8>
|
||||
|
||||
var realTicks: 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(_ 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
|
||||
}
|
||||
return segs
|
||||
}
|
||||
|
||||
// MARK: - PGS payload parsing (PCS / PDS / ODS / WDS)
|
||||
|
||||
struct CompositionObject {
|
||||
var objectID: Int
|
||||
var x: Int
|
||||
var y: Int
|
||||
var forced: Bool
|
||||
var w: Int = 0
|
||||
var h: Int = 0
|
||||
var pixels: [UInt8] = [] // palette indices, row-major w*h
|
||||
}
|
||||
|
||||
struct Palette {
|
||||
var entries: [RGBA] = Array(repeating: .transparent, count: 256)
|
||||
}
|
||||
|
||||
struct Composition {
|
||||
var startTicks: Int64
|
||||
var canvasW: Int
|
||||
var canvasH: 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(_ 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]
|
||||
let (r, g, b) = space.ycbcrToRGB(y, cr, cb)
|
||||
pal.entries[id] = RGBA(r: r, g: g, b: b, a: alpha)
|
||||
}
|
||||
i += 5
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one PGS RLE object body into `w*h` 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(_ 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
|
||||
if color == 0 {
|
||||
guard i < end else { break }
|
||||
let flags = d[i]
|
||||
i += 1
|
||||
run = 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
|
||||
}
|
||||
if flags & 0x80 != 0 { // explicit color follows the run
|
||||
guard i < end else { color = 0; break }
|
||||
color = d[i]
|
||||
i += 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
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Full read of a .sup file into compositions.
|
||||
func readPGS(_ buf: [UInt8], space: ColorSpace) throws -> [Composition] {
|
||||
let segs = try readPGSSegments(buf)
|
||||
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] = []
|
||||
|
||||
func flush() {
|
||||
guard var c = pending else { return }
|
||||
pending = 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)
|
||||
}
|
||||
}
|
||||
frames.append(c)
|
||||
}
|
||||
|
||||
for seg in segs {
|
||||
let d = seg.data
|
||||
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]:
|
||||
// 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))
|
||||
// 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
|
||||
}
|
||||
pending = c
|
||||
case 0x14: // PDS
|
||||
parsePaletteSegment(d, space: space, into: &palette)
|
||||
pending?.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 {
|
||||
// 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])
|
||||
}
|
||||
} 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]))
|
||||
}
|
||||
case 0x17, 0x80: // WDS, END — positions come from PCS entries; ignore
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return frames
|
||||
}
|
||||
Reference in new issue
Block a user