Files
MP42Foundation/MP42/MP42PgsToVobSubConverter.m
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

386 lines
16 KiB
Objective-C

//
// 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