Files

347 lines
16 KiB
Swift
Raw Permalink 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.
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 pendingHighNibble: UInt8? // high nibble awaiting its low nibble
mutating func nibble(_ value: UInt8) {
if let high = pendingHighNibble {
bytes.append((high << 4) | (value & 0x0F))
pendingHighNibble = nil
} else {
pendingHighNibble = value & 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 high = pendingHighNibble {
bytes.append(high << 4)
pendingHighNibble = 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 pendingHighNibble != nil { nibble(0) }
}
private mutating func emitRunValue(_ encodedValue: Int) {
precondition(encodedValue >= 4 && encodedValue <= 1023)
if encodedValue <= 15 {
nibble(UInt8(encodedValue))
} else if encodedValue <= 63 {
nibble(UInt8(encodedValue >> 4)); nibble(UInt8(encodedValue & 15))
} else if encodedValue <= 255 {
nibble(0); nibble(UInt8(encodedValue >> 4)); nibble(UInt8(encodedValue & 15))
} else {
nibble(0); nibble(UInt8(encodedValue >> 8)); nibble(UInt8((encodedValue >> 4) & 15)); nibble(UInt8(encodedValue & 15))
}
}
mutating func run(_ runLength: Int, color colorIndex: Int) {
var remaining = runLength
while remaining > 255 { emitRunValue(255 * 4 + colorIndex); remaining -= 255 }
emitRunValue(remaining * 4 + colorIndex)
}
/// End of line: fill the remainder (possibly zero pixels) with color c.
mutating func endLine(color colorIndex: Int) {
nibble(0); nibble(0); nibble(0); nibble(UInt8(colorIndex & 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(_ frame: DVDSup, rows: [Int]) -> [UInt8] {
var writer = NibbleWriter()
for row in rows {
var col = 0
let rowStart = row * frame.width
while col < frame.width {
let colorIndex = Int(frame.paletteIndices[rowStart + col])
var runLength = 1
while col + runLength < frame.width && Int(frame.paletteIndices[rowStart + col + runLength]) == colorIndex { runLength += 1 }
if runLength >= 64 && col + runLength == frame.width {
writer.endLine(color: colorIndex) // EOL fill paints the remaining pixels
} else {
writer.run(runLength, color: colorIndex)
}
col += runLength
}
writer.alignLine()
}
writer.padToByte()
return writer.bytes
}
// MARK: - Classic VobSub SPU
//
// 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)
// 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(_ frame: DVDSup) -> [UInt8] {
let evenRows = stride(from: 0, to: frame.height, by: 2).map { $0 }
let oddRows = stride(from: 1, to: frame.height, by: 2).map { $0 }
let evenFieldRLE = encodeField(frame, rows: evenRows)
let oddFieldRLE = encodeField(frame, rows: oddRows)
func bigEndian16(_ value: Int) -> [UInt8] {
let bits = UInt16(truncatingIfNeeded: value)
return [UInt8(bits >> 8), UInt8(bits & 0xFF)]
}
let evenFieldOffset = 4 // even-field RLE start
let oddFieldOffset = 4 + evenFieldRLE.count // odd-field RLE start
let commandsOffset = 4 + evenFieldRLE.count + oddFieldRLE.count
let endBlockOffset = commandsOffset + 24 + (frame.forced ? 1 : 0)
let totalSize = endBlockOffset + 6
precondition(totalSize <= 0xFFFF, "SPU larger than 64 KiB")
var spuBytes: [UInt8] = []
spuBytes.append(contentsOf: bigEndian16(totalSize))
spuBytes.append(contentsOf: bigEndian16(commandsOffset))
spuBytes.append(contentsOf: evenFieldRLE)
spuBytes.append(contentsOf: oddFieldRLE)
// command block 1: start date = 0 (relative to packet PTS) + display params
spuBytes.append(contentsOf: bigEndian16(0))
spuBytes.append(contentsOf: bigEndian16(endBlockOffset)) // next → block 2
spuBytes.append(0x01) // set start date
// colormap identity (color n → palette row n). ffmpeg's dvdsubenc emits
// this same 32/10 layout; the 03/20 variant 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.
spuBytes.append(0x03); spuBytes.append(0x32); spuBytes.append(0x10)
spuBytes.append(0x04); spuBytes.append(0xFF); spuBytes.append(0xF0) // alpha: 0 clear, 1-3 opaque
spuBytes.append(0x05) // position, 12-bit x1/x2/y1/y2
let rightEdge = frame.left + frame.width - 1, bottomEdge = frame.top + frame.height - 1
spuBytes.append(UInt8(frame.left >> 4))
spuBytes.append(UInt8((frame.left << 4) & 0xF0) | UInt8((rightEdge >> 8) & 0x0F))
spuBytes.append(UInt8(rightEdge & 0xFF))
spuBytes.append(UInt8(frame.top >> 4))
spuBytes.append(UInt8((frame.top << 4) & 0xF0) | UInt8((bottomEdge >> 8) & 0x0F))
spuBytes.append(UInt8(bottomEdge & 0xFF))
spuBytes.append(0x06) // RLE field offsets
spuBytes.append(contentsOf: bigEndian16(evenFieldOffset))
spuBytes.append(contentsOf: bigEndian16(oddFieldOffset))
if frame.forced { spuBytes.append(0x00) } // menu → forced flag
spuBytes.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
spuBytes.append(contentsOf: bigEndian16(Int((frame.endTicks - frame.startTicks) >> 10)))
spuBytes.append(contentsOf: bigEndian16(endBlockOffset)) // self-reference
spuBytes.append(0x02) // set end date
spuBytes.append(0xFF)
precondition(spuBytes.count == totalSize)
return spuBytes
}
// MARK: - MPEG program-stream wrapper (.sub file container)
//
// Each SPU becomes one or more 0x800-byte sectors
// (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 packHeaderBytes: [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 `idxTimestamp` prints
/// (its PTS words are always ms × 90).
func encodePTS(_ ticks: Int64) -> [UInt8] {
let wholeMs = (ticks + 45) / 90
let pts = UInt64(wholeMs * 90) & 0x1_FFFF_FFFF
return [
// '0010' prefix nibble — mkvmerge's VobSub reader flags the textually
// correct '0011' as "PTS error" but accepts '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 filePositions: [Int] // byte offset of each record's first sector (→ .idx filepos:)
}
func wrapPS(_ frames: [DVDSup]) -> VobSubFile {
var fileBytes: [UInt8] = []
var filePositions: [Int] = []
for frame in frames {
let spu = createSupFrame(frame)
// Slice the SPU into PES payloads: the first payload is 2020 bytes
// (2048 − PACK 14 − PES header 14 with PTS), later ones 2025.
var pesPayloads: [[UInt8]] = []
var sliceStart = 0
var maxSliceSize = 2020 - 1
while sliceStart < spu.count {
pesPayloads.append([0x20] + Array(spu[sliceStart..<min(sliceStart + maxSliceSize, spu.count)]))
sliceStart += maxSliceSize
maxSliceSize = 2025 - 1
}
filePositions.append(fileBytes.count)
for (payloadIndex, payload) in pesPayloads.enumerated() {
var sector = [UInt8](repeating: 0xFF, count: 0x800)
sector.replaceSubrange(0..<14, with: packHeaderBytes)
let headerLength = payloadIndex == 0 ? 5 : 0
let pesFieldLength = payload.count + 3 + headerLength // counts the hdrlen byte
sector[14] = 0x00; sector[15] = 0x00; sector[16] = 0x01; sector[17] = 0xBD
sector[18] = UInt8(pesFieldLength >> 8); sector[19] = UInt8(pesFieldLength & 0xFF)
sector[20] = 0x81
sector[21] = payloadIndex == 0 ? 0x80 : 0x00 // PTS present only first
sector[22] = UInt8(headerLength)
var cursor = 23
if payloadIndex == 0 {
sector.replaceSubrange(cursor..<cursor + 5, with: encodePTS(frame.startTicks))
cursor += 5
}
sector.replaceSubrange(cursor..<cursor + payload.count, with: payload)
cursor += payload.count
// padding PES (private_stream_2) fills the rest of the last sector;
// payload bytes are never truncated by our sizing.
let bytesLeft = 0x800 - cursor
if bytesLeft >= 6 {
let padFieldLength = bytesLeft - 6
sector[cursor] = 0x00; sector[cursor + 1] = 0x00; sector[cursor + 2] = 0x01; sector[cursor + 3] = 0xBE
sector[cursor + 4] = UInt8(padFieldLength >> 8); sector[cursor + 5] = UInt8(padFieldLength & 0xFF)
}
fileBytes.append(contentsOf: sector)
}
}
return VobSubFile(bytes: fileBytes, filePositions: filePositions)
}
// MARK: - .idx writer
func rgbHex(_ color: RGBA) -> String { String(format: "%02x%02x%02x", color.r, color.g, color.b) }
func idxTimestamp(_ ticks: Int64) -> String {
let totalMs = (ticks + 45) / 90
let hours = totalMs / 3_600_000
let minutes = (totalMs % 3_600_000) / 60_000
let seconds = (totalMs % 60_000) / 1000
let millis = totalMs % 1000
return String(format: "%02d:%02d:%02d:%03d", hours, minutes, seconds, millis)
}
func writeIdx(resolution: DVDResolution, fourColorPalette: [RGBA], frames: [DVDSup],
filePositions: [Int], lang: String, langName: String) -> String {
var lines: [String] = []
lines.append("# VobSub index file, v7 (do not modify this line!)")
lines.append("# Created by sup2vob")
lines.append("")
lines.append("# Frame size")
lines.append("size: \(resolution.width)x\(resolution.height)")
lines.append("")
lines.append("# Origin - upper-left corner")
lines.append("org: 0, 0")
lines.append("")
lines.append("# Scaling")
lines.append("scale: 100%, 100%")
lines.append("")
lines.append("# Alpha blending")
lines.append("alpha: 100%")
lines.append("")
lines.append("# Smoothing")
lines.append("smooth: OFF")
lines.append("")
lines.append("# Fade in/out in milliseconds")
lines.append("fadein/out: 0, 0")
lines.append("")
lines.append("# Force subtitle placement relative to (org.x, org.y)")
lines.append("align: OFF at LEFT TOP")
lines.append("")
lines.append("# For correcting non-progressive desync. (in millisecs or hh:mm:ss:ms)")
lines.append("time offset: 0")
lines.append("")
lines.append("# ON: displays only forced subtitles, OFF: shows everything")
lines.append("forced subs: OFF")
lines.append("")
lines.append("# The palette of the generated file")
var palette16 = Array(repeating: RGBA.transparent, count: 16)
for (slot, color) in fourColorPalette.prefix(4).enumerated() { palette16[slot] = color }
lines.append("palette: " + palette16.map { rgbHex($0) }.joined(separator: ", "))
lines.append("")
lines.append("# Custom colors (transp idxs and the four colors)")
lines.append("custom colors: OFF, tridx: 1000, colors: 000000, 444444, 888888, cccccc")
lines.append("")
lines.append("# Language index in use")
lines.append("langidx: 0")
lines.append("")
lines.append("# \(langName)")
lines.append("id: \(lang), index: 0")
lines.append("# Decomment next line to activate alternative name in DirectVobSub / Windows Media Player 6.x")
lines.append("# alt: \(langName)")
lines.append("# Vob/Cell ID: 1, 1 (PTS: 0)")
for (frameIndex, frame) in frames.enumerated() {
lines.append("timestamp: \(idxTimestamp(frame.startTicks)), filepos: \(String(format: "%09x", filePositions[frameIndex]))")
}
return lines.joined(separator: "\n") + "\n"
}
func writeSub(_ frames: [DVDSup]) -> VobSubFile {
wrapPS(frames)
}