347 lines
14 KiB
Swift
347 lines
14 KiB
Swift
import Foundation
|
||
|
||
// MARK: - VobSub RLE encoder
|
||
//
|
||
// The DVD/VobSub 2-bit RLE stream is a NIBBLE bitstream (MSB-first), matching
|
||
// ffmpeg's decode_run_2bit verbatim:
|
||
// v = 0; t = 1;
|
||
// while (v < t && t <= 0x40) { v = (v << 4) | nextNibble(); t <<= 2; }
|
||
// if (v < 4) -> "fill rest of line with color v&3"; else run = v >> 2, color = v & 3.
|
||
// The loop consumes at most FOUR nibbles (t reaches 0x100 and stops), so a run
|
||
// r with color c (value v = r*4+c) must be emitted exactly like ffmpeg's
|
||
// dvdsubenc (dvd_encode_rle):
|
||
// v <= 15 : 1 nibble (v) — run 1..3
|
||
// v <= 63 : 2 nibbles (v>>4, v&15) — run 4..15
|
||
// v <= 255 : 3 nibbles (0, v>>4, v&15) — run 16..63
|
||
// v <= 1023 : 4 nibbles (0, v>>8, (v>>4)&15, v&15) — run 64..255
|
||
// and the end-of-line fill with color c is the 4-nibble code (0,0,0,c).
|
||
// (A 5-nibble form would desynchronize: the decoder stops before the last one.)
|
||
|
||
struct NibbleWriter {
|
||
private(set) var bytes: [UInt8] = []
|
||
private var pending: UInt8? // high nibble awaiting its low nibble
|
||
|
||
mutating func nibble(_ n: UInt8) {
|
||
if let hi = pending {
|
||
bytes.append((hi << 4) | (n & 0x0F))
|
||
pending = nil
|
||
} else {
|
||
pending = n & 0x0F
|
||
}
|
||
}
|
||
|
||
/// Pad the stream to a whole byte (only meaningful once every line has
|
||
/// been terminated, i.e. at the end of the RLE stream).
|
||
mutating func padToByte() {
|
||
if let hi = pending {
|
||
bytes.append(hi << 4)
|
||
pending = nil
|
||
}
|
||
}
|
||
|
||
/// Byte-align after a line: the decoder calls align_get_bits at every end
|
||
/// of line, so a dangling half byte would desynchronize the next line.
|
||
/// Matches ffmpeg's encoder `if (ncnt & 1) PUTNIBBLE(0)`.
|
||
mutating func alignLine() {
|
||
if pending != nil { nibble(0) }
|
||
}
|
||
|
||
private mutating func emitRunValue(_ v: Int) {
|
||
precondition(v >= 4 && v <= 1023)
|
||
if v <= 15 {
|
||
nibble(UInt8(v))
|
||
} else if v <= 63 {
|
||
nibble(UInt8(v >> 4)); nibble(UInt8(v & 15))
|
||
} else if v <= 255 {
|
||
nibble(0); nibble(UInt8(v >> 4)); nibble(UInt8(v & 15))
|
||
} else {
|
||
nibble(0); nibble(UInt8(v >> 8)); nibble(UInt8((v >> 4) & 15)); nibble(UInt8(v & 15))
|
||
}
|
||
}
|
||
|
||
mutating func run(_ r: Int, color c: Int) {
|
||
var r = r
|
||
while r > 255 { emitRunValue(255 * 4 + c); r -= 255 }
|
||
emitRunValue(r * 4 + c)
|
||
}
|
||
|
||
/// End of line: fill the remainder (possibly zero pixels) with color c.
|
||
mutating func endLine(color c: Int) {
|
||
nibble(0); nibble(0); nibble(0); nibble(UInt8(c & 3))
|
||
}
|
||
}
|
||
|
||
/// Encode one interlaced field of an indexed bitmap (`rows` = source row numbers).
|
||
/// Per-run emission mirrors ffmpeg's dvd_encode_rle exactly: the end-of-line
|
||
/// fill code REPLACES a long (≥64) run that ends the line — it is not an extra
|
||
/// terminator — because the decoder treats the fill code as "paint the rest of
|
||
/// the line", so an unconditional fill would be mistaken for the next line's
|
||
/// first run. Short runs that end the line just use their normal code.
|
||
func encodeField(_ s: DVDSup, rows: [Int]) -> [UInt8] {
|
||
var w = NibbleWriter()
|
||
for row in rows {
|
||
var x = 0
|
||
let base = row * s.w
|
||
while x < s.w {
|
||
let c = Int(s.idx[base + x])
|
||
var run = 1
|
||
while x + run < s.w && Int(s.idx[base + x + run]) == c { run += 1 }
|
||
if run >= 64 && x + run == s.w {
|
||
w.endLine(color: c) // EOL fill paints the remaining pixels
|
||
} else {
|
||
w.run(run, color: c)
|
||
}
|
||
x += run
|
||
}
|
||
w.alignLine()
|
||
}
|
||
w.padToByte()
|
||
return w.bytes
|
||
}
|
||
|
||
// MARK: - Classic VobSub SPU (the byte-for-byte format BDSup2Sub/mkvmerge emit)
|
||
//
|
||
// One SPU (this is exactly what mkvmerge stores per MKV block after stripping
|
||
// the 0x20 sub-packet IDs, and what libavcodec's dvdsub decoder consumes):
|
||
//
|
||
// [0:2] BE16 size = total SPU length
|
||
// [2:4] BE16 cmd_pos = offset of the command area (RLE data ends there)
|
||
// [4:] even-field RLE (offset1 in cmd 0x06 = 4, ffmpeg reads
|
||
// [...] odd-field RLE the fields at buf+offsetN, buf = SPU start)
|
||
// cmd_pos: [BE16 date][BE16 next] cmds… FF (next → block 2)
|
||
// next: [BE16 date][BE16 next = self] 02 FF (self-reference ends the walk)
|
||
//
|
||
// Commands mirror ffmpeg's dvdsubdec.c grammar with no length-prefixed data:
|
||
// 0x01 start time (from the block's date word), 0x03 colormap, 0x04 alpha,
|
||
// 0x05 position (12-bit x1/x2/y1/y2), 0x06 BE16 RLE field offsets, 0x00 menu
|
||
// (forced), 0xFF end.
|
||
//
|
||
// The date words are 90 kHz ticks >> 10 RELATIVE to the packet PTS — the SPU
|
||
// spec convention every consumer implements by ADDING them to the packet's
|
||
// own timestamp (VLC parse.c: `i_start = i_pts + GetWBE(date) * 11ms`;
|
||
// ffmpeg dvdsubdec: `(date << 10) / 90` ms as ASS-style relative times;
|
||
// ffmpeg dvdsubenc feeds back the relative ASS display time; BDSup2Sub's own
|
||
// output carries date 0 on the start block and the duration on the end one).
|
||
// An absolute `startTicks >> 10` here re-adds the PTS to itself: VLC queues
|
||
// every caption minutes past its real slot (nothing shows on screen) and
|
||
// MPlayer-derived renderers clamp/drop the late ones outright.
|
||
func createSupFrame(_ s: DVDSup) -> [UInt8] {
|
||
let evenRows = stride(from: 0, to: s.h, by: 2).map { $0 }
|
||
let oddRows = stride(from: 1, to: s.h, by: 2).map { $0 }
|
||
let even = encodeField(s, rows: evenRows)
|
||
let odd = encodeField(s, rows: oddRows)
|
||
|
||
func be16(_ v: Int) -> [UInt8] {
|
||
let u = UInt16(truncatingIfNeeded: v)
|
||
return [UInt8(u >> 8), UInt8(u & 0xFF)]
|
||
}
|
||
|
||
let off1 = 4 // even-field RLE start
|
||
let off2 = 4 + even.count // odd-field RLE start
|
||
let cmdPos = 4 + even.count + odd.count
|
||
let block2 = cmdPos + 24 + (s.forced ? 1 : 0)
|
||
let total = block2 + 6
|
||
precondition(total <= 0xFFFF, "SPU larger than 64 KiB")
|
||
|
||
var out: [UInt8] = []
|
||
out.append(contentsOf: be16(total))
|
||
out.append(contentsOf: be16(cmdPos))
|
||
out.append(contentsOf: even)
|
||
out.append(contentsOf: odd)
|
||
|
||
// command block 1: start date = 0 (relative to packet PTS) + display params
|
||
out.append(contentsOf: be16(0))
|
||
out.append(contentsOf: be16(block2)) // next → block 2
|
||
out.append(0x01) // set start date
|
||
// colormap identity (color n → palette row n). ffmpeg's dvdsubenc emits
|
||
// this same 32/10 layout; the jar's 03/20 is DirectVobSub's permuted
|
||
// dialect (its palette rows are ordered for that). Both decode to the
|
||
// intended colors in VLC/ffmpeg, which read the 32/10 form as identity.
|
||
out.append(0x03); out.append(0x32); out.append(0x10)
|
||
out.append(0x04); out.append(0xFF); out.append(0xF0) // alpha: 0 clear, 1-3 opaque
|
||
out.append(0x05) // position, 12-bit x1/x2/y1/y2
|
||
let x2 = s.x + s.w - 1, y2 = s.y + s.h - 1
|
||
out.append(UInt8(s.x >> 4))
|
||
out.append(UInt8((s.x << 4) & 0xF0) | UInt8((x2 >> 8) & 0x0F))
|
||
out.append(UInt8(x2 & 0xFF))
|
||
out.append(UInt8(s.y >> 4))
|
||
out.append(UInt8((s.y << 4) & 0xF0) | UInt8((y2 >> 8) & 0x0F))
|
||
out.append(UInt8(y2 & 0xFF))
|
||
out.append(0x06) // RLE field offsets
|
||
out.append(contentsOf: be16(off1))
|
||
out.append(contentsOf: be16(off2))
|
||
if s.forced { out.append(0x00) } // menu → forced flag
|
||
out.append(0xFF) // end of block
|
||
|
||
// command block 2: end date as display DURATION (relative to the packet
|
||
// PTS, like the start word); next == own start → clean decoder exit
|
||
out.append(contentsOf: be16(Int((s.end - s.start) >> 10)))
|
||
out.append(contentsOf: be16(block2)) // self-reference
|
||
out.append(0x02) // set end date
|
||
out.append(0xFF)
|
||
precondition(out.count == total)
|
||
return out
|
||
}
|
||
|
||
// MARK: - MPEG program-stream wrapper (.sub file container)
|
||
//
|
||
// Each SPU becomes one or more 0x800-byte sectors, laid out exactly like
|
||
// BDSup2Sub's output (which mkvmerge's VobSub demuxer accepts verbatim):
|
||
//
|
||
// every sector: PACK header (14 B, constant) + PES packet
|
||
// PES, 1st chunk: '00 00 01 BD' len '81 80' hdrlen=5 + 5 B PTS (payload ≤ 2020)
|
||
// PES, rest: '00 00 01 BD' len '81 00' hdrlen=0 (payload ≤ 2025)
|
||
// payload = 0x20 sub-packet ID + the next slice of the SPU
|
||
// last sector: '00 00 01 BE' len + 0xFF fill to the sector end
|
||
//
|
||
// mkvmerge strips the leading 0x20 of every payload and concatenates the rest
|
||
// into the MKV block, so the SPU reassembles exactly.
|
||
|
||
let kPackHeader: [UInt8] = [0x00, 0x00, 0x01, 0xBA, 0x44, 0x02, 0xC4, 0x82,
|
||
0x04, 0xA9, 0x01, 0x89, 0xC3, 0xF8]
|
||
|
||
/// Standard 40-bit MPEG-2 PTS, '0011' prefix. mkvmerge cross-checks the PES
|
||
/// PTS against the .idx timestamp and warns on any difference, so ticks are
|
||
/// rounded through the same milliseconds value `timeStrIdx` prints (BDSup2Sub
|
||
/// does the same: its PTS words are always ms × 90).
|
||
func encodePTS(_ ticks: Int64) -> [UInt8] {
|
||
let ms = (ticks + 45) / 90
|
||
let pts = UInt64(ms * 90) & 0x1_FFFF_FFFF
|
||
return [
|
||
// '0010' prefix nibble — mkvmerge's VobSub reader flags the textually
|
||
// correct '0011' as "PTS error" but accepts BDSup2Sub's '0010' dialect.
|
||
0x21 | UInt8((pts >> 30) & 7) << 1,
|
||
UInt8((pts >> 22) & 0xFF),
|
||
UInt8(((pts >> 15) & 0x7F) << 1 | 1),
|
||
UInt8((pts >> 7) & 0xFF),
|
||
UInt8((pts & 0x7F) << 1 | 1),
|
||
]
|
||
}
|
||
|
||
struct VobSubFile {
|
||
var bytes: [UInt8]
|
||
var filepos: [Int] // byte offset of each record's first sector (→ .idx)
|
||
}
|
||
|
||
func wrapPS(_ subs: [DVDSup]) -> VobSubFile {
|
||
var out: [UInt8] = []
|
||
var positions: [Int] = []
|
||
for s in subs {
|
||
let spu = createSupFrame(s)
|
||
|
||
// Slice the SPU into PES payloads: the first payload is 2020 bytes
|
||
// (2048 − PACK 14 − PES header 14 with PTS), later ones 2025.
|
||
var chunks: [[UInt8]] = []
|
||
var i = 0
|
||
var maxFrag = 2020 - 1
|
||
while i < spu.count {
|
||
chunks.append([0x20] + Array(spu[i..<min(i + maxFrag, spu.count)]))
|
||
i += maxFrag
|
||
maxFrag = 2025 - 1
|
||
}
|
||
|
||
positions.append(out.count)
|
||
for (ci, payload) in chunks.enumerated() {
|
||
var sec = [UInt8](repeating: 0xFF, count: 0x800)
|
||
sec.replaceSubrange(0..<14, with: kPackHeader)
|
||
let hdrlen = ci == 0 ? 5 : 0
|
||
let pesLen = payload.count + 3 + hdrlen // counts the hdrlen byte
|
||
sec[14] = 0x00; sec[15] = 0x00; sec[16] = 0x01; sec[17] = 0xBD
|
||
sec[18] = UInt8(pesLen >> 8); sec[19] = UInt8(pesLen & 0xFF)
|
||
sec[20] = 0x81
|
||
sec[21] = ci == 0 ? 0x80 : 0x00 // PTS present only first
|
||
sec[22] = UInt8(hdrlen)
|
||
var o = 23
|
||
if ci == 0 {
|
||
sec.replaceSubrange(o..<o + 5, with: encodePTS(s.start))
|
||
o += 5
|
||
}
|
||
sec.replaceSubrange(o..<o + payload.count, with: payload)
|
||
o += payload.count
|
||
|
||
// padding PES (private_stream_2) fills the rest of the last sector;
|
||
// payload bytes are never truncated by our sizing.
|
||
let left = 0x800 - o
|
||
if left >= 6 {
|
||
let padLen = left - 6
|
||
sec[o] = 0x00; sec[o + 1] = 0x00; sec[o + 2] = 0x01; sec[o + 3] = 0xBE
|
||
sec[o + 4] = UInt8(padLen >> 8); sec[o + 5] = UInt8(padLen & 0xFF)
|
||
}
|
||
out.append(contentsOf: sec)
|
||
}
|
||
}
|
||
return VobSubFile(bytes: out, filepos: positions)
|
||
}
|
||
|
||
// MARK: - .idx writer
|
||
|
||
func hex6(_ c: RGBA) -> String { String(format: "%02x%02x%02x", c.r, c.g, c.b) }
|
||
|
||
func timeStrIdx(_ ticks: Int64) -> String {
|
||
let ms = (ticks + 45) / 90
|
||
let h = ms / 3_600_000
|
||
let m = (ms % 3_600_000) / 60_000
|
||
let s = (ms % 60_000) / 1000
|
||
let mm = ms % 1000
|
||
return String(format: "%02d:%02d:%02d:%03d", h, m, s, mm)
|
||
}
|
||
|
||
func writeIdx(resolution: DVDResolution, palette4: [RGBA], subs: [DVDSup],
|
||
filepos: [Int], lang: String, langName: String) -> String {
|
||
var L: [String] = []
|
||
L.append("# VobSub index file, v7 (do not modify this line!)")
|
||
L.append("# Created by sup2vob (BDSup2Sub-compatible output)")
|
||
L.append("")
|
||
L.append("# Frame size")
|
||
L.append("size: \(resolution.width)x\(resolution.height)")
|
||
L.append("")
|
||
L.append("# Origin - upper-left corner")
|
||
L.append("org: 0, 0")
|
||
L.append("")
|
||
L.append("# Scaling")
|
||
L.append("scale: 100%, 100%")
|
||
L.append("")
|
||
L.append("# Alpha blending")
|
||
L.append("alpha: 100%")
|
||
L.append("")
|
||
L.append("# Smoothing")
|
||
L.append("smooth: OFF")
|
||
L.append("")
|
||
L.append("# Fade in/out in milliseconds")
|
||
L.append("fadein/out: 0, 0")
|
||
L.append("")
|
||
L.append("# Force subtitle placement relative to (org.x, org.y)")
|
||
L.append("align: OFF at LEFT TOP")
|
||
L.append("")
|
||
L.append("# For correcting non-progressive desync. (in millisecs or hh:mm:ss:ms)")
|
||
L.append("time offset: 0")
|
||
L.append("")
|
||
L.append("# ON: displays only forced subtitles, OFF: shows everything")
|
||
L.append("forced subs: OFF")
|
||
L.append("")
|
||
L.append("# The palette of the generated file")
|
||
var pal16 = Array(repeating: RGBA.transparent, count: 16)
|
||
for (i, c) in palette4.prefix(4).enumerated() { pal16[i] = c }
|
||
L.append("palette: " + pal16.map { hex6($0) }.joined(separator: ", "))
|
||
L.append("")
|
||
L.append("# Custom colors (transp idxs and the four colors)")
|
||
L.append("custom colors: OFF, tridx: 1000, colors: 000000, 444444, 888888, cccccc")
|
||
L.append("")
|
||
L.append("# Language index in use")
|
||
L.append("langidx: 0")
|
||
L.append("")
|
||
L.append("# \(langName)")
|
||
L.append("id: \(lang), index: 0")
|
||
L.append("# Decomment next line to activate alternative name in DirectVobSub / Windows Media Player 6.x")
|
||
L.append("# alt: \(langName)")
|
||
L.append("# Vob/Cell ID: 1, 1 (PTS: 0)")
|
||
for (k, s) in subs.enumerated() {
|
||
L.append("timestamp: \(timeStrIdx(s.start)), filepos: \(String(format: "%09x", filepos[k]))")
|
||
}
|
||
return L.joined(separator: "\n") + "\n"
|
||
}
|
||
|
||
func writeSub(_ subs: [DVDSup]) -> VobSubFile {
|
||
wrapPS(subs)
|
||
}
|