Compare commits

...
3 Commits
Author SHA1 Message Date
Scott GarrettandClaude Code 72e879e316 Add a slim sup2vob CLI built from the vendored Sup2Vob sources
The extractsubs helper shipped in the Subler app bundle needs sup2vob
on PATH, so the converter gets a CLI build beside the framework target.
Slim by design: this directory holds only upstream's main.swift and a
Makefile that compiles it against ../MP42/Sup2Vob/ — the exact files the
framework builds, so an upstream merge updates app and CLI in one pass
and the two can never silently disagree. The CLI's --full output is the
byte-identical oracle for the framework converter (verified: same
sub/idx bytes for a full movie track).

main.swift is upstream verbatim except for the documented globals seam:
the CLI's debugFrames/fullFramePassthrough declarations belong to the
vendored Convert.swift, so main.swift drops its re-declaration and only
assigns them (--debug/--full). The framework facade
(MP42SupConverter.swift) is deliberately not part of the CLI build.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 23:06:27 -05:00
Scott GarrettandClaude Code 837aa1c098 Keep the PGS source resolution through the sup2vob conversion
VobSub conversions of PGS material were downscaled to the 720x480/576
DVD frame — a 1080p source came out of the mux at one quarter of its
authored size. The framework's sup2vob façade now always runs the
upstream CLI's `--full` mode: fullFramePassthrough keeps every frame's
object geometry verbatim, and the idx size line (which the VobSub
importer carries into track.width/height and the muxer writes into the
subpic track) is the PGS's own PCS canvas, e.g. 1920x1080. The
frame-rate-derived DVD frame stays as fallback for streams that define
no usable canvas. The conversion output is byte-identical to running
`sup2vob --full` on the same .sup.

The vendored upstream sources stay untouched apart from one comment —
the passthrough is enabled in the adaptation layer, same as the CLI
does with its flag. This applies to both PGS paths, which share the
conversion: .sup drag-import and PGS-from-MKV via
MP42PgsToVobSubConverter.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 21:13:57 -05:00
Scott GarrettandClaude Code 57772086a5 Convert Matroska PGS tracks to VobSub and name flagged tracks SDH
A PGS track inside an MKV can now be muxed as a real subp track: the
muxer's bitmap-converter branch recognizes a PGS source with a VobSub
target (new MP42ConversionSettings subtitlesVobSubConversion) and uses
the new MP42PgsToVobSubConverter instead of MP42BitmapSubConverter.

