Compare commits

...
2 Commits
Author SHA1 Message Date
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
Scott GarrettandClaude Code 30dd96ff79 Recognize subtitle language and type tokens in filenames
getFilenameLanguage now tokenizes the name and scans right-to-left the way mkvmerge's own heuristics do, so a language code survives behind a trailing flag token ("...eng.hearing_impaired.srt" was read as "und"). Three-char tokens try ISO 639-2/T and the library's B codes; the dash stays out of the separator set so region subtags ("pt-BR") are not split into a bogus ISO 639-1 hit.

getFilenameSubtitlesTrackName maps community type tokens (sdh / hearing_impaired / deaf, cc / closed caption, forced, commentary, lyrics) to a bare conventional track name ("SDH"); the language rides its own element. MP4 has no SDH flag and the name-keyword pass in MP42File organizeMediaCharacteristicsForMediaType: turns these names into the real QuickTime tags (public.subtitles.forced-only, public.accessibility.*).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 18:17:53 -05:00
10 changed files with 1224 additions and 53 deletions

No files matched your search

+3
View File
@@ -51,6 +51,9 @@ FourCharCode getTrackMediaSubType(MP4FileHandle fileHandle, MP4TrackId Id, uint3
NSString * getTrackLanguage(MP4FileHandle fileHandle, MP4TrackId Id);
NSString * getFilenameLanguage(CFStringRef filename);
// Community-convention track name ("SDH") from subtitle type tokens in the
// filename (sdh/cc/forced/commentary/lyrics), or nil when absent
NSString * getFilenameSubtitlesTrackName(CFStringRef filename);
NSString * guessStringLanguage(NSString *string);
MP4Duration getTrackDuration(MP4FileHandle fileHandle, MP4TrackId trackId);
+114 -49
View File
@@ -299,64 +299,129 @@ NSString * getTrackLanguage(MP4FileHandle fileHandle, MP4TrackId Id)
return @(lang);
}
// if the subtitle filename is something like title.en.srt or movie.fre.srt
// this function detects it and returns the subtitle language
// If the subtitle filename is something like title.en.srt or movie.fre.srt,
// this function detects it and returns the subtitle language.
//
// The name is tokenized and scanned right-to-left, the way mkvmerge's own
// filename heuristics work: community naming puts the language right before
// the extension (movie.eng.sdh.srt, movie.eng.hearing_impaired.srt), and the
// old "whatever sits between the last two dots" rule lost the language as
// soon as a trailing type token shadowed it. Dashes are deliberately NOT a
// separator here, so region-script subtags (pt-BR, zh-Hans) survive as one
// token and their region part can't be misread as a 2-letter ISO 639-1 code
// ("br" is Breton). Returns "und" when nothing decodes — every caller already
// treats that as "no hint" (SRT/SSA fall back to guessing from the file's
// text, the VobSub sup path keeps the converter's idx default).
NSString * getFilenameLanguage(CFStringRef filename)
{
CFRange findResult;
CFStringRef baseName = NULL;
CFStringRef langStr = NULL;
NSString *lang = @"en";
NSString *baseName = [(__bridge NSString *)filename lastPathComponent].stringByDeletingPathExtension;
NSArray<NSString *> *tokens =
[baseName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@". _"]];
MP42Languages *langManager = MP42Languages.defaultManager;
// find and strip the extension
findResult = CFStringFind(filename, CFSTR("."), kCFCompareBackwards);
findResult.length = findResult.location;
findResult.location = 0;
baseName = CFStringCreateWithSubstring(NULL, filename, findResult);
for (NSString *token in [tokens reverseObjectEnumerator]) {
NSString *lowercaseToken = token.lowercaseString;
// then find the previous period
findResult = CFStringFind(baseName, CFSTR("."), kCFCompareBackwards);
findResult.location++;
findResult.length = CFStringGetLength(baseName) - findResult.location;
// check for 3 char language code
if (findResult.length == 3) {
char langCStr[4] = "";
langStr = CFStringCreateWithSubstring(NULL, baseName, findResult);
CFStringGetCString(langStr, langCStr, 4, kCFStringEncodingASCII);
lang = [langManager extendedTagForISO_639_2:@(langCStr)];
CFRelease(langStr);
// and for a 2 char language code
} else if (findResult.length == 2) {
char langCStr[3] = "";
langStr = CFStringCreateWithSubstring(NULL, baseName, findResult);
CFStringGetCString(langStr, langCStr, 3, kCFStringEncodingASCII);
lang = [langManager extendedTagForISO_639_1:@(langCStr)];
CFRelease(langStr);
}
else if (findResult.length) {
char langCStr[40] = "";
langStr = CFStringCreateWithSubstring(NULL, baseName, findResult);
CFStringGetCString(langStr, langCStr, 40, kCFStringEncodingASCII);
lang = [langManager extendedTagForLang:@(langCStr)];
if ([lang isEqualToString:@"und"] && [langManager validateExtendedTag:@(langCStr)]) {
lang = @(langCStr);
if (lowercaseToken.length == 3) {
// ISO 639-2/T through the code cache first, then the library
// lookup which also matches the B codes (fre, ger, dut, …) that
// mkvmerge-style naming still uses.
NSString *tag = [langManager extendedTagForISO_639_2:lowercaseToken];
if (tag.length && ![tag isEqualToString:@"und"]) {
return tag;
}
tag = [langManager extendedTagForISO_639_2b:lowercaseToken];
if (tag.length && ![tag isEqualToString:@"und"]) {
return tag;
}
} else if (lowercaseToken.length == 2) {
// ISO 639-1; unknown codes come back empty/und from the library
NSString *tag = [langManager extendedTagForISO_639_1:lowercaseToken];
if (tag.length && ![tag isEqualToString:@"und"]) {
return tag;
}
} else if (lowercaseToken.length) {
// A full language name ("english") or a locale-identifier style
// extended tag ("pt-BR") as before
NSString *tag = [langManager extendedTagForLang:token];
if (tag.length && ![tag isEqualToString:@"und"]) {
return tag;
}
if ([langManager validateExtendedTag:token]) {
return token;
}
}
CFRelease(langStr);
}
CFRelease(baseName);
return lang;
return @"und";
}
// Community subtitle-type tokens: the flags release naming puts next to the
// language (movie.eng.sdh.srt, movie.eng.forced.srt). Neither container has a
// real SDH/CC flag — MP4 only has per-sample forced flags — so the community
// convention is to put the type in the track *name*, which is what players
// like VLC display. Returns nil when the filename carries no such token.
// Dashes are separators here (unlike getFilenameLanguage) so
// "hearing-impaired" splits into hit-able tokens too.
static NSString * subtitleTypeTokenFromFilename(CFStringRef filename)
{
NSString *baseName = [(__bridge NSString *)filename lastPathComponent].stringByDeletingPathExtension;
NSArray<NSString *> *tokens =
[baseName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@". _-"]];
BOOL forced = NO, lyrics = NO, commentary = NO, closedCaptions = NO, hearingImpaired = NO;
for (NSUInteger i = 0; i < tokens.count; i++) {
NSString *lowercaseToken = tokens[i].lowercaseString;
if ([lowercaseToken isEqualToString:@"sdh"] || [lowercaseToken isEqualToString:@"hearingimpaired"] ||
[lowercaseToken isEqualToString:@"impaired"] || [lowercaseToken isEqualToString:@"deaf"]) {
hearingImpaired = YES;
} else if ([lowercaseToken isEqualToString:@"cc"]) {
closedCaptions = YES;
} else if ([lowercaseToken isEqualToString:@"closed"] && i + 1 < tokens.count &&
[tokens[i + 1].lowercaseString hasPrefix:@"caption"]) {
// "closed_caption"/"closed-caption" — the separator splits the
// pair, so match it across two tokens. (Bare "captions" is NOT a
// CC marker; naming like Movie.eng.Captions.srt stays unnamed.)
closedCaptions = YES;
} else if ([lowercaseToken isEqualToString:@"commentary"] || [lowercaseToken isEqualToString:@"commentaries"]) {
commentary = YES;
} else if ([lowercaseToken isEqualToString:@"forced"]) {
forced = YES;
} else if ([lowercaseToken isEqualToString:@"lyrics"] || [lowercaseToken isEqualToString:@"lyric"]) {
lyrics = YES;
}
}
// SDH outranks CC (they overlap in naming), and both outrank the
// forced-only flag (SDH files typically flag many lines forced too).
if (hearingImpaired) {
return @"SDH";
}
if (closedCaptions) {
return @"CC";
}
if (commentary) {
return @"Commentary";
}
if (lyrics) {
return @"Lyrics";
}
if (forced) {
return @"Forced";
}
return nil;
}
// Track name for a subtitle file, following the community convention of
// naming the track after the type token the filename carries ("SDH", "CC",
// "Forced", "Commentary", "Lyrics"). Deliberately NOT prefixed with the
// language: the language rides its own element (MP4 elng/mdhd, MKV
// Language/LanguageIETF) and players show it alongside the name. Returns nil
// when the filename carries no type token.
NSString * getFilenameSubtitlesTrackName(CFStringRef filename)
{
return subtitleTypeTokenFromFilename(filename);
}
NSString *guessStringLanguage(NSString *stringFromFileAtURL)
+4
View File
@@ -67,6 +67,10 @@ MP42_OBJC_DIRECT_MEMBERS
}
}
// "...eng.forced.ass" style type tokens name the track after the type
// (MP4 has no SDH/CC flag; the name is the convention players show)
track.name = getFilenameSubtitlesTrackName((__bridge CFStringRef)self.fileURL.path);
_parser = [[MP42SSAParser alloc] initWithString:stringFromFileAtURL];
if (!_parser.lines.count) {
+4
View File
@@ -57,6 +57,10 @@ MP42_OBJC_DIRECT_MEMBERS
}
}
// "...eng.sdh.srt" style type tokens name the track after the type
// (MP4 has no SDH/CC flag; the name is the convention players show)
track.name = getFilenameSubtitlesTrackName((__bridge CFStringRef)self.fileURL.path);
NSInteger success = 0;
MP4Duration duration = 0;
+77 -4
View File
@@ -18,6 +18,9 @@
#import "MP42Track+Private.h"
#import "MP42SampleBuffer.h"
// MP42SupConverter — the vendored sup2vob PGS→VobSub converter (Sup2Vob/).
#import "MP42-Shared-Swift.h"
MP42_OBJC_DIRECT_MEMBERS
@interface SBVobSubSample : NSObject
{
@@ -227,23 +230,86 @@ MP42_OBJC_DIRECT_MEMBERS
@implementation MP42VobSubImporter {
@private
NSArray *_VobSubTracks;
/// For .sup sources: the temp directory holding the sup2vob-generated
/// .idx/.sub pair, and that .idx's URL. The pair lives until dealloc —
/// the model tracks retain this importer through export, and demux reads
/// the .sub from disk. Both nil for .idx sources, where the .idx sits
/// beside its .sub at fileURL.
NSURL *_convertedDirectory;
NSURL *_indexFileURL;
}
+ (NSArray<NSString *> *)supportedFileFormats {
return @[@"idx"];
return @[@"idx", @"sup"];
}
+ (NSArray<UTType *> *)supportedContentTypes
{
return @[[UTType typeWithFilenameExtension:@"idx"]];
return @[[UTType typeWithFilenameExtension:@"idx"],
[UTType typeWithFilenameExtension:@"sup"]];
}
// Convert a BLU-RAY PGS .sup into a VobSub pair in a private temp directory
// and return the generated .idx URL. The tracks retain this importer until the
// model drops them, so dealloc's cleanup can't pull the pair out from under a
// later demux.
- (NSURL *)convertSupAtURL:(NSURL *)supURL error:(NSError * __autoreleasing *)outError
{
NSURL *tempDirectory = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES]
URLByAppendingPathComponent:[NSString stringWithFormat:@"sup2vob-%@", [NSUUID UUID].UUIDString]];
NSURL *subURL = [tempDirectory URLByAppendingPathComponent:@"subtitles.sub"];
if (![NSFileManager.defaultManager createDirectoryAtURL:tempDirectory withIntermediateDirectories:YES attributes:nil error:outError]) {
return nil;
}
NSError *conversionError = nil;
if (![MP42SupConverter convertSupAtURL:supURL
toSubAtURL:subURL
language:@"en"
languageName:@"English"
error:&conversionError]) {
// Nothing usable was written; don't leave the empty directory behind
// (on success the pair lives here until dealloc instead).
[[NSFileManager defaultManager] removeItemAtURL:tempDirectory error:NULL];
if (outError) {
*outError = conversionError ?:
MP42Error(MP42LocalizedString(@"The file could not be opened.", @"vobsub error message"),
MP42LocalizedString(@"The file is not a sup file, or it does not contain any subtitles.", @"vobsub error message"), 101);
}
return nil;
}
_convertedDirectory = tempDirectory;
return [tempDirectory URLByAppendingPathComponent:@"subtitles.idx"];
}
- (void)dealloc
{
if (_convertedDirectory) {
[[NSFileManager defaultManager] removeItemAtURL:_convertedDirectory error:NULL];
}
}
- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)outError
{
if ((self = [super initWithURL:fileURL])) {
_indexFileURL = fileURL;
if ([fileURL.pathExtension caseInsensitiveCompare:@"sup"] == NSOrderedSame) {
_indexFileURL = [self convertSupAtURL:fileURL error:outError];
if (!_indexFileURL) {
return nil;
}
}
MP42TrackId count = 0;
_VobSubTracks = LoadVobSubSubtitles(self.fileURL.URLByDeletingLastPathComponent, self.fileURL.lastPathComponent);
_VobSubTracks = LoadVobSubSubtitles(_indexFileURL.URLByDeletingLastPathComponent, _indexFileURL.lastPathComponent);
// PGS carries no usable language (the generated idx id: line is the
// converter default), so — like the .srt/.ssa importers — take it from
// the filename; the 2-letter code path below would otherwise pin "en".
NSString *filenameLanguage = _convertedDirectory ? getFilenameLanguage((__bridge CFStringRef)fileURL.path) : nil;
for (SBVobSubTrack *track in _VobSubTracks) {
MP42SubtitleTrack *newTrack = [[MP42SubtitleTrack alloc] init];
@@ -253,6 +319,13 @@ MP42_OBJC_DIRECT_MEMBERS
newTrack.alternateGroup = 2;
newTrack.trackId = count++;
newTrack.language = [MP42Languages.defaultManager extendedTagForISO_639_1:track->language];
if (filenameLanguage && ![filenameLanguage isEqualToString:@"und"]) {
newTrack.language = filenameLanguage;
}
// "...eng.sdh.idx/sup" style type tokens name the track after
// the type ("SDH") — MP4 has no SDH/CC flag, the name is the
// convention players show; the language rides its own element.
newTrack.name = getFilenameSubtitlesTrackName((__bridge CFStringRef)fileURL.path);
newTrack.timescale = 1000;
newTrack.duration = track->duration;
@@ -310,7 +383,7 @@ MP42_OBJC_DIRECT_MEMBERS
{
@autoreleasepool {
NSURL *subFileURL = [self.fileURL.URLByDeletingPathExtension URLByAppendingPathExtension:@"sub"];
NSURL *subFileURL = [_indexFileURL.URLByDeletingPathExtension URLByAppendingPathExtension:@"sub"];
NSData *subFileData = [NSData dataWithContentsOfURL:subFileURL];
+278
View File
@@ -0,0 +1,278 @@
//
// Convert.swift
// MP42Foundation
//
// PGS composition → DVD subpicture conversion, part of the sup2vob converter
// vendored from https://git.technomancer.com/Scott-Files/sup2vob. Kept
// identical to upstream apart from this header and the two module globals the
// CLI declared in its (not vendored) main.swift; see MP42SupConverter.swift.
//
import Foundation
/// Set by `--debug`: traces per-frame decisions in convertToDVD. Nothing in
/// the framework writes these two CLI globals, hence `nonisolated(unsafe)` —
/// it keeps upstream's plain `var` semantics without the Swift concurrency
/// warning.
nonisolated(unsafe) var debugFrames = false
/// Set by the CLI's `--full`: keep the source frame size with no scaling.
/// Upstream declares this in main.swift; inside the framework it stays false —
/// imports always downscale to the DVD frame the muxer writes.
nonisolated(unsafe) var fullFramePassthrough = false
// MARK: - DVD subtitle frame (post scale + color reduction)
struct DVDSup {
var width: Int
var height: Int
var left: Int // left offset on the DVD frame
var top: Int // top offset on the DVD frame
var startTicks: Int64 // 90 kHz ticks (real)
var endTicks: Int64 // 90 kHz ticks (real)
var forced: Bool
var paletteIndices: [UInt8] // width*height, values 0..3 (index into the shared 4-color palette)
}
struct DVDResolution {
var width: Int
var height: Int
static let ntsc = DVDResolution(width: 720, height: 480)
static let pal = DVDResolution(width: 720, height: 576)
/// Picks NTSC/PAL from the PGS composition frame-rate code:
/// 0x10=23.976p 0x20=24p 0x30=25p 0x40=29.97p 0x50=50i 0x60=59.94i
/// 0x70=50p 0x80=59.94p; low codes 0x02/0x04/0x06 are 25/50-family formats.
static func from(frameRateCode: UInt8) -> DVDResolution {
let majorCode = Int(frameRateCode >> 4)
let minorCode = Int(frameRateCode & 0x0F)
if majorCode == 3 || majorCode == 5 || majorCode == 7 { return .pal }
if minorCode == 2 || minorCode == 4 || minorCode == 6 { return .pal }
return .ntsc
}
}
// MARK: - Frame assembly (objects → RGBA canvas rectangle)
/// Compose the frame's objects onto their bounding rectangle.
func composeRect(_ composition: Composition) -> (left: Int, top: Int, width: Int, height: Int, pixels: [RGBA])? {
var minX = Int.max, minY = Int.max, maxX = Int.min, maxY = Int.min
for object in composition.objects where object.width > 0 && object.height > 0 {
minX = min(minX, object.left); minY = min(minY, object.top)
maxX = max(maxX, object.left + object.width); maxY = max(maxY, object.top + object.height)
}
guard maxX > minX, maxY > minY else { return nil }
let clipLeft = max(0, minX), clipTop = max(0, minY)
let clipRight = min(composition.canvasWidth, maxX), clipBottom = min(composition.canvasHeight, maxY)
let width = clipRight - clipLeft, height = clipBottom - clipTop
guard width > 0, height > 0 else { return nil }
var pixels = Array(repeating: RGBA.transparent, count: width * height)
for object in composition.objects where object.width > 0 && object.height > 0 {
for srcY in 0..<object.height {
let dstY = object.top + srcY - clipTop
guard dstY >= 0 && dstY < height else { continue }
for srcX in 0..<object.width {
let dstX = object.left + srcX - clipLeft
guard dstX >= 0 && dstX < width else { continue }
// No color key in PGS: every index goes through the palette;
// transparency is the palette entry's alpha (undocumented
// entries default to alpha 0).
pixels[dstY * width + dstX] = composition.palette.entries[Int(object.pixels[srcY * object.width + srcX])]
}
}
}
return (clipLeft, clipTop, width, height, pixels)
}
// MARK: - Scaling (area-average filter with alpha coverage)
func scaleBox(_ source: [RGBA], _ sourceWidth: Int, _ sourceHeight: Int,
_ destWidth: Int, _ destHeight: Int) -> [RGBA] {
var output = [RGBA](repeating: .transparent, count: destWidth * destHeight)
guard destWidth > 0, destHeight > 0 else { return output }
let sourcePixelsPerDestX = Double(sourceWidth) / Double(destWidth)
let sourcePixelsPerDestY = Double(sourceHeight) / Double(destHeight)
for destY in 0..<destHeight {
let srcYStart = Int(Double(destY) * sourcePixelsPerDestY)
let srcYEnd = min(sourceHeight, max(srcYStart + 1, Int(ceil(Double(destY + 1) * sourcePixelsPerDestY))))
for destX in 0..<destWidth {
let srcXStart = Int(Double(destX) * sourcePixelsPerDestX)
let srcXEnd = min(sourceWidth, max(srcXStart + 1, Int(ceil(Double(destX + 1) * sourcePixelsPerDestX))))
var alphaWeightSum = 0.0, redSum = 0.0, greenSum = 0.0, blueSum = 0.0
for srcY in srcYStart..<srcYEnd {
let verticalCoverage = min(Double(srcYEnd), Double(srcY + 1)) - max(Double(srcYStart), Double(srcY))
for srcX in srcXStart..<srcXEnd {
let pixel = source[srcY * sourceWidth + srcX]
guard pixel.a > 0 else { continue }
let horizontalCoverage = min(Double(srcXEnd), Double(srcX + 1)) - max(Double(srcXStart), Double(srcX))
let pixelWeight = Double(pixel.a) / 255.0 * horizontalCoverage * verticalCoverage
alphaWeightSum += pixelWeight
redSum += Double(pixel.r) * pixelWeight
greenSum += Double(pixel.g) * pixelWeight
blueSum += Double(pixel.b) * pixelWeight
}
}
let destCellArea = Double(srcXEnd - srcXStart) * Double(srcYEnd - srcYStart)
guard destCellArea > 0, alphaWeightSum / destCellArea * 255.0 >= 128.0 else { continue }
// DVD has no real alpha: keep pixels whose coverage is at least half.
let totalWeight = max(alphaWeightSum, 0.0001)
let r = UInt8(min(255, max(0, Int((redSum / totalWeight).rounded()))))
let g = UInt8(min(255, max(0, Int((greenSum / totalWeight).rounded()))))
let b = UInt8(min(255, max(0, Int((blueSum / totalWeight).rounded()))))
output[destY * destWidth + destX] = RGBA(r: r, g: g, b: b, a: 255)
}
}
return output
}
// MARK: - Color reduction
func nearestColor(_ color: RGBA, among candidates: [RGBA]) -> RGBA {
var best = candidates[0], bestDistance = Int.max
for candidate in candidates {
let rDiff = Int(color.r) - Int(candidate.r)
let gDiff = Int(color.g) - Int(candidate.g)
let bDiff = Int(color.b) - Int(candidate.b)
let squaredDistance = rDiff * rDiff + gDiff * gDiff + bDiff * bDiff
if squaredDistance < bestDistance { bestDistance = squaredDistance; best = candidate }
}
return best
}
struct ConversionResult {
var frames: [DVDSup]
var fourColorPalette: [RGBA] // [0] = transparent, [1..3] = shared colors (also idx0 in the 16-slot file palette)
}
/// PGS compositions → DVD subpictures: end times, scaling, cropping, and a
/// single shared 4-color palette (VobSub's `tridx: 1000` convention makes only
/// 2-bit code 0 transparent, so all frames must share one color set).
func convertToDVD(_ compositions: [Composition], resolution targetRes: DVDResolution) -> ConversionResult {
// Non-blank compositions are frames. The next composition (blank or not)
// closes the previous frame's display time — PGS "clear screen" semantics.
var timedFrames: [(composition: Composition, endTicks: Int64)] = []
for (i, composition) in compositions.enumerated() where !composition.isBlank {
var endTicks: Int64? = nil
for j in (i + 1)..<compositions.count where compositions[j].startTicks > composition.startTicks {
endTicks = compositions[j].startTicks
break
}
timedFrames.append((composition, endTicks ?? (composition.startTicks + 2 * 90000)))
}
// pass 1: geometry + opaque pixels per frame, counting colors globally
struct PreppedFrame {
var left, top, width, height: Int
var startTicks, endTicks: Int64
var forced: Bool
var pixels: [RGBA]
}
var preppedFrames: [PreppedFrame] = []
var colorCounts: [Int: Int] = [:]
for (composition, endTicks) in timedFrames {
guard let (rectLeft, rectTop, rectWidth, rectHeight, canvasPixels) = composeRect(composition) else {
if debugFrames {
let objectWidths = composition.objects.map { String($0.width) }.joined(separator: ",")
FileHandle.standardError.write("drop t=\(composition.startTicks): composeRect nil (objs=\(composition.objects.count) widths=[\(objectWidths)])\n".data(using: .utf8)!)
}
continue
}
if fullFramePassthrough {
// Passthrough: keep the object rect verbatim — no downscale, no transparent-edge crop (its
// output frames match the source object geometry exactly).
var paddedPixels = canvasPixels
var paddedHeight = rectHeight
if rectHeight < 2 { paddedPixels += Array(repeating: .transparent, count: rectWidth); paddedHeight = 2 }
for pixel in paddedPixels where pixel.isPainted { colorCounts[pixel.packedARGB, default: 0] += 1 }
preppedFrames.append(PreppedFrame(left: rectLeft, top: rectTop, width: rectWidth, height: paddedHeight,
startTicks: composition.startTicks, endTicks: endTicks,
forced: composition.objects.contains { $0.forced }, pixels: paddedPixels))
continue
}
let scaleX = Double(targetRes.width) / Double(composition.canvasWidth)
let scaleY = Double(targetRes.height) / Double(composition.canvasHeight)
var destLeft = Int((Double(rectLeft) * scaleX).rounded())
var destTop = Int((Double(rectTop) * scaleY).rounded())
// ffmpeg's decoder needs h ≥ 2 (`w > 0 && h > 1`), so the scale target
// can never be a single row tall.
destLeft = min(max(0, destLeft), targetRes.width - 2)
destTop = min(max(0, destTop), targetRes.height - 2)
let destWidth = min(max(2, Int((Double(rectWidth) * scaleX).rounded())), targetRes.width - destLeft)
let destHeight = min(max(2, Int((Double(rectHeight) * scaleY).rounded())), targetRes.height - destTop)
guard destWidth > 0, destHeight > 0 else {
if debugFrames { FileHandle.standardError.write("drop t=\(composition.startTicks): rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight)\n".data(using: .utf8)!) }
continue
}
let scaled = scaleBox(canvasPixels, rectWidth, rectHeight, destWidth, destHeight)
// crop to the opaque bounding box
var bboxLeft = destWidth, bboxTop = destHeight, bboxRight = -1, bboxBottom = -1
for row in 0..<destHeight {
for col in 0..<destWidth where scaled[row * destWidth + col].isOpaque {
bboxLeft = min(bboxLeft, col); bboxTop = min(bboxTop, row)
bboxRight = max(bboxRight, col); bboxBottom = max(bboxBottom, row)
}
}
if bboxBottom == bboxTop { // keep ≥ 2 rows; an extra row is empty because
if bboxTop == destHeight - 1 { bboxTop -= 1 } else { bboxBottom += 1 } // bbox covered all opaque rows
}
guard bboxRight >= bboxLeft else {
if debugFrames {
let visibleCount = scaled.filter { $0.isVisible }.count
let canvasOpaqueCount = canvasPixels.filter { $0.isOpaque }.count
let objectIndexHistogram = composition.objects.map { object -> String in
var indexCounts: [Int: Int] = [:]
for pixelValue in object.pixels { indexCounts[Int(pixelValue), default: 0] += 1 }
let topEntries = indexCounts.sorted { $0.key < $1.key }.prefix(12)
.map { "\($0.key):\($0.value)" }.joined(separator: " ")
return "obj\(object.objectID)(\(object.width)x\(object.height)) [\(topEntries)]"
}.joined(separator: " ")
FileHandle.standardError.write("drop t=\(composition.startTicks): no opaque after scale (rect=\(rectLeft),\(rectTop) \(rectWidth)x\(rectHeight) → \(destLeft),\(destTop) \(destWidth)x\(destHeight), scaledVis=\(visibleCount) canvasOpaque=\(canvasOpaqueCount))\n \(objectIndexHistogram)\n".data(using: .utf8)!)
}
continue
}
let cropWidth = bboxRight - bboxLeft + 1, cropHeight = bboxBottom - bboxTop + 1
var croppedPixels = [RGBA](repeating: .transparent, count: cropWidth * cropHeight)
for row in 0..<cropHeight {
for col in 0..<cropWidth {
croppedPixels[row * cropWidth + col] = scaled[(row + bboxTop) * destWidth + (col + bboxLeft)]
}
}
destLeft += bboxLeft; destTop += bboxTop
for pixel in croppedPixels where pixel.isOpaque { colorCounts[pixel.packedARGB, default: 0] += 1 }
preppedFrames.append(PreppedFrame(left: destLeft, top: destTop, width: cropWidth, height: cropHeight,
startTicks: composition.startTicks, endTicks: endTicks,
forced: composition.objects.contains { $0.forced }, pixels: croppedPixels))
}
// pass 2: shared palette = 3 most-used colors overall
let rankedColors = colorCounts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
var colors = rankedColors.prefix(3).map { colorCount -> RGBA in
RGBA(r: UInt8((colorCount.key >> 16) & 0xFF), g: UInt8((colorCount.key >> 8) & 0xFF),
b: UInt8(colorCount.key & 0xFF), a: 255)
}
while colors.count < 3 { colors.append(.transparent) }
var frames: [DVDSup] = []
for prepped in preppedFrames {
var colorCodeByRGB: [Int: UInt8] = [:]
for (slot, color) in colors.enumerated() where color.isVisible { colorCodeByRGB[color.packedARGB] = UInt8(slot + 1) }
var paletteIndices = [UInt8](repeating: 0, count: prepped.pixels.count)
// The paint set is RGBA.isPainted (alpha-≥77 rule — see
// the fullFramePassthrough branch). The DVD path never sees sub-128 pixels here
// because scaleBox already resolved coverage to 0/255, so the
// predicates agree in both modes.
for (pixelPos, pixel) in prepped.pixels.enumerated() where pixel.isPainted {
if let code = colorCodeByRGB[pixel.packedARGB] { paletteIndices[pixelPos] = code }
else { paletteIndices[pixelPos] = UInt8((colors.firstIndex(of: nearestColor(pixel, among: colors)) ?? 0) + 1) }
}
frames.append(DVDSup(width: prepped.width, height: prepped.height, left: prepped.left, top: prepped.top,
startTicks: prepped.startTicks, endTicks: prepped.endTicks,
forced: prepped.forced, paletteIndices: paletteIndices))
}
return ConversionResult(frames: frames, fourColorPalette: [RGBA.transparent] + colors)
}
+62
View File
@@ -0,0 +1,62 @@
//
// MP42SupConverter.swift
// MP42Foundation
//
// Objective-C entry point for the vendored sup2vob converter
// (https://git.technomancer.com/Scott-Files/sup2vob): BLU-RAY PGS .sup →
// VobSub .sub/.idx. MP42VobSubImporter drives it so a dragged-in .sup lands
// on the framework's existing VobSub import/mux path unchanged.
//
import Foundation
@objc(MP42SupConverter) public class SupConverter: NSObject {
@objc public static let errorDomain = "org.galad.MP42Foundation.SubConverter"
/// Converts the BLU-RAY PGS `inputURL` (.sup) to a VobSub pair: the .sub is
/// written to `subURL` and the matching .idx beside it (same stem, `.idx`
/// extension). `language`/`languageName` only decorate the .idx `id:`/`alt:`
/// lines — the importer overwrites the track language from the source
/// filename, the way the .srt importer does.
///
/// Mirrors sup2vob's CLI orchestration: PAL/NTSC picked automatically from
/// the PGS frame-rate code, BT.709 palette interpretation, frames
/// downscaled to the DVD frame the muxer writes.
@objc(convertSupAtURL:toSubAtURL:language:languageName:error:)
public static func convertSup(at inputURL: URL,
toSubAt subURL: URL,
language: String,
languageName: String) throws {
let fileBytes = [UInt8](try Data(contentsOf: inputURL))
let compositions: [Composition]
do {
compositions = try readPGS(fileBytes, space: .bt709)
} catch let supError as PGSError {
throw conversionError(100, "\(inputURL.lastPathComponent): \(supError)")
}
guard !compositions.isEmpty else {
throw conversionError(101, "\(inputURL.lastPathComponent): no compositions found")
}
let resolution = DVDResolution.from(frameRateCode: compositions[0].frameRateCode)
let result = convertToDVD(compositions, resolution: resolution)
guard !result.frames.isEmpty else {
throw conversionError(102, "\(inputURL.lastPathComponent): no displayable subtitle frames")
}
let subFile = writeSub(result.frames)
let idxText = writeIdx(resolution: resolution, fourColorPalette: result.fourColorPalette,
frames: result.frames, filePositions: subFile.filePositions,
lang: language, langName: languageName)
let idxURL = subURL.deletingPathExtension().appendingPathExtension("idx")
try Data(subFile.bytes).write(to: subURL)
try idxText.write(to: idxURL, atomically: true, encoding: .ascii)
}
private static func conversionError(_ code: Int, _ message: String) -> NSError {
NSError(domain: errorDomain, code: code, userInfo: [NSLocalizedDescriptionKey: message])
}
}
+295
View File
@@ -0,0 +1,295 @@
//
// 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
}
+355
View File
@@ -0,0 +1,355 @@
//
// VobSub.swift
// MP42Foundation
//
// DVD SPU encoding plus the .sub/.idx writers, part of the sup2vob converter
// vendored from https://git.technomancer.com/Scott-Files/sup2vob. Kept
// identical to upstream apart from this header; see MP42SupConverter.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 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)
}
+32
View File
@@ -276,6 +276,14 @@
A9FB3C7B306BB692000B756D /* MP42VisionOCR.h in Headers */ = {isa = PBXBuildFile; fileRef = A9FB3C76306BB692000B756D /* MP42VisionOCR.h */; };
A9FD169F27661B690096BBA8 /* SampleDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9FD169E27661B690096BBA8 /* SampleDescription.swift */; };
A9FD16A027661B690096BBA8 /* SampleDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9FD169E27661B690096BBA8 /* SampleDescription.swift */; };
5AB1E22600000000000000B1 /* PGS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A1 /* PGS.swift */; };
5AB1E22600000000000000B2 /* Convert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A2 /* Convert.swift */; };
5AB1E22600000000000000B3 /* VobSub.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A3 /* VobSub.swift */; };
5AB1E22600000000000000B4 /* MP42SupConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A4 /* MP42SupConverter.swift */; };
5AB1E22600000000000000C1 /* PGS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A1 /* PGS.swift */; };
5AB1E22600000000000000C2 /* Convert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A2 /* Convert.swift */; };
5AB1E22600000000000000C3 /* VobSub.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A3 /* VobSub.swift */; };
5AB1E22600000000000000C4 /* MP42SupConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E22600000000000000A4 /* MP42SupConverter.swift */; };
FFE849961EBCAFDF000AA078 /* MP42AC3AudioEncoder.h in Headers */ = {isa = PBXBuildFile; fileRef = FFE849941EBCAFDF000AA078 /* MP42AC3AudioEncoder.h */; };
FFE849971EBCAFDF000AA078 /* MP42AC3AudioEncoder.m in Sources */ = {isa = PBXBuildFile; fileRef = FFE849951EBCAFDF000AA078 /* MP42AC3AudioEncoder.m */; };
/* End PBXBuildFile section */
@@ -486,6 +494,10 @@
A9FB3C76306BB692000B756D /* MP42VisionOCR.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MP42VisionOCR.h; sourceTree = "<group>"; };
A9FB3C77306BB692000B756D /* MP42VisionOCR.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MP42VisionOCR.m; sourceTree = "<group>"; };
A9FD169E27661B690096BBA8 /* SampleDescription.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleDescription.swift; sourceTree = "<group>"; };
5AB1E22600000000000000A1 /* PGS.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PGS.swift; sourceTree = "<group>"; };
5AB1E22600000000000000A2 /* Convert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Convert.swift; sourceTree = "<group>"; };
5AB1E22600000000000000A3 /* VobSub.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VobSub.swift; sourceTree = "<group>"; };
5AB1E22600000000000000A4 /* MP42SupConverter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MP42SupConverter.swift; sourceTree = "<group>"; };
FFE849941EBCAFDF000AA078 /* MP42AC3AudioEncoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AC3AudioEncoder.h; sourceTree = "<group>"; };
FFE849951EBCAFDF000AA078 /* MP42AC3AudioEncoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AC3AudioEncoder.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -550,6 +562,17 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5AB1E22600000000000000D1 /* Sup2Vob */ = {
isa = PBXGroup;
children = (
5AB1E22600000000000000A1 /* PGS.swift */,
5AB1E22600000000000000A2 /* Convert.swift */,
5AB1E22600000000000000A3 /* VobSub.swift */,
5AB1E22600000000000000A4 /* MP42SupConverter.swift */,
);
path = Sup2Vob;
sourceTree = "<group>";
};
A9B9C1E3182391DF00416A4E = {
isa = PBXGroup;
children = (
@@ -614,6 +637,7 @@
A9B9C2301823923100416A4E /* MP42File.h */,
A9B9C2311823923100416A4E /* MP42File.m */,
A9FD169E27661B690096BBA8 /* SampleDescription.swift */,
5AB1E22600000000000000D1 /* Sup2Vob */,
A9B9C2501823923100416A4E /* MP42Track.h */,
A9B9C2511823923100416A4E /* MP42Track.m */,
A99FCBC31BAD65EF0058E27A /* MP42Track+Private.h */,
@@ -1052,6 +1076,10 @@
A910B5DC18394EB20064028F /* MP42Languages.m in Sources */,
A9059DCF1D870F8D000D1B9A /* MP42ConversionSettings.m in Sources */,
A9FD16A027661B690096BBA8 /* SampleDescription.swift in Sources */,
5AB1E22600000000000000B1 /* PGS.swift in Sources */,
5AB1E22600000000000000B2 /* Convert.swift in Sources */,
5AB1E22600000000000000B3 /* VobSub.swift in Sources */,
5AB1E22600000000000000B4 /* MP42SupConverter.swift in Sources */,
A910B5E018394EB20064028F /* MP42PrivateUtilities.m in Sources */,
A910B5E218394EB20064028F /* MP42Utilities.m in Sources */,
A910B5E418394EB20064028F /* MP42SubUtilities.m in Sources */,
@@ -1124,6 +1152,10 @@
A9059DCC1D870B9C000D1B9A /* MP42ConversionSettings.m in Sources */,
A9B9C26B1823923200416A4E /* MP42AudioConverter.m in Sources */,
A9FD169F27661B690096BBA8 /* SampleDescription.swift in Sources */,
5AB1E22600000000000000C1 /* PGS.swift in Sources */,
5AB1E22600000000000000C2 /* Convert.swift in Sources */,
5AB1E22600000000000000C3 /* VobSub.swift in Sources */,
5AB1E22600000000000000C4 /* MP42SupConverter.swift in Sources */,
A941C9601F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */,
A9B9C2711823923200416A4E /* MP42BitmapSubConverter.m in Sources */,
A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */,