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>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-28 20:00:08 -05:00
1 parent e02f60b5f6
commit 57772086a5
9 files changed
+552 -52

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 {
+46 -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,54 @@ 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 live in the DVD frame (720x480/576),
// not the PGS source video's frame — and an MKV-sourced track
// carries no size at all — so steer the subpic branch's
// trackWidth/trackHeight preference with it.
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
+384
View File
@@ -0,0 +1,384 @@
//
// 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
// (DVD 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 DVD frame sup2vob rendered into
// (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)
+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 */,