The converter rebuilds the PGS elementary stream from the source
container up-front, because mkvmerge stores each PGS segment with its
13-byte "PG" envelope removed (type + 2-byte length + payload,
zlib-compressed) — a plain concatenation of demuxed blocks is not a
.sup. Each block is walked segment-by-segment and the envelope is
restored as PG + 90 kHz pts (from the block's nanosecond timestamp) +
four zero bytes + type + length, byte-identical to what mkvextract
writes; blocks that already carry envelopes pass through verbatim. The
rebuilt temp .sup then rides the existing MP42VobSubImporter wholesale
for palette, DVD geometry, and raw-SPU samples, which replay through
copyEncodedSample while the live muxing stream is discarded.

Subtitle type recognition now names any flagged track "SDH" (hearing
impaired, commentary, forced, lyrics, closed captions) instead of a
per-type name, and MKV container tracks get the same treatment on the
conversion path: the TrackEntry Name runs through the recognizer, or
the MKV's own filename when there is no Name element. tagsOnly mode
stays verbatim — that model is the tag writer's diff baseline.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 20:00:08 -05:00
14 changed files with 757 additions and 58 deletions

No files matched your search

+4
View File
@@ -14,6 +14,10 @@ NS_ASSUME_NONNULL_BEGIN
@interface MP42ConversionSettings : NSObject <NSCopying, NSSecureCoding>
+ (instancetype)subtitlesConversion;
// Convert a bitmap subtitle (VobSub/PGS) *to* VobSub rather than to tx3g —
// the muxer picks MP42PgsToVobSubConverter when the source is PGS and this
// is the requested format (a PGS-in-MKV track muxed as a real MP4 subp track).
+ (instancetype)subtitlesVobSubConversion;
@property (nonatomic, readonly) FourCharCode format;
+5
View File
@@ -16,6 +16,11 @@
return [[MP42ConversionSettings alloc] initWitFormat:kMP42SubtitleCodecType_3GText];
}
+ (instancetype)subtitlesVobSubConversion
{
return [[MP42ConversionSettings alloc] initWitFormat:kMP42SubtitleCodecType_VobSub];
}
- (instancetype)initWitFormat:(FourCharCode)format
{
self = [super init];
+19
View File
@@ -318,6 +318,25 @@ MP42_OBJC_DIRECT_MEMBERS
if (trackName) {
newTrack.name = trackName;
}
if (!tagsOnly && [newTrack isKindOfClass:[MP42SubtitleTrack class]]) {
// Community-convention SDH naming, same as the subtitle
// file importers: mkvmerge commonly stores the source
// subtitle file's name (with its flag tokens) as the
// TrackEntry Name, so recognize them there; a nameless
// track can also inherit a flag token from the MKV's own
// filename. tagsOnly is exempt — that model must mirror
// the file verbatim for the tag writer's diff.
// Key off the TrackName element's presence, not the
// model name: every track starts life with a default
// localized "<type> Track" name, so an empty name never
// happens here.
NSString *token = trackName.length ?
getSubtitleTypeTokenFromString(trackName) :
getFilenameSubtitlesTrackName((__bridge CFStringRef)self.fileURL.path);
if (token) {
newTrack.name = token;
}
}
if (mkvTrack->LanguageBCP47) {
newTrack.language = [MP42Languages.defaultManager normalizedExtendedTag:@(mkvTrack->LanguageBCP47)];
} else {
+47 -10
View File
@@ -15,6 +15,7 @@
#import "MP42SampleBuffer.h"
#import "MP42AudioConverter.h"
#import "MP42BitmapSubConverter.h"
#import "MP42PgsToVobSubConverter.h"
#import "MP42TextSubConverter.h"
#import "mp4v2.h"
@@ -126,19 +127,55 @@ MP42_OBJC_DIRECT_MEMBERS
}
if ([track isMemberOfClass:[MP42SubtitleTrack class]] && track.conversionSettings &&
(track.format == kMP42SubtitleCodecType_VobSub || track.format == kMP42SubtitleCodecType_PGS)) {
MP42BitmapSubConverter *subConverter = [[MP42BitmapSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track
error:outError];
if (track.format == kMP42SubtitleCodecType_PGS &&
track.conversionSettings.format == kMP42SubtitleCodecType_VobSub) {
// PGS → VobSub (muxed as a real subp track): sup2vob derives one
// global DVD palette/geometry for the whole track, and the subpic
// branch needs both at track-creation time, so this converter
// converts during init (re-reading the source itself) and the
// live stream it receives is discarded.
MP42PgsToVobSubConverter *pgsConverter = [[MP42PgsToVobSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track
error:outError];
if (subConverter == nil) {
if (outError && *outError) {
[_logger writeErrorToLog:*outError];
if (pgsConverter == nil) {
if (outError && *outError) {
[_logger writeErrorToLog:*outError];
}
[unsupportedTracks addObject:track];
continue;
}
[unsupportedTracks addObject:track];
continue;
}
track.converter = subConverter;
format = track.conversionSettings.format;
track.converter = pgsConverter;
format = track.conversionSettings.format;
// The converted subtitles keep the PGS's own canvas size
// (sup2vob runs in full-frame passthrough, e.g. 1920x1080)
// — and an MKV-sourced track carries no size at all — so
// steer the subpic branch's trackWidth/trackHeight
// preference with the converter's frame size.
MP42SubtitleTrack *subTrack = (MP42SubtitleTrack *)track;
subTrack.trackWidth = pgsConverter.frameWidth;
subTrack.trackHeight = pgsConverter.frameHeight;
NSData *convertedCookie = pgsConverter.magicCookie;
if (convertedCookie.length >= sizeof(uint32_t) * 16) {
magicCookie = convertedCookie;
}
} else {
MP42BitmapSubConverter *subConverter = [[MP42BitmapSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track
error:outError];
if (subConverter == nil) {
if (outError && *outError) {
[_logger writeErrorToLog:*outError];
}
[unsupportedTracks addObject:track];
continue;
}
track.converter = subConverter;
format = track.conversionSettings.format;
}
} else if ([track isMemberOfClass:[MP42SubtitleTrack class]] && track.conversionSettings) {
MP42TextSubConverter *subConverter = [[MP42TextSubConverter alloc] initWithTrack:(MP42SubtitleTrack *)track
error:outError];
+47
View File
@@ -0,0 +1,47 @@
//
// MP42PgsToVobSubConverter.h
// MP42Foundation
//
// Converts a Blu-ray PGS subtitle track (demuxed from an MKV) into VobSub
// subpic samples, so a PGS-only-in-MKV subtitle can land in an MP4 as a
// real subp track instead of only as OCR'd tx3g text.
//
#import <Foundation/Foundation.h>
#import "MP42ConverterProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class MP42SampleBuffer;
@class MP42SubtitleTrack;
// MP42ConverterProtocol for PGS → VobSub (subpic) muxing. PGS conversion is
// whole-track batch work (sup2vob derives one global 4-color DVD palette and
// needs later compositions to compute frame end-times), and the muxer needs
// the palette and frame size when it *creates* the subpic track — before any
// sample is pumped. So the conversion runs to completion in -initWithTrack:
// error:, and copyEncodedSample just replays the finished samples: the
// track's live input stream (whose bytes the prepass already re-read from
// disk) is discarded, and EOF is emitted once the input stream ends.
@interface MP42PgsToVobSubConverter : NSObject <MP42ConverterProtocol>
- (nullable instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError * __autoreleasing *)outError;
// DVD frame the converted subtitles were rendered at (720x480 NTSC /
// 720x576 PAL), from the generated idx `size:` line. The muxer sizes the
// subpic track with these — the PGS model track carries the source video's
// size (or 0 from an MKV), not the frame the VobSub was converted to.
@property (nonatomic, readonly) uint32_t frameWidth;
@property (nonatomic, readonly) uint32_t frameHeight;
// The idx palette as 16 UInt32 0x00RRGGBB entries — the subpic magic cookie.
- (nullable NSData *)magicCookie;
- (void)addSample:(MP42SampleBuffer *)sample;
- (nullable MP42SampleBuffer *)copyEncodedSample;
- (void)cancel;
@end
NS_ASSUME_NONNULL_END
+385
View File
@@ -0,0 +1,385 @@
//
// MP42PgsToVobSubConverter.m
// MP42Foundation
//
#import "MP42PgsToVobSubConverter.h"
#import "MP42FileImporter.h"
#import "MP42FileImporter+Private.h"
#import "MP42Track.h"
#import "MP42Track+Private.h"
#import "MP42SubtitleTrack.h"
#import "MP42Fifo.h"
#import "MP42SampleBuffer.h"
#import "MP42PrivateUtilities.h"
#import "MP42MediaFormat.h"
// The demuxer threads this converter starts pump bounded FIFOs (capacity 20),
// so the collecting loops must run to EOF even on error paths — a stalled
// demuxer thread would hold the source file open forever. The deadlines only
// fire on genuinely stuck input.
static const NSTimeInterval kPGSPrepassTimeout = 600;
static const NSTimeInterval kVobSubPrepassTimeout = 300;
// Declared in the interface so the thread-start @selector stays legal:
// MP42_OBJC_DIRECT_MEMBERS would otherwise make the method direct-dispatch
// only, and @selector on a direct method is a hard compile error
// (MP42BitmapSubConverter predates the macro covering its own routines).
@interface MP42PgsToVobSubConverter ()
- (void)inputDrainThreadMainRoutine;
@end
MP42_OBJC_DIRECT_MEMBERS
@implementation MP42PgsToVobSubConverter {
// Phase-1/2 prepass products, all built synchronously in init:
NSMutableArray<MP42SampleBuffer *> *_pendingSamples;
NSData *_magicCookie;
uint32_t _frameWidth;
uint32_t _frameHeight;
// Kept alive so the temp .sup (and the importer's own temp idx/sub pair,
// removed by its dealloc) outlive the samples served from them.
MP42FileImporter *_vobsubImporter;
NSURL *_tempDirectory;
// Live input stream: contents discarded (the prepass re-read the same
// bytes from disk), only its EOF flag matters.
MP42Fifo<MP42SampleBuffer *> *_inputSamplesBuffer;
NSThread *_inputThread;
dispatch_semaphore_t _done;
volatile BOOL _inputDone;
BOOL _eofSent;
BOOL _streamMalformed;
}
// Started by -initWithTrack:error:; discards the live input stream (declared
// in the class extension above — see the @selector note there).
- (void)inputDrainThreadMainRoutine
{
@autoreleasepool {
MP42SampleBuffer *sampleBuffer = nil;
while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) {
@autoreleasepool {
if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) {
_inputDone = YES;
break;
}
// The live PGS bytes are discarded: the init prepass already
// re-read the same stream from the source file.
}
}
dispatch_semaphore_signal(_done);
}
}
- (nullable instancetype)initWithTrack:(MP42SubtitleTrack *)track error:(NSError * __autoreleasing *)outError
{
if ((self = [super init])) {
NSURL *sourceURL = track.URL;
if (!sourceURL) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The subtitle track does not reference a source file.", @"pgs-to-vobsub error message"), 200);
}
return nil;
}
// Phase 1 — re-read the PGS elementary stream from the source
// container with a fresh importer (the live muxing stream is
// discarded: sup2vob needs the whole stream before it can emit
// anything). Matroska PGS blocks store each segment with its 13-byte
// "PG" envelope removed ("PG" + 4-byte 90 kHz pts + 4 zero bytes +
// type + length — mkvmerge writes it, mkvextract reconstructs it),
// so each block is walked segment-by-segment and the envelopes are
// rebuilt with the block's own timestamp as pts.
NSError *phaseError = nil;
MP42FileImporter *reader = [[MP42FileImporter alloc] initWithURL:sourceURL error:&phaseError];
MP42Track *readerTrack = nil;
MP42Track *onlyPGSTrack = nil;
NSUInteger pgsTrackCount = 0;
for (MP42Track *candidate in reader.tracks) {
if ([candidate isMemberOfClass:[MP42SubtitleTrack class]] &&
candidate.format == kMP42SubtitleCodecType_PGS) {
pgsTrackCount++;
onlyPGSTrack = candidate;
// The document track's sourceId is its index in the source
// file (MP42File addTrack pins it), matching this freshly
// read track's trackId.
if (candidate.trackId == track.sourceId) {
readerTrack = candidate;
}
}
}
if (!readerTrack && pgsTrackCount == 1) {
readerTrack = onlyPGSTrack;
}
if (!readerTrack) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The PGS track was not found in the source file.", @"pgs-to-vobsub error message"), 201);
}
return nil;
}
// The MKV importer only fills sourceId on audio tracks, but its demux
// keys track selection (mkv_GetTrackInfo, TrackMask) on track.sourceId
// — pin it to the source index before selecting the track.
readerTrack.sourceId = readerTrack.trackId;
[reader setActiveTrack:readerTrack];
[reader startReading];
NSMutableData *pgsStream = [NSMutableData data];
if (![self drainTrack:readerTrack intoData:pgsStream timeout:kPGSPrepassTimeout]) {
// Drain out the remainder so the demuxer thread reaches its
// setDone and releases the file (its FIFO back-pressure only
// unblocks while samples are being consumed; cancelReading
// would deadlock against that same back-pressure).
[self drainTrack:readerTrack intoData:nil timeout:kPGSPrepassTimeout];
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"Reading the PGS stream timed out.", @"pgs-to-vobsub error message"), 202);
}
return nil;
}
if (_streamMalformed) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The PGS blocks were not in a recognized Matroska layout.", @"pgs-to-vobsub error message"), 208);
}
return nil;
}
if (!pgsStream.length) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The PGS track did not contain any data.", @"pgs-to-vobsub error message"), 203);
}
return nil;
}
// Phase 2 — the vendored sup2vob conversion rides the VobSub importer
// wholesale: its .sup support already converts to a temp idx/sub pair
// (the PGS canvas resolution, global 4-color palette) and its demux
// emits the raw-SPU subpic samples with gap-clearing that the subp
// mux path wants. Re-inventing any of it here would just drift.
_tempDirectory = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES]
URLByAppendingPathComponent:[NSString stringWithFormat:@"pgsvob-%@", [NSUUID UUID].UUIDString]];
[[NSFileManager defaultManager] createDirectoryAtURL:_tempDirectory withIntermediateDirectories:YES attributes:nil error:NULL];
NSURL *supURL = [_tempDirectory URLByAppendingPathComponent:@"subtitles.sup"];
if (![pgsStream writeToURL:supURL atomically:YES]) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The temporary .sup file could not be written.", @"pgs-to-vobsub error message"), 204);
}
return nil;
}
_vobsubImporter = [[MP42FileImporter alloc] initWithURL:supURL error:&phaseError];
MP42SubtitleTrack *vobTrack = nil;
for (MP42Track *candidate in _vobsubImporter.tracks) {
if ([candidate isMemberOfClass:[MP42SubtitleTrack class]]) {
vobTrack = (MP42SubtitleTrack *)candidate;
break;
}
}
if (!_vobsubImporter || !vobTrack) {
if (outError) {
*outError = phaseError ?:
MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The PGS stream did not convert to VobSub subtitles.", @"pgs-to-vobsub error message"), 205);
}
return nil;
}
[_vobsubImporter setActiveTrack:vobTrack];
[_vobsubImporter startReading];
_pendingSamples = [[NSMutableArray alloc] init];
if (![self collectSamplesFromTrack:vobTrack timeout:kVobSubPrepassTimeout]) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"Converting the PGS stream to VobSub timed out.", @"pgs-to-vobsub error message"), 206);
}
return nil;
}
_magicCookie = [_vobsubImporter magicCookieForTrack:vobTrack];
if (_magicCookie.length < sizeof(uint32_t) * 16) {
if (outError) {
*outError = MP42Error(MP42LocalizedString(@"The PGS track could not be converted.", @"pgs-to-vobsub error message"),
MP42LocalizedString(@"The converted subtitles did not carry a VobSub palette.", @"pgs-to-vobsub error message"), 207);
}
return nil;
}
// The idx `size:` line carries the frame sup2vob rendered into —
// the PGS's own canvas (MP42VobSubImporter stores it as the
// track's width/height).
_frameWidth = (uint32_t)vobTrack.width;
_frameHeight = (uint32_t)vobTrack.height;
_inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:20];
_done = dispatch_semaphore_create(0);
_inputThread = [[NSThread alloc] initWithTarget:self selector:@selector(inputDrainThreadMainRoutine) object:nil];
[_inputThread setName:@"PGS to VobSub Input Drain"];
[_inputThread start];
}
return self;
}
// Appends one demuxed PGS block's bytes to the .sup being rebuilt.
//
// Matroska (mkvmerge) stores each presentation as segments stripped of
// their 13-byte "PG" envelope — the blocks are [type][len:2][payload]
// repeated — while .sup files (and sup2vob) expect the full
// [PG][pts:4][0:4][type][len:2][payload] form. Rebuild the envelopes using
// the block's own start time as pts (MKV timestamps are nanoseconds, PTS
// ticks are 90 kHz). Blocks that already carry the envelope (some muxers
// store PGS verbatim) pass through untouched.
//
// Returns NO if a block is not walkable in either layout — the resulting
// .sup would be corrupt, so the conversion must not proceed.
- (BOOL)appendPGSBlock:(MP42SampleBuffer *)sample toData:(NSMutableData *)data
{
const unsigned char *bytes = (const unsigned char *)sample->data;
NSUInteger size = (NSUInteger)sample->size;
if (!bytes || !size) {
return YES; // the importer's leading gap placeholder carries no data
}
if (size >= 2 && bytes[0] == 'P' && bytes[1] == 'G') {
[data appendBytes:bytes length:size];
return YES;
}
UInt32 pts = (UInt32)((UInt64)sample->decodeTimestamp * 9 / 100000);
NSUInteger cursor = 0;
while (cursor < size) {
if (cursor + 3 > size) {
return NO;
}
NSUInteger segmentLength = ((NSUInteger)bytes[cursor + 1] << 8) | (NSUInteger)bytes[cursor + 2];
if (cursor + 3 + segmentLength > size) {
return NO;
}
unsigned char envelope[13];
envelope[0] = 'P'; envelope[1] = 'G';
envelope[2] = (unsigned char)(pts >> 24);
envelope[3] = (unsigned char)(pts >> 16);
envelope[4] = (unsigned char)(pts >> 8);
envelope[5] = (unsigned char)pts;
envelope[6] = envelope[7] = envelope[8] = envelope[9] = 0;
envelope[10] = bytes[cursor];
envelope[11] = bytes[cursor + 1];
envelope[12] = bytes[cursor + 2];
[data appendBytes:envelope length:sizeof(envelope)];
[data appendBytes:bytes + cursor + 3 length:segmentLength];
cursor += 3 + segmentLength;
}
return YES;
}
// Polls the track's sample queue until the EOF-flagged sample arrives,
// rebuilding the .sup stream into `data`. Polling (not dequeueAndWait)
// because the samples must keep flowing to release the demuxer thread's
// bounded-FIFO back-pressure while this thread works.
- (BOOL)drainTrack:(MP42Track *)track intoData:(nullable NSMutableData *)data timeout:(NSTimeInterval)timeout
{
NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];
for (;;) {
MP42SampleBuffer *sample = [track copyNextSample];
if (!sample) {
if ([deadline timeIntervalSinceNow] < 0) {
return NO;
}
usleep(2000);
continue;
}
if (sample->flags & MP42SampleBufferFlagEndOfFile) {
return YES;
}
if (data && ![self appendPGSBlock:sample toData:data]) {
_streamMalformed = YES;
// Keep draining to EOF anyway (back-pressure, see above).
}
}
}
// Same polling loop, collecting whole samples (they replay from
// -copyEncodedSample later).
- (BOOL)collectSamplesFromTrack:(MP42Track *)track timeout:(NSTimeInterval)timeout
{
NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout];
for (;;) {
MP42SampleBuffer *sample = [track copyNextSample];
if (!sample) {
if ([deadline timeIntervalSinceNow] < 0) {
return NO;
}
usleep(2000);
continue;
}
if (sample->flags & MP42SampleBufferFlagEndOfFile) {
return YES;
}
[_pendingSamples addObject:sample];
}
}
- (void)addSample:(MP42SampleBuffer *)sample
{
[_inputSamplesBuffer enqueue:sample];
}
- (nullable MP42SampleBuffer *)copyEncodedSample
{
if (_pendingSamples.count) {
MP42SampleBuffer *sample = _pendingSamples.firstObject;
[_pendingSamples removeObjectAtIndex:0];
return sample;
}
// The muxer loop ends this track on the EOF flag; emit it exactly once,
// and only after the live input stream ended too (so cancelling or a
// stuck importer can't leave the muxer holding an "unfinished" track
// whose data is already complete but unrecognized).
if (_inputDone && !_eofSent) {
_eofSent = YES;
MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init];
sample->flags |= MP42SampleBufferFlagEndOfFile;
return sample;
}
return nil;
}
- (nullable NSData *)magicCookie
{
return _magicCookie;
}
- (void)cancel
{
[_inputSamplesBuffer cancel];
dispatch_semaphore_wait(_done, DISPATCH_TIME_FOREVER);
}
- (void)dealloc
{
if (_tempDirectory) {
[[NSFileManager defaultManager] removeItemAtURL:_tempDirectory error:NULL];
}
}
@end
+5 -2
View File
@@ -51,9 +51,12 @@ 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
// Community-convention track name from subtitle type tokens in the filename
// (sdh/cc/forced/commentary/lyrics): any flag set yields "SDH", nil when absent
NSString * getFilenameSubtitlesTrackName(CFStringRef filename);
// Same token recognition applied to arbitrary text (e.g. an MKV TrackEntry
// name carrying the source subtitle file's name)
NSString * getSubtitleTypeTokenFromString(NSString *text);
NSString * guessStringLanguage(NSString *string);
MP4Duration getTrackDuration(MP4FileHandle fileHandle, MP4TrackId trackId);
+32 -40
View File
@@ -361,67 +361,59 @@ NSString * getFilenameLanguage(CFStringRef filename)
// 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.
// like VLC display. Any flag set names the track "SDH": the release-naming
// crowd treats SDH/CC/forced/commentary/lyrics as one bucket of
// not-plain-subtitles, and one recognizable name serves players better than
// five. Returns nil when the text carries no such token.
// Dashes are separators here (unlike getFilenameLanguage) so
// "hearing-impaired" splits into hit-able tokens too.
static NSString * subtitleTypeTokenFromFilename(CFStringRef filename)
static NSString * subtitleTypeTokenFromString(NSString *text)
{
NSString *baseName = [(__bridge NSString *)filename lastPathComponent].stringByDeletingPathExtension;
if (!text.length) {
return nil;
}
NSArray<NSString *> *tokens =
[baseName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@". _-"]];
[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@". _-"]];
BOOL forced = NO, lyrics = NO, commentary = NO, closedCaptions = NO, hearingImpaired = NO;
BOOL anyFlag = 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;
[lowercaseToken isEqualToString:@"impaired"] || [lowercaseToken isEqualToString:@"deaf"] ||
[lowercaseToken isEqualToString:@"cc"] ||
[lowercaseToken isEqualToString:@"commentary"] || [lowercaseToken isEqualToString:@"commentaries"] ||
[lowercaseToken isEqualToString:@"forced"] ||
[lowercaseToken isEqualToString:@"lyrics"] || [lowercaseToken isEqualToString:@"lyric"]) {
anyFlag = 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;
anyFlag = 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;
return anyFlag ? @"SDH" : nil;
}
// Track name for any subtitle descriptor (a file path, or an MKV TrackEntry
// name): "SDH" when it carries a community type token (sdh/cc/forced/
// commentary/lyrics — any flag set means SDH), nil when it carries none.
NSString * getSubtitleTypeTokenFromString(NSString *text)
{
return subtitleTypeTokenFromString(text);
}
// 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.
// naming the track after the type tokens the filename carries ("SDH").
// 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 *baseName = [(__bridge NSString *)filename lastPathComponent].stringByDeletingPathExtension;
return subtitleTypeTokenFromString(baseName);
}
NSString *guessStringLanguage(NSString *stringFromFileAtURL)
+3 -2
View File
@@ -17,8 +17,9 @@ import Foundation
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.
/// Upstream declares this in main.swift; inside the framework
/// MP42SupConverter turns it on for every import — the muxed subpic track
/// keeps the PGS's own canvas size instead of the DVD frame.
nonisolated(unsafe) var fullFramePassthrough = false
// MARK: - DVD subtitle frame (post scale + color reduction)
+21 -4
View File
@@ -20,9 +20,12 @@ import Foundation
/// 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.
/// Mirrors sup2vob's CLI orchestration with `--full`: BT.709 palette
/// interpretation, and the source geometry is kept — frames stay at the
/// resolution the PGS itself defines (its PCS canvas, e.g. 1920x1080),
/// so the muxed subpic track matches the subtitles' authored size
/// instead of being downscaled to the DVD frame. The DVD frame from the
/// frame-rate code stays as fallback for a stream with no usable canvas.
@objc(convertSupAtURL:toSubAtURL:language:languageName:error:)
public static func convertSup(at inputURL: URL,
toSubAt subURL: URL,
@@ -40,7 +43,21 @@ import Foundation
throw conversionError(101, "\(inputURL.lastPathComponent): no compositions found")
}
let resolution = DVDResolution.from(frameRateCode: compositions[0].frameRateCode)
// Upstream's `--full` mode: keep the source frames verbatim. The
// CLI's main.swift set this global from the flag; enabling it here
// is the framework's one behavioral adaptation of the vendored
// sources (upstream's logic and geometry code stay untouched).
fullFramePassthrough = true
// The size the muxer writes: the display resolution the PGS itself
// declares in its PCS canvas (1920x1080 for a full-HD source). Fall
// back to the frame-rate's DVD frame only if the stream defines no
// usable canvas.
let canvasWidth = compositions[0].canvasWidth
let canvasHeight = compositions[0].canvasHeight
let resolution = canvasWidth > 0 && canvasHeight > 0
? DVDResolution(width: canvasWidth, height: canvasHeight)
: 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")
+10
View File
@@ -70,6 +70,9 @@
A910B5FA18394EB20064028F /* sfifo.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2641823923200416A4E /* sfifo.c */; };
A910B5FD18394EB20064028F /* MP42TesseractOCR.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2451823923100416A4E /* MP42TesseractOCR.mm */; };
A910B5FF18394EB20064028F /* MP42BitmapSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */; };
AA00000318394EB20064028F /* MP42PgsToVobSubConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = AA00000118394EB20064028F /* MP42PgsToVobSubConverter.h */; };
AA00000418394EB20064028F /* MP42PgsToVobSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = AA00000218394EB20064028F /* MP42PgsToVobSubConverter.m */; };
AA00000518394EB20064028F /* MP42PgsToVobSubConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = AA00000218394EB20064028F /* MP42PgsToVobSubConverter.m */; };
A910B60118394EB20064028F /* MP42AudioConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2201823923100416A4E /* MP42AudioConverter.m */; };
A910B60318394EB20064028F /* MP42H264Importer.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2351823923100416A4E /* MP42H264Importer.mm */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-checker"; }; };
A910B60518394EB20064028F /* MP42VobSubImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2571823923200416A4E /* MP42VobSubImporter.m */; };
@@ -405,6 +408,8 @@
A9B9C2241823923100416A4E /* MP42AVFImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AVFImporter.m; sourceTree = "<group>"; };
A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42BitmapSubConverter.h; sourceTree = "<group>"; };
A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42BitmapSubConverter.m; sourceTree = "<group>"; };
AA00000118394EB20064028F /* MP42PgsToVobSubConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42PgsToVobSubConverter.h; sourceTree = "<group>"; };
AA00000218394EB20064028F /* MP42PgsToVobSubConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42PgsToVobSubConverter.m; sourceTree = "<group>"; };
A9B9C2271823923100416A4E /* MP42CCImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42CCImporter.h; sourceTree = "<group>"; };
A9B9C2281823923100416A4E /* MP42CCImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42CCImporter.m; sourceTree = "<group>"; };
A9B9C2291823923100416A4E /* MP42ChapterTrack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42ChapterTrack.h; sourceTree = "<group>"; };
@@ -819,6 +824,8 @@
A9B9C2451823923100416A4E /* MP42TesseractOCR.mm */,
A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */,
A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */,
AA00000118394EB20064028F /* MP42PgsToVobSubConverter.h */,
AA00000218394EB20064028F /* MP42PgsToVobSubConverter.m */,
A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */,
A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */,
A908010C1D4B83A3002B6950 /* MP42AudioDecoder.h */,
@@ -919,6 +926,7 @@
A91711E6187D547D00459495 /* MP42PreviewGenerator.h in Headers */,
A9B9C2951823923200416A4E /* MP42SrtImporter.h in Headers */,
A9B9C2701823923200416A4E /* MP42BitmapSubConverter.h in Headers */,
AA00000318394EB20064028F /* MP42PgsToVobSubConverter.h in Headers */,
A941C95E1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */,
A9B9C2721823923200416A4E /* MP42CCImporter.h in Headers */,
A9B9C2AF1823923200416A4E /* sfifo.h in Headers */,
@@ -1096,6 +1104,7 @@
A910B5FA18394EB20064028F /* sfifo.c in Sources */,
A910B5FD18394EB20064028F /* MP42TesseractOCR.mm in Sources */,
A910B5FF18394EB20064028F /* MP42BitmapSubConverter.m in Sources */,
AA00000418394EB20064028F /* MP42PgsToVobSubConverter.m in Sources */,
A910B60118394EB20064028F /* MP42AudioConverter.m in Sources */,
A97EA7CA1D4B8A2D00257CEA /* FFmpegUtils.m in Sources */,
A941C9591F82996600FC5E8D /* MP42TextSubConverter.m in Sources */,
@@ -1158,6 +1167,7 @@
5AB1E22600000000000000C4 /* MP42SupConverter.swift in Sources */,
A941C9601F82A9B900FC5E8D /* MP42SSAConverter.m in Sources */,
A9B9C2711823923200416A4E /* MP42BitmapSubConverter.m in Sources */,
AA00000518394EB20064028F /* MP42PgsToVobSubConverter.m in Sources */,
A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */,
A9ED5B0F1F824A9B00E0E4FA /* MP42SSAParser.m in Sources */,
A9B9C2A21823923200416A4E /* MP42VobSubImporter.m in Sources */,
+2
View File
@@ -0,0 +1,2 @@
# build artifact (see Makefile)
/sup2vob
+37
View File
@@ -0,0 +1,37 @@
# sup2vob — PGS (.sup) -> VobSub (.sub/.idx) converter CLI
#
# Slim CLI: the conversion sources are NOT vendored a second time here —
# they are the framework's ../MP42/Sup2Vob/ files, so the CLI and the app
# always run identical conversion code (the CLI's byte-identical `--full`
# output is the framework converter's verification oracle). Only
# main.swift lives in this directory; see its header for the single
# upstream adaptation. MP42SupConverter.swift (the framework's ObjC
# facade over the same conversion) is deliberately not compiled in.
#
# Build: make -> ./sup2vob
# Clean: make clean
SWIFTC ?= swiftc
OPTFLAGS ?= -O
TARGET := sup2vob
PREFIX ?= /usr/local
CONV := ../MP42/Sup2Vob
SOURCES := main.swift $(CONV)/PGS.swift $(CONV)/Convert.swift $(CONV)/VobSub.swift
.PHONY: all clean rebuild install
all: $(TARGET)
$(TARGET): $(SOURCES)
$(SWIFTC) $(OPTFLAGS) -o $(TARGET) $(SOURCES)
clean:
rm -f $(TARGET)
rebuild: clean all
# extractsubs (shipped in the Subler app bundle's Resources) resolves
# sup2vob from PATH, so a rebuild only takes effect once installed
# (usually: sudo make install).
install: $(TARGET)
install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin/$(TARGET)
+140
View File
@@ -0,0 +1,140 @@
//
// main.swift
// sup2vob CLI
//
// sup2vob's CLI entry point (https://git.technomancer.com/Scott-Files/
// sup2vob) kept identical to upstream with one adaptation: upstream
// declares the CLI globals `debugFrames` and `fullFramePassthrough` here,
// but this slim build shares the conversion sources with the framework
// target, where Convert.swift owns both declarations — re-declaring them
// would collide. Assignments ("--debug", "--full") stay upstream-exact.
// The Makefile compiles this file against ../MP42/Sup2Vob/, so the CLI and
// the framework always run the same conversion code.
//
import Foundation
let usage = """
usage: sup2vob [options] <input.sup>
Converts a Blu-ray PGS .sup file to VobSub (.sub + .idx)
options:
-o <file> output .sub path (a matching .idx is written beside it);
default: <input> with .sup replaced by .sub
--ntsc force a 720x480 DVD frame (default: auto from the PGS rate)
--pal force a 720x576 DVD frame (default: auto from the PGS rate)
--full pass through the source frame size (e.g. 1920x1080) with
no scaling
--lang <id> two-letter language id for the .idx (default: en)
--langname <n> alternative language name for the commented alt: line
(default: English)
--bt601 interpret the PGS palette as BT.601 (default: BT.709)
--debug trace per-frame conversion decisions on stderr
-h, --help show usage and exit
"""
var outputPath: String? = nil
var input: String? = nil
var forcedResolution: DVDResolution? = nil
// fullFramePassthrough: declared in Convert.swift (see file header).
var lang = "en"
var langName = "English"
var colorSpace: ColorSpace = .bt709
var args = Array(CommandLine.arguments.dropFirst())
while !args.isEmpty {
let arg = args.removeFirst()
switch arg {
case "-h", "--help":
print(usage)
exit(0)
case "-o":
guard !args.isEmpty else { FileHandle.standardError.write("missing argument for -o\n".data(using: .utf8)!); exit(1) }
outputPath = args.removeFirst()
case "--ntsc": forcedResolution = .ntsc
case "--pal": forcedResolution = .pal
case "--full": fullFramePassthrough = true
case "--lang":
guard !args.isEmpty else { FileHandle.standardError.write("missing argument for --lang\n".data(using: .utf8)!); exit(1) }
lang = args.removeFirst()
case "--langname":
guard !args.isEmpty else { FileHandle.standardError.write("missing argument for --langname\n".data(using: .utf8)!); exit(1) }
langName = args.removeFirst()
case "--bt601": colorSpace = .bt601
case "-bt601", "--bt709": colorSpace = .bt709
case "--debug": debugFrames = true
default:
if arg.hasPrefix("-") {
FileHandle.standardError.write("unknown option: \(arg)\n".data(using: .utf8)!)
exit(1)
}
if input == nil { input = arg }
}
}
guard let input else {
FileHandle.standardError.write(usage.data(using: .utf8)!)
exit(1)
}
guard let fileData = FileManager.default.contents(atPath: input) else {
FileHandle.standardError.write("cannot read \(input)\n".data(using: .utf8)!)
exit(1)
}
let fileBytes = [UInt8](fileData)
let compositions: [Composition]
do {
compositions = try readPGS(fileBytes, space: colorSpace)
} catch let e as PGSError {
FileHandle.standardError.write("\(input): \(e)\n".data(using: .utf8)!)
exit(1)
} catch {
FileHandle.standardError.write("\(input): \(error)\n".data(using: .utf8)!)
exit(1)
}
guard !compositions.isEmpty else {
FileHandle.standardError.write("\(input): no compositions found\n".data(using: .utf8)!)
exit(1)
}
let resolution = forcedResolution ?? (fullFramePassthrough
? DVDResolution(width: compositions[0].canvasWidth, height: compositions[0].canvasHeight)
: DVDResolution.from(frameRateCode: compositions[0].frameRateCode))
let result = convertToDVD(compositions, resolution: resolution)
if debugFrames, let frame = result.frames.first {
let indexToGrayLUT: [UInt8] = [0, 85, 170, 255]
var pgm = "P5\n\(frame.width) \(frame.height)\n255\n".data(using: .ascii)!
pgm.append(contentsOf: frame.paletteIndices.map { indexToGrayLUT[Int($0)] })
try? pgm.write(to: URL(fileURLWithPath: "/tmp/suptest/dbg_frame0.pgm"))
FileHandle.standardError.write("debug: frame0 idx → /tmp/suptest/dbg_frame0.pgm (\(frame.width)x\(frame.height) x=\(frame.left) y=\(frame.top))\n".data(using: .utf8)!)
}
guard !result.frames.isEmpty else {
FileHandle.standardError.write("\(input): no displayable subtitle frames\n".data(using: .utf8)!)
exit(1)
}
let subPath = outputPath ?? (input.hasSuffix(".sup") ? String(input.dropLast(4)) + ".sub" : input + ".sub")
let idxPath = (subPath as NSString).deletingPathExtension + ".idx"
let subFile = writeSub(result.frames)
let idxText = writeIdx(resolution: resolution, fourColorPalette: result.fourColorPalette,
frames: result.frames, filePositions: subFile.filePositions,
lang: lang, langName: langName)
do {
try Data(subFile.bytes).write(to: URL(fileURLWithPath: subPath))
try idxText.write(toFile: idxPath, atomically: true, encoding: .ascii)
} catch {
FileHandle.standardError.write("write failed: \(error)\n".data(using: .utf8)!)
exit(1)
}
let visiblePaletteHex = result.fourColorPalette.dropFirst().filter { $0.isVisible }
.map { String(format: "#%02x%02x%02x", $0.r, $0.g, $0.b) }.joined(separator: " ")
FileHandle.standardError.write("""
sup2vob: \(result.frames.count) frames → \(subPath) (\(subFile.bytes.count) bytes) + \(idxPath)
frame size \(resolution.width)x\(resolution.height), palette: \(visiblePaletteHex)
""".data(using: .utf8)!)