Compare commits

..
8 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
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
Scott GarrettandClaude Code 7ff1ed4d0b Serve the contrib submodule URL over HTTPS
The repos are public; hardcoded gitea@ SSH URLs made recursive clones
fail for anyone without a key on the server. Contributors keep SSH via
a url.insteadOf rewrite on their own machines.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 14:00:19 -05:00
Scott GarrettandClaude Code a287ea6404 Adopt Xcode 27.2 project migration
Purely settings: deployment target raised to the toolchain-recommended
value, string-catalog symbols enabled, c11/c++11 module-verification
standards, LastUpgradeCheck bumped, and Xcode's cosmetic re-sort of the
Matroska file entries in the pbxproj (same files, same targets).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:53:01 -05:00
Scott GarrettandClaude Code 79c251c6dc Move the contrib submodule to Gitea
Mirror of SublerApp/contrib now lives at Scott-Files/contrib on
git.technomancer.com so every dependency builds from the fork's own
server over SSH.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-28 13:46:00 -05:00
22 changed files with 1968 additions and 90 deletions

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "contrib"]
path = contrib
url = https://github.com/SublerApp/contrib.git
url = https://git.technomancer.com/Scott-Files/contrib.git
+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
+6
View File
@@ -51,6 +51,12 @@ FourCharCode getTrackMediaSubType(MP4FileHandle fileHandle, MP4TrackId Id, uint3
NSString * getTrackLanguage(MP4FileHandle fileHandle, MP4TrackId Id);
NSString * getFilenameLanguage(CFStringRef filename);
// 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);
+106 -49
View File
@@ -299,64 +299,121 @@ 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. 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 * subtitleTypeTokenFromString(NSString *text)
{
if (!text.length) {
return nil;
}
NSArray<NSString *> *tokens =
[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@". _-"]];
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"] ||
[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.)
anyFlag = YES;
}
}
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 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)
{
NSString *baseName = [(__bridge NSString *)filename lastPathComponent].stringByDeletingPathExtension;
return subtitleTypeTokenFromString(baseName);
}
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];
+279
View File
@@ -0,0 +1,279 @@
//
// 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
/// 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)
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)
}
+79
View File
@@ -0,0 +1,79 @@
//
// 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 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,
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")
}
// 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")
}
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)
}
+74 -24
View File
@@ -7,6 +7,18 @@
objects = {
/* Begin PBXBuildFile section */
5AB1E120261124000000000007 /* MP42Ebml.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000001 /* MP42Ebml.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000008 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; };
5AB1E120261124000000000009 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; };
5AB1E120261124000000000010 /* MP42MatroskaTagMapping.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000011 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; };
5AB1E120261124000000000012 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; };
5AB1E120261124000000000013 /* MP42MkvTagWriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000005 /* MP42MkvTagWriter.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000014 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; };
5AB1E120261124000000000015 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; };
5AB1E120261124000000000024 /* MP42MkvRemuxer.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000021 /* MP42MkvRemuxer.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000025 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; };
5AB1E120261124000000000026 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; };
6661A2EE20890B4400B1A669 /* MP42Foundation.h in Headers */ = {isa = PBXBuildFile; fileRef = 6661A2ED20890B4400B1A669 /* MP42Foundation.h */; settings = {ATTRIBUTES = (Public, ); }; };
7538B2052505AB1800898792 /* SampleCursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9B5C954241A302E000ACD15 /* SampleCursor.swift */; };
A9022A941D6F3FD9005F0920 /* MP42MetadataItem.h in Headers */ = {isa = PBXBuildFile; fileRef = A9022A921D6F3FD9005F0920 /* MP42MetadataItem.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -58,22 +70,13 @@
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 */; };
A910B60718394EB20064028F /* MP42MkvImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C23F1823923100416A4E /* MP42MkvImporter.m */; };
5AB1E120261124000000000007 /* MP42Ebml.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000001 /* MP42Ebml.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000008 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; };
5AB1E120261124000000000009 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; };
5AB1E120261124000000000010 /* MP42MatroskaTagMapping.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000011 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; };
5AB1E120261124000000000012 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; };
5AB1E120261124000000000013 /* MP42MkvTagWriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000005 /* MP42MkvTagWriter.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000014 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; };
5AB1E120261124000000000015 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; };
5AB1E120261124000000000024 /* MP42MkvRemuxer.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000021 /* MP42MkvRemuxer.h */; settings = {ATTRIBUTES = (Public, ); }; };
5AB1E120261124000000000025 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; };
5AB1E120261124000000000026 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; };
A910B60918394EB20064028F /* MP42Mp4Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2411823923100416A4E /* MP42Mp4Importer.m */; };
A910B60D18394EB20064028F /* MP42SrtImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24B1823923100416A4E /* MP42SrtImporter.m */; };
A910B60F18394EB20064028F /* MP42AVFImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2241823923100416A4E /* MP42AVFImporter.m */; };
@@ -276,6 +279,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 */
@@ -297,6 +308,15 @@
50682E722B86B6BC008DB28B /* es-419 */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "es-419"; path = "es-419.lproj/InfoPlist.strings"; sourceTree = "<group>"; };
50682E732B86B6CC008DB28B /* es-419 */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "es-419"; path = "es-419.lproj/Localizable.strings"; sourceTree = "<group>"; };
50682E742B86B6E3008DB28B /* es-419 */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "es-419"; path = "es-419.lproj/Localizable.strings"; sourceTree = "<group>"; };
5AB1E120261124000000000001 /* MP42Ebml.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Ebml.h; sourceTree = "<group>"; };
5AB1E120261124000000000002 /* MP42Ebml.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Ebml.m; sourceTree = "<group>"; };
5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MatroskaTagMapping.h; sourceTree = "<group>"; };
5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MatroskaTagMapping.m; sourceTree = "<group>"; };
5AB1E120261124000000000005 /* MP42MkvTagWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvTagWriter.h; sourceTree = "<group>"; };
5AB1E120261124000000000006 /* MP42MkvTagWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvTagWriter.m; sourceTree = "<group>"; };
5AB1E120261124000000000021 /* MP42MkvRemuxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvRemuxer.h; sourceTree = "<group>"; };
5AB1E120261124000000000022 /* MP42MkvRemuxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvRemuxer.m; sourceTree = "<group>"; };
5AB1E120261124000000000023 /* MP42MkvTagWriter+Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MP42MkvTagWriter+Internal.h"; sourceTree = "<group>"; };
6661A2ED20890B4400B1A669 /* MP42Foundation.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MP42Foundation.h; sourceTree = "<group>"; };
7538B2042505A99700898792 /* mp42-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "mp42-Bridging-Header.h"; sourceTree = "<group>"; };
7538B2062506B29D00898792 /* MP42-Shared-Swift.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MP42-Shared-Swift.h"; sourceTree = "<group>"; };
@@ -388,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>"; };
@@ -413,15 +435,6 @@
A9B9C23D1823923100416A4E /* MP42Metadata.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Metadata.m; sourceTree = "<group>"; };
A9B9C23E1823923100416A4E /* MP42MkvImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvImporter.h; sourceTree = "<group>"; };
A9B9C23F1823923100416A4E /* MP42MkvImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvImporter.m; sourceTree = "<group>"; };
5AB1E120261124000000000001 /* MP42Ebml.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Ebml.h; sourceTree = "<group>"; };
5AB1E120261124000000000002 /* MP42Ebml.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Ebml.m; sourceTree = "<group>"; };
5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MatroskaTagMapping.h; sourceTree = "<group>"; };
5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MatroskaTagMapping.m; sourceTree = "<group>"; };
5AB1E120261124000000000005 /* MP42MkvTagWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvTagWriter.h; sourceTree = "<group>"; };
5AB1E120261124000000000006 /* MP42MkvTagWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvTagWriter.m; sourceTree = "<group>"; };
5AB1E120261124000000000021 /* MP42MkvRemuxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvRemuxer.h; sourceTree = "<group>"; };
5AB1E120261124000000000022 /* MP42MkvRemuxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvRemuxer.m; sourceTree = "<group>"; };
5AB1E120261124000000000023 /* MP42MkvTagWriter+Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MP42MkvTagWriter+Internal.h"; sourceTree = "<group>"; };
A9B9C2401823923100416A4E /* MP42Mp4Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Mp4Importer.h; sourceTree = "<group>"; };
A9B9C2411823923100416A4E /* MP42Mp4Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Mp4Importer.m; sourceTree = "<group>"; };
A9B9C2421823923100416A4E /* MP42Muxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Muxer.h; sourceTree = "<group>"; };
@@ -486,6 +499,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 +567,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 +642,7 @@
A9B9C2301823923100416A4E /* MP42File.h */,
A9B9C2311823923100416A4E /* MP42File.m */,
A9FD169E27661B690096BBA8 /* SampleDescription.swift */,
5AB1E22600000000000000D1 /* Sup2Vob */,
A9B9C2501823923100416A4E /* MP42Track.h */,
A9B9C2511823923100416A4E /* MP42Track.m */,
A99FCBC31BAD65EF0058E27A /* MP42Track+Private.h */,
@@ -795,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 */,
@@ -895,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 */,
@@ -970,7 +1002,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
CLASSPREFIX = MP42;
LastUpgradeCheck = 2700;
LastUpgradeCheck = 2720;
ORGANIZATIONNAME = "Damiano Galassi";
TargetAttributes = {
A910B5A218394E900064028F = {
@@ -1052,6 +1084,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 */,
@@ -1068,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 */,
@@ -1124,8 +1161,13 @@
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 */,
AA00000518394EB20064028F /* MP42PgsToVobSubConverter.m in Sources */,
A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */,
A9ED5B0F1F824A9B00E0E4FA /* MP42SSAParser.m in Sources */,
A9B9C2A21823923200416A4E /* MP42VobSubImporter.m in Sources */,
@@ -1231,6 +1273,7 @@
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
OTHER_LDFLAGS = (
"-read_only_relocs",
suppress,
@@ -1261,6 +1304,7 @@
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
OTHER_LDFLAGS = (
"-read_only_relocs",
suppress,
@@ -1356,10 +1400,11 @@
"$(SRCROOT)/contrib/Tesseract/lib",
"$(SRCROOT)/contrib/ffmpeg/lib",
);
MACOSX_DEPLOYMENT_TARGET = 10.13;
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
ONLY_ACTIVE_ARCH = YES;
OTHER_CFLAGS = "";
OTHER_LDFLAGS = "-w";
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_INCLUDE_PATHS = "$(SRCROOT)/contrib/mp4v2/";
SWIFT_OBJC_INTERFACE_HEADER_NAME = "MP42-Swift.h";
SWIFT_PRECOMPILE_BRIDGING_HEADER = NO;
@@ -1451,9 +1496,10 @@
"$(SRCROOT)/contrib/Tesseract/lib",
"$(SRCROOT)/contrib/ffmpeg/lib",
);
MACOSX_DEPLOYMENT_TARGET = 10.13;
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
OTHER_CFLAGS = "";
OTHER_LDFLAGS = "-w";
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_INCLUDE_PATHS = "$(SRCROOT)/contrib/mp4v2/";
SWIFT_OBJC_INTERFACE_HEADER_NAME = "MP42-Swift.h";
@@ -1487,6 +1533,8 @@
"@executable_path/../Frameworks",
"@loader_path/Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "c11 c++11";
PRODUCT_BUNDLE_IDENTIFIER = "com.galad.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = MP42Foundation;
SKIP_INSTALL = YES;
@@ -1519,6 +1567,8 @@
"@executable_path/../Frameworks",
"@loader_path/Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "c11 c++11";
PRODUCT_BUNDLE_IDENTIFIER = "com.galad.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = MP42Foundation;
SKIP_INSTALL = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2700"
LastUpgradeVersion = "2720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2700"
LastUpgradeVersion = "2720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+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)!)