Compare commits
23
Commits
0a8f6fe4ea
...
72e879e316
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72e879e316 | ||
|
|
837aa1c098 | ||
|
|
57772086a5 | ||
|
|
e02f60b5f6 | ||
|
|
30dd96ff79 | ||
|
|
7ff1ed4d0b | ||
|
|
a287ea6404 | ||
|
|
79c251c6dc | ||
|
|
e7c7b80e8f | ||
|
|
e8231dea59 | ||
|
|
10dcee30a6 | ||
|
|
0cf79eca1c | ||
|
|
8ba3f25a2c | ||
|
|
e42855867d | ||
|
|
1040f47542 | ||
|
|
bfa477b799 | ||
|
|
37cd9b40b9 | ||
|
|
bb12164229 | ||
|
|
f883d07809 | ||
|
|
0a3c902ce7 | ||
|
|
cf35350ad3 | ||
|
|
616cd9733b | ||
|
|
993151da53 |
No files matched your search
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "contrib"]
|
||||
path = contrib
|
||||
url = https://github.com/SublerApp/contrib.git
|
||||
url = https://git.technomancer.com/Scott-Files/contrib.git
|
||||
+29
-6
@@ -216,25 +216,48 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
|
||||
- (void)setVolume:(float)newVolume
|
||||
{
|
||||
if (_volume != newVolume) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setVolume:_volume];
|
||||
}
|
||||
|
||||
_volume = newVolume;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"volume"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"volume"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setFallbackTrack:(MP42Track *)newFallbackTrack
|
||||
{
|
||||
MP42Track *fallbackTrackStrongRef = _fallbackTrack;
|
||||
if (fallbackTrackStrongRef != newFallbackTrack) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setFallbackTrack:fallbackTrackStrongRef];
|
||||
}
|
||||
|
||||
_fallbackTrack = newFallbackTrack;
|
||||
_fallbackTrackId = 0;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"fallback"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"fallback"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setFollowsTrack:(MP42Track *)newFollowsTrack
|
||||
{
|
||||
MP42Track *followsTrackStrongRef = _followsTrack;
|
||||
if (followsTrackStrongRef != newFollowsTrack) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setFollowsTrack:followsTrackStrongRef];
|
||||
}
|
||||
|
||||
_followsTrack = newFollowsTrack;
|
||||
_followsTrackId = 0;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"follows"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"follows"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)formatSummary
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
#import "MP42PrivateUtilities.h"
|
||||
#import "MP42SubtitleTrack.h"
|
||||
|
||||
#import "MP42OCRWrapper.h"
|
||||
#import "MP42TesseractOCR.h"
|
||||
#import "MP42VisionOCR.h"
|
||||
#import "MP42SubUtilities.h"
|
||||
|
||||
#include "FFmpegUtils.h"
|
||||
@@ -32,7 +33,7 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
{
|
||||
NSThread *decoderThread;
|
||||
|
||||
MP42OCRWrapper *_ocr;
|
||||
id<MP42TextRecognizer> _ocr;
|
||||
CIContext *_imgContext;
|
||||
AVCodec *avCodec;
|
||||
AVCodecContext *avContext;
|
||||
@@ -426,7 +427,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
|
||||
srcMagicCookie = [track.importer magicCookieForTrack:track];
|
||||
|
||||
_ocr = [[MP42OCRWrapper alloc] initWithLanguage:track.language];
|
||||
_ocr = [[MP42TesseractOCR alloc] initWithLanguage:track.language];
|
||||
// _ocr = [[MP42VisionOCR alloc] initWithLanguage:track.language];
|
||||
|
||||
if (format == kMP42SubtitleCodecType_VobSub) {
|
||||
// Launch the vobsub decoder thread.
|
||||
|
||||
+50
-14
@@ -12,7 +12,6 @@
|
||||
#import "MP42PrivateUtilities.h"
|
||||
#import "MP42MediaFormat.h"
|
||||
|
||||
MP42_OBJC_DIRECT_MEMBERS
|
||||
@implementation MP42ChapterTrack {
|
||||
@private
|
||||
NSMutableArray<MP42TextSample *> *_chapters;
|
||||
@@ -102,19 +101,24 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
return [[MP42ChapterTrack alloc] initWithTextFile:URL];
|
||||
}
|
||||
|
||||
- (NSString *)defaultName {
|
||||
- (NSString *)defaultName
|
||||
{
|
||||
NSBundle *bundle = [NSBundle bundleForClass:[MP42ChapterTrack class]];
|
||||
return NSLocalizedStringFromTableInBundle(@"Chapter Track", @"Localizable", bundle, @"Default Chapter Track name");
|
||||
}
|
||||
|
||||
- (NSUInteger)addChapter:(MP42TextSample *)chapter
|
||||
{
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
|
||||
[_chapters addObject:chapter];
|
||||
[_chapters sortUsingSelector:@selector(compare:)];
|
||||
|
||||
[[self.undo prepareWithInvocationTarget:self] removeChapter:chapter];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
}
|
||||
|
||||
return [_chapters indexOfObject:chapter];
|
||||
}
|
||||
|
||||
@@ -129,7 +133,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
return idx;
|
||||
}
|
||||
|
||||
- (NSUInteger)addChapter:(NSString *)title image:(MP42Image *)image duration:(uint64_t)timestamp {
|
||||
- (NSUInteger)addChapter:(NSString *)title image:(MP42Image *)image duration:(uint64_t)timestamp
|
||||
{
|
||||
MP42TextSample *newChapter = [[MP42TextSample alloc] init];
|
||||
newChapter.title = title;
|
||||
newChapter.image = image;
|
||||
@@ -140,10 +145,22 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
return idx;
|
||||
}
|
||||
|
||||
- (NSUInteger)indexOfChapter:(MP42TextSample *)chapterSample {
|
||||
- (NSUInteger)indexOfChapter:(MP42TextSample *)chapterSample
|
||||
{
|
||||
return [_chapters indexOfObject:chapterSample];
|
||||
}
|
||||
|
||||
- (void)removeChapter:(MP42TextSample *)chapter
|
||||
{
|
||||
[[self.undo prepareWithInvocationTarget:self] addChapter:chapter];
|
||||
[_chapters removeObject:chapter];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)removeChapterAtIndex:(NSUInteger)index
|
||||
{
|
||||
[self removeChaptersAtIndexes:[NSIndexSet indexSetWithIndex:index]];
|
||||
@@ -151,24 +168,43 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
|
||||
- (void)removeChaptersAtIndexes:(NSIndexSet *)indexes
|
||||
{
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
[_chapters removeObjectsAtIndexes:indexes];
|
||||
NSArray<MP42TextSample *> *toBeRemoved = [_chapters objectsAtIndexes:indexes];
|
||||
|
||||
for (MP42TextSample *chapter in toBeRemoved) {
|
||||
[self removeChapter:chapter];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTimestamp:(MP4Duration)timestamp forChapter:(MP42TextSample *)chapterSample
|
||||
{
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
MP4Duration previousTimestamp = chapterSample.timestamp;
|
||||
|
||||
if (previousTimestamp != timestamp) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setTimestamp:previousTimestamp forChapter:chapterSample];
|
||||
}
|
||||
|
||||
[chapterSample setTimestamp:timestamp];
|
||||
[_chapters sortUsingSelector:@selector(compare:)];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTitle:(NSString *)title forChapter:(MP42TextSample *)chapterSample
|
||||
{
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
NSString *previousTitle = chapterSample.title;
|
||||
if ([previousTitle isEqualToString:title] == NO) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setTitle:previousTitle forChapter:chapterSample];
|
||||
}
|
||||
|
||||
[chapterSample setTitle:title];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_areChaptersEdited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (MP42TextSample *)chapterAtIndex:(NSUInteger)index
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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];
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
//
|
||||
// MP42Ebml.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Minimal EBML (Extensible Binary Meta Language) primitives: variable-size
|
||||
// integer coding, flat element scanning over a file descriptor, and element
|
||||
// serialization helpers. Sufficient to read and rewrite the metadata-side
|
||||
// elements of Matroska files (Tags, Attachments, SeekHead, Cues, Void); it
|
||||
// deliberately knows nothing about track/cluster payload contents.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
FOUNDATION_EXPORT NSErrorDomain const MP42MkvErrorDomain;
|
||||
|
||||
typedef NS_ERROR_ENUM(MP42MkvErrorDomain, MP42MkvError) {
|
||||
MP42MkvErrorParse = 1, // malformed / truncated EBML structure
|
||||
MP42MkvErrorUnsupported = 2, // layout we refuse to rewrite (multiple segments, stray unknown sizes…)
|
||||
MP42MkvErrorStaleFile = 3, // file changed on disk since it was opened
|
||||
MP42MkvErrorWriteFailed = 4,
|
||||
MP42MkvErrorCancelled = 5,
|
||||
};
|
||||
|
||||
// Pass as the `length` argument of -scanChildrenFrom:length: to scan to the
|
||||
// end of the file.
|
||||
FOUNDATION_EXPORT const uint64_t MP42EbmlScanToEnd;
|
||||
|
||||
// One EBML element header + extent found by a flat scan.
|
||||
@interface MP42EbmlElement : NSObject
|
||||
|
||||
@property (nonatomic) uint32_t identifier; // raw ID, marker bit included
|
||||
@property (nonatomic) uint64_t start; // absolute offset of the first ID byte
|
||||
@property (nonatomic) uint64_t headerSize; // ID bytes + size vint bytes
|
||||
@property (nonatomic) uint64_t dataSize; // decoded payload length
|
||||
@property (nonatomic) BOOL sizeIsUnknown; // unknown-size vint: payload runs to parent end
|
||||
|
||||
- (uint64_t)dataStart; // start + headerSize
|
||||
- (uint64_t)end; // only meaningful when !sizeIsUnknown
|
||||
|
||||
// Total extent (header + payload) of a known-size element.
|
||||
- (uint64_t)totalSize;
|
||||
|
||||
@end
|
||||
|
||||
@interface MP42EbmlScanner : NSObject
|
||||
|
||||
@property (nonatomic, readonly) uint64_t fileSize;
|
||||
|
||||
// Opens the file at URL for reading. The scanner owns the descriptor; call
|
||||
// -close when done (also called from dealloc).
|
||||
+ (nullable instancetype)scannerWithURL:(NSURL *)URL error:(NSError * _Nullable *)outError;
|
||||
- (void)close;
|
||||
|
||||
- (nullable NSData *)readAtOffset:(uint64_t)offset
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Flat scan of direct children covering [start, start+length) (or to EOF for
|
||||
// MP42EbmlScanToEnd). Elements are returned in file order; payloads are not
|
||||
// descended into. An element with an unknown-size vint consumes the rest of
|
||||
// the region and terminates the scan — callers must only tolerate that for
|
||||
// trailing elements (clusters in streamed files).
|
||||
//
|
||||
// Returns nil (and sets *outError) on malformed or truncated data. Runs of
|
||||
// 0x00 padding are treated as end-of-structure, not an error.
|
||||
- (nullable NSArray<MP42EbmlElement *> *)scanChildrenFrom:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
@end
|
||||
|
||||
//
|
||||
// EBML vint primitives and element builders (all class methods, no I/O).
|
||||
//
|
||||
@interface MP42Ebml : NSObject
|
||||
|
||||
+ (NSError *)errorWithCode:(MP42MkvError)code message:(NSString *)format, ... NS_FORMAT_FUNCTION(2, 3);
|
||||
|
||||
// Size vints: marker bit is stripped from the value. An all-ones value bits
|
||||
// pattern decodes as "unknown size".
|
||||
|
||||
// Returns the byte length of the size vint at buf (1...8), or 0 if the
|
||||
// leading byte is invalid or `available` is too small.
|
||||
+ (NSUInteger)sizeVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available;
|
||||
// Decodes a size vint of the given length. Sets *unknown for all-ones values.
|
||||
+ (uint64_t)sizeVintValueAt:(const uint8_t *)buf length:(NSUInteger)length unknown:(nullable BOOL *)unknown;
|
||||
// Canonical minimal width for encoding a size value.
|
||||
+ (NSUInteger)encodedLengthForSizeValue:(uint64_t)value;
|
||||
|
||||
// ID vints: the marker bit is part of the ID value.
|
||||
+ (NSUInteger)idVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available;
|
||||
+ (uint32_t)idValueAt:(const uint8_t *)buf length:(NSUInteger)length;
|
||||
|
||||
// Block-header track number: an "unmarked" vint whose marker bit only codes
|
||||
// the length. Returns the bytes consumed (0 when invalid/truncated) and the
|
||||
// decoded value in *outValue.
|
||||
+ (NSUInteger)blockTrackNumberAt:(const uint8_t *)buf available:(NSUInteger)available value:(nullable uint32_t *)outValue;
|
||||
|
||||
// Unsigned integer element payloads (SeekPosition, CueClusterPosition…).
|
||||
+ (uint64_t)unsignedIntValueAt:(const uint8_t *)buf length:(NSUInteger)length;
|
||||
|
||||
// Appends a size vint using the canonical minimal width.
|
||||
+ (void)appendSize:(uint64_t)value to:(NSMutableData *)data;
|
||||
// Appends a size vint at a fixed width (width must be >= canonical width).
|
||||
+ (void)appendSize:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data;
|
||||
// Appends an unknown-size vint of the given width (1...8).
|
||||
+ (void)appendUnknownSizeOfWidth:(NSUInteger)width to:(NSMutableData *)data;
|
||||
|
||||
+ (void)appendId:(uint32_t)identifier to:(NSMutableData *)data;
|
||||
+ (void)appendUnsignedInt:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data;
|
||||
|
||||
// Complete elements.
|
||||
+ (void)appendElement:(uint32_t)identifier payload:(nullable NSData *)payload to:(NSMutableData *)data;
|
||||
+ (void)appendStringElement:(uint32_t)identifier string:(NSString *)string to:(NSMutableData *)data;
|
||||
+ (void)appendVoidOfLength:(uint64_t)length to:(NSMutableData *)data;
|
||||
|
||||
// Flat scan of direct children inside an in-memory buffer, mirroring
|
||||
// -[MP42EbmlScanner scanChildrenFrom:length: semantics]. Returned elements
|
||||
// carry offsets relative to the buffer's own byte 0.
|
||||
+ (nullable NSArray<MP42EbmlElement *> *)scanBuffer:(NSData *)buffer
|
||||
from:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Where an element's payload ends within a region, tolerating the
|
||||
// truncated/unknown-size case: min(payload end or region end).
|
||||
+ (uint64_t)payloadEndForElement:(MP42EbmlElement *)element regionEnd:(uint64_t)regionEnd;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
//
|
||||
// MP42Ebml.m
|
||||
// MP42Foundation
|
||||
//
|
||||
|
||||
#import "MP42Ebml.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
|
||||
NSErrorDomain const MP42MkvErrorDomain = @"org.galad.MP42Foundation.Matroska";
|
||||
|
||||
const uint64_t MP42EbmlScanToEnd = UINT64_MAX;
|
||||
|
||||
@implementation MP42EbmlElement
|
||||
|
||||
- (uint64_t)dataStart
|
||||
{
|
||||
return self.start + self.headerSize;
|
||||
}
|
||||
|
||||
- (uint64_t)end
|
||||
{
|
||||
NSAssert(!self.sizeIsUnknown, @"unknown-size element has no end");
|
||||
return [self dataStart] + self.dataSize;
|
||||
}
|
||||
|
||||
- (uint64_t)totalSize
|
||||
{
|
||||
return self.headerSize + self.dataSize;
|
||||
}
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ 0x%x start=%llu hdr=%llu size=%@>",
|
||||
NSStringFromClass(self.class), self.identifier, self.start, self.headerSize,
|
||||
self.sizeIsUnknown ? @"UNKNOWN" : @(self.dataSize).stringValue];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42Ebml
|
||||
|
||||
+ (NSError *)errorWithCode:(MP42MkvError)code message:(NSString *)format, ...
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
|
||||
va_end(args);
|
||||
|
||||
return [NSError errorWithDomain:MP42MkvErrorDomain
|
||||
code:code
|
||||
userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
}
|
||||
|
||||
#pragma mark - vints
|
||||
|
||||
+ (NSUInteger)vintLengthAt:(const uint8_t *)buf available:(NSUInteger)available max:(NSUInteger)max
|
||||
{
|
||||
if (available == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t first = buf[0];
|
||||
for (NSUInteger len = 1; len <= max; len++) {
|
||||
if (first & (0x80 >> (len - 1))) {
|
||||
return len <= available ? len : 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
+ (NSUInteger)sizeVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available
|
||||
{
|
||||
return [self vintLengthAt:buf available:available max:8];
|
||||
}
|
||||
|
||||
+ (uint64_t)sizeVintValueAt:(const uint8_t *)buf length:(NSUInteger)length unknown:(BOOL *)unknown
|
||||
{
|
||||
uint64_t value = 0;
|
||||
for (NSUInteger i = 0; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
|
||||
// Strip the marker bit: it is the high bit of the leading byte, i.e.
|
||||
// (0x80 >> (length-1)) shifted up to the top of a `length`-byte value.
|
||||
value &= ~(((uint64_t)(0x80 >> (length - 1))) << (8 * (length - 1)));
|
||||
|
||||
if (unknown) {
|
||||
// All value bits set == "unknown size"
|
||||
*unknown = value == ((uint64_t)1 << (7 * length)) - 1;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
+ (NSUInteger)encodedLengthForSizeValue:(uint64_t)value
|
||||
{
|
||||
for (NSUInteger width = 1; width <= 8; width++) {
|
||||
// width w encodes values 0 ... 2^(7w)-2; all-ones means "unknown".
|
||||
if (7 * width < 64 && value < ((uint64_t)1 << (7 * width)) - 1) {
|
||||
return width;
|
||||
}
|
||||
}
|
||||
return 8;
|
||||
}
|
||||
|
||||
+ (NSUInteger)idVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available
|
||||
{
|
||||
return [self vintLengthAt:buf available:available max:4];
|
||||
}
|
||||
|
||||
+ (uint32_t)idValueAt:(const uint8_t *)buf length:(NSUInteger)length
|
||||
{
|
||||
uint32_t value = 0;
|
||||
for (NSUInteger i = 0; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
return value; // marker bit stays part of the ID
|
||||
}
|
||||
|
||||
+ (NSUInteger)blockTrackNumberAt:(const uint8_t *)buf available:(NSUInteger)available value:(uint32_t *)outValue
|
||||
{
|
||||
// Block headers open with an "unmarked" vint: same leading-zero length
|
||||
// coding as IDs/sizes, but the length-marker bit is NOT part of the
|
||||
// value (this is what MatroskaParser.c's readVLUInt decodes).
|
||||
NSUInteger length = [self vintLengthAt:buf available:available max:8];
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
uint32_t value = (uint32_t)(buf[0] & (0xFF >> length));
|
||||
for (NSUInteger i = 1; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
if (outValue) {
|
||||
*outValue = value;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
+ (uint64_t)unsignedIntValueAt:(const uint8_t *)buf length:(NSUInteger)length
|
||||
{
|
||||
uint64_t value = 0;
|
||||
// Per the spec, integers are at most 8 bytes; be tolerant of longer.
|
||||
NSUInteger start = length > 8 ? length - 8 : 0;
|
||||
for (NSUInteger i = start; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
#pragma mark - encoding
|
||||
|
||||
+ (void)appendSize:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
uint64_t encoded = value | ((uint64_t)1 << (7 * width));
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(encoded >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendSize:(uint64_t)value to:(NSMutableData *)data
|
||||
{
|
||||
[self appendSize:value width:[self encodedLengthForSizeValue:value] to:data];
|
||||
}
|
||||
|
||||
+ (void)appendUnknownSizeOfWidth:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
// Value bits all ones, marker set: 0xFF, 0x7FFF, 0x3FFFFF, …
|
||||
[self appendSize:((uint64_t)1 << (7 * width)) - 1 width:width to:data];
|
||||
}
|
||||
|
||||
+ (void)appendId:(uint32_t)identifier to:(NSMutableData *)data
|
||||
{
|
||||
NSUInteger width = 0;
|
||||
if (identifier >= 0x10000000u) {
|
||||
width = 4;
|
||||
} else if (identifier >= 0x200000u) {
|
||||
width = 3;
|
||||
} else if (identifier >= 0x4000u) {
|
||||
width = 2;
|
||||
} else if (identifier >= 0x80u) {
|
||||
width = 1;
|
||||
} else {
|
||||
NSCAssert(NO, @"invalid element identifier 0x%x", identifier);
|
||||
return;
|
||||
}
|
||||
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(identifier >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendUnsignedInt:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(value >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendElement:(uint32_t)identifier payload:(NSData *)payload to:(NSMutableData *)data
|
||||
{
|
||||
[self appendId:identifier to:data];
|
||||
[self appendSize:payload.length to:data];
|
||||
[data appendData:payload];
|
||||
}
|
||||
|
||||
+ (void)appendStringElement:(uint32_t)identifier string:(NSString *)string to:(NSMutableData *)data
|
||||
{
|
||||
[self appendElement:identifier payload:[string dataUsingEncoding:NSUTF8StringEncoding] to:data];
|
||||
}
|
||||
|
||||
+ (void)appendVoidOfLength:(uint64_t)length to:(NSMutableData *)data
|
||||
{
|
||||
NSCAssert(length >= 2, @"cannot build a Void element shorter than 2 bytes");
|
||||
if (length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
// total = 1 (ID) + width (size vint) + payload zeros
|
||||
for (NSUInteger width = 1; width <= 8; width++) {
|
||||
if (width > length - 1) {
|
||||
break;
|
||||
}
|
||||
uint64_t payload = length - 1 - width;
|
||||
if ([self encodedLengthForSizeValue:payload] <= width) {
|
||||
uint8_t voidId = 0xEC;
|
||||
[data appendBytes:&voidId length:1];
|
||||
[self appendSize:payload width:width to:data]; // non-minimal width allowed
|
||||
if (payload > 0) {
|
||||
NSMutableData *zeros = [NSMutableData dataWithLength:(NSUInteger)payload];
|
||||
[data appendData:zeros];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
NSCAssert(NO, @"no Void encoding fits %llu bytes", length);
|
||||
}
|
||||
|
||||
#pragma mark - buffer scanning
|
||||
|
||||
+ (NSArray<MP42EbmlElement *> *)scanBuffer:(NSData *)buffer
|
||||
from:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError **)outError
|
||||
{
|
||||
if (start > buffer.length) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse message:@"Buffer scan past end of data"];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
uint64_t end = (length == MP42EbmlScanToEnd) ? buffer.length : MIN(start + length, buffer.length);
|
||||
const uint8_t *bytes = buffer.bytes;
|
||||
|
||||
NSMutableArray<MP42EbmlElement *> *elements = [NSMutableArray array];
|
||||
uint64_t cursor = start;
|
||||
|
||||
while (cursor < end) {
|
||||
NSUInteger avail = (NSUInteger)MIN((uint64_t)12, end - cursor);
|
||||
|
||||
if (bytes[cursor] == 0x00) {
|
||||
break; // zero padding ends the structure
|
||||
}
|
||||
|
||||
NSUInteger idLen = [self idVintLengthAt:bytes + cursor available:avail];
|
||||
if (idLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element ID at offset %llu", cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUInteger sizeLen = [self sizeVintLengthAt:bytes + cursor + idLen available:avail - idLen];
|
||||
if (sizeLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element size at offset %llu", cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
BOOL unknown = NO;
|
||||
uint64_t dataSize = [self sizeVintValueAt:bytes + cursor + idLen length:sizeLen unknown:&unknown];
|
||||
|
||||
MP42EbmlElement *element = [[MP42EbmlElement alloc] init];
|
||||
element.identifier = [self idValueAt:bytes + cursor length:idLen];
|
||||
element.start = cursor;
|
||||
element.headerSize = idLen + sizeLen;
|
||||
|
||||
if (unknown) {
|
||||
element.sizeIsUnknown = YES;
|
||||
element.dataSize = end - element.dataStart;
|
||||
[elements addObject:element];
|
||||
break;
|
||||
}
|
||||
|
||||
if (element.dataStart + dataSize > end) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Element 0x%x at offset %llu extends past its parent",
|
||||
element.identifier, cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
element.dataSize = dataSize;
|
||||
[elements addObject:element];
|
||||
cursor = element.dataStart + dataSize;
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
+ (uint64_t)payloadEndForElement:(MP42EbmlElement *)element regionEnd:(uint64_t)regionEnd
|
||||
{
|
||||
uint64_t end = element.dataStart + element.dataSize;
|
||||
return MIN(end, regionEnd);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42EbmlScanner {
|
||||
NSURL *_URL;
|
||||
int _fd;
|
||||
uint64_t _fileSize;
|
||||
}
|
||||
|
||||
+ (instancetype)scannerWithURL:(NSURL *)URL error:(NSError **)outError
|
||||
{
|
||||
int fd = open(URL.fileSystemRepresentation, O_RDONLY);
|
||||
if (fd < 0) {
|
||||
if (outError) {
|
||||
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
|
||||
code:NSFileReadUnknownError
|
||||
userInfo:@{ NSLocalizedDescriptionKey:
|
||||
[NSString stringWithFormat:@"Cannot open %@ (%d)", URL.lastPathComponent, errno] }];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
off_t size = lseek(fd, 0, SEEK_END);
|
||||
if (size < 0) {
|
||||
close(fd);
|
||||
if (outError) {
|
||||
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
|
||||
code:NSFileReadUnknownError
|
||||
userInfo:@{ NSLocalizedDescriptionKey:
|
||||
[NSString stringWithFormat:@"Cannot determine size of %@ (%d)", URL.lastPathComponent, errno] }];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
MP42EbmlScanner *scanner = [[MP42EbmlScanner alloc] init];
|
||||
scanner->_URL = URL;
|
||||
scanner->_fd = fd;
|
||||
scanner->_fileSize = (uint64_t)size;
|
||||
return scanner;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self close];
|
||||
}
|
||||
|
||||
- (void)close
|
||||
{
|
||||
if (_fd >= 0) {
|
||||
close(_fd);
|
||||
_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
- (NSData *)readAtOffset:(uint64_t)offset length:(uint64_t)length error:(NSError **)outError
|
||||
{
|
||||
if (length == 0) {
|
||||
return [NSData data];
|
||||
}
|
||||
if (length > SIZE_MAX || offset + length > _fileSize) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Read past end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableData *data = [NSMutableData dataWithLength:(NSUInteger)length];
|
||||
uint8_t *bytes = data.mutableBytes;
|
||||
uint64_t done = 0;
|
||||
|
||||
while (done < length) {
|
||||
ssize_t n = pread(_fd, bytes + done, (size_t)(length - done), (off_t)(offset + done));
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorWriteFailed
|
||||
message:@"Read error in %@ (%d)", _URL.lastPathComponent, errno];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
if (n == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Unexpected end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
done += (uint64_t)n;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
- (NSArray<MP42EbmlElement *> *)scanChildrenFrom:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError **)outError
|
||||
{
|
||||
if (start > _fileSize) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Scan past end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
uint64_t end = (length == MP42EbmlScanToEnd) ? _fileSize : MIN(start + length, _fileSize);
|
||||
|
||||
NSMutableArray<MP42EbmlElement *> *elements = [NSMutableArray array];
|
||||
uint64_t cursor = start;
|
||||
|
||||
while (cursor < end) {
|
||||
uint8_t buf[12]; // up to 4 ID bytes + 8 size bytes
|
||||
NSUInteger avail = (NSUInteger)MIN((uint64_t)sizeof(buf), end - cursor);
|
||||
|
||||
ssize_t n = pread(_fd, buf, avail, (off_t)cursor);
|
||||
if (n <= 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (n <= 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Truncated EBML header at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
avail = (NSUInteger)n;
|
||||
|
||||
// Zero padding (some muxers pad allocations) ends the structure.
|
||||
if (buf[0] == 0x00) {
|
||||
break;
|
||||
}
|
||||
|
||||
NSUInteger idLen = [MP42Ebml idVintLengthAt:buf available:avail];
|
||||
if (idLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element ID at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUInteger sizeLen = [MP42Ebml sizeVintLengthAt:buf + idLen available:avail - idLen];
|
||||
if (sizeLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element size at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
BOOL unknown = NO;
|
||||
uint64_t dataSize = [MP42Ebml sizeVintValueAt:buf + idLen length:sizeLen unknown:&unknown];
|
||||
|
||||
MP42EbmlElement *element = [[MP42EbmlElement alloc] init];
|
||||
element.identifier = [MP42Ebml idValueAt:buf length:idLen];
|
||||
element.start = cursor;
|
||||
element.headerSize = idLen + sizeLen;
|
||||
|
||||
if (unknown) {
|
||||
// Unknown size runs to the end of the parent region and, in
|
||||
// practice, only ever occurs on the trailing element (streamed
|
||||
// clusters). It terminates the scan.
|
||||
element.sizeIsUnknown = YES;
|
||||
element.dataSize = end - element.dataStart;
|
||||
[elements addObject:element];
|
||||
break;
|
||||
}
|
||||
|
||||
if (element.dataStart + dataSize > end) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Element 0x%x at %llu in %@ extends past its parent",
|
||||
element.identifier, cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
element.dataSize = dataSize;
|
||||
[elements addObject:element];
|
||||
cursor = element.dataStart + dataSize;
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -200,6 +200,8 @@ typedef void (^MP42FileProgressHandler)(double progress);
|
||||
*/
|
||||
- (void)cancel;
|
||||
|
||||
@property (nonatomic, readwrite, nullable) NSUndoManager *undo;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+85
-52
@@ -95,7 +95,6 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) {
|
||||
|
||||
@end
|
||||
|
||||
MP42_OBJC_DIRECT_MEMBERS
|
||||
@implementation MP42File
|
||||
|
||||
@synthesize itracks = _tracks;
|
||||
@@ -451,73 +450,97 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
NSAssert(self.status != MP42StatusWriting, @"Unsupported operation: trying to add a track while the file is open for writing");
|
||||
NSAssert(![self.itracks containsObject:track], @"Unsupported operation: trying to add a track that is already present.");
|
||||
|
||||
track.sourceId = track.trackId;
|
||||
track.trackId = 0;
|
||||
track.muxed = NO;
|
||||
track.edited = YES;
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
track.sourceId = track.trackId;
|
||||
track.trackId = 0;
|
||||
track.muxed = NO;
|
||||
track.edited = YES;
|
||||
|
||||
track.language = track.language;
|
||||
track.name = track.name;
|
||||
if ([track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
for (id previousTrack in self.itracks)
|
||||
if ([previousTrack isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
[self.itracks removeObject:previousTrack];
|
||||
break;
|
||||
track.language = track.language;
|
||||
track.name = track.name;
|
||||
if ([track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
for (id previousTrack in self.itracks)
|
||||
if ([previousTrack isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
[self.itracks removeObject:previousTrack];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (trackNeedConversion(track.format) && ![track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
NSAssert(track.conversionSettings, @"Missing conversion settings");
|
||||
}
|
||||
|
||||
if ([track isMemberOfClass:[MP42AudioTrack class]]) {
|
||||
MP42AudioTrack *audioTrack = (MP42AudioTrack *)track;
|
||||
MP42Track *fallbackTrack = audioTrack.fallbackTrack;
|
||||
if (fallbackTrack && ![self.itracks containsObject:fallbackTrack]) {
|
||||
audioTrack.fallbackTrack = nil;
|
||||
}
|
||||
}
|
||||
|
||||
if ([track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
track.duration = self.duration;
|
||||
}
|
||||
}
|
||||
|
||||
if (trackNeedConversion(track.format) && ![track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
NSAssert(track.conversionSettings, @"Missing conversion settings");
|
||||
}
|
||||
|
||||
if (track.importer && track.URL) {
|
||||
if (self.importers[track.URL.path]) {
|
||||
track.importer = self.importers[track.URL.path];
|
||||
} else {
|
||||
self.importers[track.URL.path] = track.importer;
|
||||
}
|
||||
}
|
||||
|
||||
if ([track isMemberOfClass:[MP42AudioTrack class]]) {
|
||||
MP42AudioTrack *audioTrack = (MP42AudioTrack *)track;
|
||||
MP42Track *fallbackTrack = audioTrack.fallbackTrack;
|
||||
if (fallbackTrack && ![self.itracks containsObject:fallbackTrack]) {
|
||||
audioTrack.fallbackTrack = nil;
|
||||
}
|
||||
}
|
||||
|
||||
if ([track isMemberOfClass:[MP42ChapterTrack class]]) {
|
||||
track.duration = self.duration;
|
||||
}
|
||||
track.undo = self.undo;
|
||||
|
||||
[[self.undo prepareWithInvocationTarget:self] removeTracks:@[track]];
|
||||
[self.itracks addObject:track];
|
||||
}
|
||||
|
||||
- (void)addToBeDeleted:(MP42Track *)track
|
||||
{
|
||||
[[self.undo prepareWithInvocationTarget:self] removeFromToBeDeleted:track];
|
||||
[_tracksToBeDeleted addObject:track];
|
||||
}
|
||||
|
||||
- (void)removeFromToBeDeleted:(MP42Track *)track
|
||||
{
|
||||
[[self.undo prepareWithInvocationTarget:self] addToBeDeleted:track];
|
||||
[_tracksToBeDeleted removeObject:track];
|
||||
}
|
||||
|
||||
- (void)removeTracks:(NSArray<MP42Track *> *)tracks {
|
||||
NSAssert(self.status != MP42StatusWriting, @"Unsupported operation: trying to remove a track while the file is open for writing");
|
||||
|
||||
for (MP42Track *track in tracks) {
|
||||
// track is muxed, it needs to be removed from the file
|
||||
if (track.muxed)
|
||||
[_tracksToBeDeleted addObject:track];
|
||||
|
||||
// Remove the reference
|
||||
for (MP42Track *ref in self.itracks) {
|
||||
if ([ref isMemberOfClass:[MP42AudioTrack class]]) {
|
||||
MP42AudioTrack *a = (MP42AudioTrack *)ref;
|
||||
if (a.fallbackTrack == track)
|
||||
a.fallbackTrack = nil;
|
||||
if (a.followsTrack == track)
|
||||
a.followsTrack = nil;
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
for (MP42Track *track in tracks) {
|
||||
// track is muxed, it needs to be removed from the file
|
||||
if (track.muxed) {
|
||||
[self addToBeDeleted:track];
|
||||
}
|
||||
if ([ref isMemberOfClass:[MP42SubtitleTrack class]]) {
|
||||
MP42SubtitleTrack *a = (MP42SubtitleTrack *)ref;
|
||||
if (a.forcedTrack == track)
|
||||
a.forcedTrack = nil;
|
||||
|
||||
// Remove the reference
|
||||
for (MP42Track *ref in self.itracks) {
|
||||
if ([ref isMemberOfClass:[MP42AudioTrack class]]) {
|
||||
MP42AudioTrack *a = (MP42AudioTrack *)ref;
|
||||
if (a.fallbackTrack == track)
|
||||
a.fallbackTrack = nil;
|
||||
if (a.followsTrack == track)
|
||||
a.followsTrack = nil;
|
||||
}
|
||||
if ([ref isMemberOfClass:[MP42SubtitleTrack class]]) {
|
||||
MP42SubtitleTrack *a = (MP42SubtitleTrack *)ref;
|
||||
if (a.forcedTrack == track)
|
||||
a.forcedTrack = nil;
|
||||
}
|
||||
}
|
||||
|
||||
if (track.importer && track.URL) {
|
||||
if (self.importers[track.URL.path]) {
|
||||
track.importer = self.importers[track.URL.path];
|
||||
} else {
|
||||
self.importers[track.URL.path] = track.importer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (MP42Track *track in tracks) {
|
||||
[(MP42File *)[self.undo prepareWithInvocationTarget:self] addTrack:track];
|
||||
}
|
||||
|
||||
[self.itracks removeObjectsInArray:tracks];
|
||||
}
|
||||
|
||||
@@ -1409,4 +1432,14 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
[self.URL stopAccessingSecurityScopedResource];
|
||||
}
|
||||
|
||||
- (void)setUndo:(NSUndoManager *)undo {
|
||||
_undo = undo;
|
||||
|
||||
self.metadata.undo = undo;
|
||||
|
||||
for (MP42Track *track in self.tracks) {
|
||||
track.undo = undo;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -25,11 +25,22 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
+ (NSArray<NSString *> *)supportedFileFormats;
|
||||
+ (BOOL)canInitWithFileType:(NSString *)fileType;
|
||||
|
||||
// YES for the extensions handled by the Matroska importer (mkv, mka, mks);
|
||||
// used by callers that want to open such files in tags-only mode instead of
|
||||
// converting them.
|
||||
+ (BOOL)isMatroskaFileType:(NSString *)fileType;
|
||||
|
||||
+ (NSArray<UTType *> *)supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
+ (BOOL)canInitWithContentType:(UTType *)contentType API_AVAILABLE(macos(11.0));
|
||||
|
||||
- (nullable instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)error;
|
||||
|
||||
// tagsOnly is YES when the caller opens a Matroska file to edit it in place
|
||||
// (tags-only mode): the importer then mirrors the file's own track flags
|
||||
// (TrackFlagEnabled) instead of Subler's MP4-oriented "first track of each
|
||||
// type enabled" conversion heuristic. Non-Matroska importers ignore it.
|
||||
- (nullable instancetype)initWithURL:(NSURL *)fileURL tagsOnly:(BOOL)tagsOnly error:(NSError * __autoreleasing *)error;
|
||||
|
||||
@property (nonatomic, readonly) NSURL *fileURL;
|
||||
@property (nonatomic, readonly) MP42Metadata *metadata;
|
||||
@property (nonatomic, readonly) NSArray<MP42Track *> *tracks;
|
||||
|
||||
+20
-1
@@ -98,6 +98,11 @@ static NSArray<UTType *> *_supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
return [[self supportedFileFormats] containsObject:fileType.lowercaseString];
|
||||
}
|
||||
|
||||
+ (BOOL)isMatroskaFileType:(NSString *)fileType
|
||||
{
|
||||
return [[MP42MkvImporter supportedFileFormats] containsObject:fileType.lowercaseString];
|
||||
}
|
||||
|
||||
+ (NSArray<UTType *> *)supportedContentTypes
|
||||
{
|
||||
return _supportedContentTypes;
|
||||
@@ -116,13 +121,27 @@ static NSArray<UTType *> *_supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
return [self initWithURL:fileURL tagsOnly:NO error:error];
|
||||
}
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL tagsOnly:(BOOL)tagsOnly error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
// Called on MP42FileImporter itself (the factory path, e.g. from the app):
|
||||
// pick and allocate the subclass for the extension. Called on a subclass
|
||||
// instance that ignores tagsOnly (it inherits this method), forward to
|
||||
// its real designated initializer instead — MP42MkvImporter overrides this
|
||||
// method outright, so it never lands here.
|
||||
if (![self isMemberOfClass:[MP42FileImporter class]]) {
|
||||
return [self initWithURL:fileURL error:error];
|
||||
}
|
||||
|
||||
self = nil;
|
||||
|
||||
// Initialize the right file importer subclass
|
||||
for (Class c in _fileImporters) {
|
||||
if ([c canInitWithFileType:fileURL.pathExtension]) {
|
||||
|
||||
self = [[c alloc] initWithURL:fileURL error:error];
|
||||
self = [[c alloc] initWithURL:fileURL tagsOnly:tagsOnly error:error];
|
||||
if (self) {
|
||||
for (MP42Track *track in _tracksArray) {
|
||||
track.importer = self;
|
||||
|
||||
@@ -32,4 +32,9 @@
|
||||
#import <MP42Foundation/MP42RelatedItem.h>
|
||||
#import <MP42Foundation/MP42SecurityAccessToken.h>
|
||||
|
||||
#import <MP42Foundation/MP42Ebml.h>
|
||||
#import <MP42Foundation/MP42MatroskaTagMapping.h>
|
||||
#import <MP42Foundation/MP42MkvRemuxer.h>
|
||||
#import <MP42Foundation/MP42MkvTagWriter.h>
|
||||
|
||||
#endif /* MP42Foundation_h */
|
||||
@@ -0,0 +1,169 @@
|
||||
//
|
||||
// MP42MatroskaTagMapping.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Shared Matroska element identifiers and SimpleTag <-> MP42 metadata key
|
||||
// mapping, used by both the importer (read path) and the tag writer (write
|
||||
// path) so the two cannot drift apart.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// EBML / Matroska element identifiers.
|
||||
//
|
||||
// These are NOT the values printed on the older matroska.org documentation
|
||||
// pages, which are wrong for several elements (Tag, Targets, TargetTypeValue,
|
||||
// Attachments among them). The values below were verified empirically by
|
||||
// hex-dumping files written by ffmpeg and mkvtoolnix v104, and cross-checked
|
||||
// against the constants the bundled MatroskaParser.c demuxer parses with.
|
||||
// Treat MatroskaParser.c as the authority if you ever need to re-verify.
|
||||
enum {
|
||||
MP42MkvElementEBMLHeader = 0x1A45DFA3,
|
||||
MP42MkvElementSegment = 0x18538067,
|
||||
MP42MkvElementVoid = 0xEC,
|
||||
|
||||
MP42MkvElementSeekHead = 0x114D9B74,
|
||||
MP42MkvElementSeek = 0x4DBB,
|
||||
MP42MkvElementSeekID = 0x53AB,
|
||||
MP42MkvElementSeekPosition = 0x53AC,
|
||||
|
||||
MP42MkvElementSegmentInfo = 0x1549A966,
|
||||
MP42MkvElementTracks = 0x1654AE6B,
|
||||
MP42MkvElementTrackEntry = 0xAE,
|
||||
MP42MkvElementTrackNumber = 0xD7, // unsigned integer, referenced by block headers
|
||||
MP42MkvElementTrackUID = 0x73C5, // unsigned integer, tags/chapters/cue refs
|
||||
MP42MkvElementTrackName = 0x536E, // UTF-8 string
|
||||
// The Matroska element ids are a known trap: the practical ids (used by
|
||||
// libebml/mkvtoolnix and ffmpeg, and what every reader expects) are
|
||||
// 0x22B59C for the ISO-639-2/B language and 0x22B59D for the BCP-47
|
||||
// LanguageIETF. The EBML spec's later-introduced 0x447A carries the same
|
||||
// ISO value; it is accepted on read but never written. (Modern mkvtoolnix
|
||||
// files may contain ONLY the IETF element — mkvmerge derives the ISO code
|
||||
// from it — so the ISO element can be absent.)
|
||||
MP42MkvElementTrackLanguage = 0x22B59C, // ISO-639-2/B, 3 ASCII chars
|
||||
MP42MkvElementTrackLanguageSpec = 0x447A, // newer spec id, same ISO value
|
||||
MP42MkvElementTrackLanguageIETF = 0x22B59D, // BCP-47 string, e.g. "en-US"
|
||||
MP42MkvElementTrackFlagEnabled = 0xB9, // unsigned integer, default 1
|
||||
MP42MkvElementTrackFlagForced = 0x55AA, // unsigned integer, default 0
|
||||
MP42MkvElementTrackType = 0x83, // unsigned integer: 1 video, 2 audio, 17 subtitle
|
||||
MP42MkvElementFlagLacing = 0x9C, // unsigned integer, default 1 (mkvmerge writes 0 for subtitles)
|
||||
MP42MkvElementCodecID = 0x86, // ASCII string, e.g. "S_TEXT/UTF8"
|
||||
MP42MkvElementChapters = 0x1043A770,
|
||||
MP42MkvElementCluster = 0x1F43B675,
|
||||
MP42MkvElementClusterTimeCode = 0xE7, // unsigned integer, cluster child
|
||||
MP42MkvElementSimpleBlock = 0xA3, // cluster child; payload starts with the track-number vint
|
||||
MP42MkvElementBlockGroup = 0xA0, // cluster child; the track comes from its Block child
|
||||
MP42MkvElementBlock = 0xA1, // BlockGroup child (inside SimpleBlock it is 0xA3)
|
||||
MP42MkvElementBlockDuration = 0x9B, // unsigned integer, BlockGroup child: display duration
|
||||
// in TrackTimecodeScale units (default scale = 1 ms)
|
||||
|
||||
// Info children the remuxer recomputes; both are in TimecodeScale units
|
||||
// (Duration is the only EBML *float* the remuxer touches — 8-byte double).
|
||||
MP42MkvElementTimecodeScale = 0x2AD7B2, // unsigned integer, default 1000000 (1 ms in ns)
|
||||
MP42MkvElementDuration = 0x4489, // float, TimecodeScale units
|
||||
|
||||
// Chapters children (MP42MkvElementChapters). DisplayUnitID (0x76) is
|
||||
// omitted on write; ChapterLanguage (0x437C) is written from the chapter
|
||||
// track's language, omitted when it is nil or ISO "eng" (the spec default).
|
||||
MP42MkvElementEditionEntry = 0x45B9,
|
||||
MP42MkvElementEditionUID = 0x45BC, // unsigned integer, mandatory (1 edition 1 UID)
|
||||
MP42MkvElementChapterUID = 0x73C4, // unsigned integer, mandatory — ffmpeg
|
||||
// silently skips atoms without it
|
||||
// ChapterAtom is 0xB6, NOT 0xB0 — 0xB0 is PixelWidth (TrackEntry scope;
|
||||
// hex-dumping mkvmerge-written Chapters confirms 0xB6, and the vendored
|
||||
// MatroskaParser.c has always parsed 0xB6 here).
|
||||
MP42MkvElementChapterAtom = 0xB6,
|
||||
// Chapter timecodes are absolute NANOSECONDS — unlike almost every
|
||||
// other Matroska time, they do NOT follow TimecodeScale (libmatroska
|
||||
// and ffmpeg both write/read them as ns; confirmed against a
|
||||
// mkvmerge-written file).
|
||||
MP42MkvElementChapterTimeStart = 0x91, // unsigned integer, ns
|
||||
MP42MkvElementChapterTimeEnd = 0x92, // unsigned integer, ns; omit when unknown
|
||||
MP42MkvElementChapterDisplay = 0x80,
|
||||
MP42MkvElementChapterString = 0x85, // UTF-8 string
|
||||
MP42MkvElementChapterLanguage = 0x437C, // ISO-639-2/B, default "eng"
|
||||
|
||||
MP42MkvElementAttachments = 0x1941A469,
|
||||
MP42MkvElementAttachedFile = 0x61A7,
|
||||
MP42MkvElementFileDescription = 0x467E,
|
||||
MP42MkvElementFileName = 0x466E,
|
||||
MP42MkvElementFileMimeType = 0x4660,
|
||||
MP42MkvElementFileData = 0x465C,
|
||||
MP42MkvElementFileUID = 0x46AE,
|
||||
MP42MkvElementImageType = 0x3E5B,
|
||||
|
||||
MP42MkvElementCues = 0x1C53BB6B,
|
||||
MP42MkvElementCuePoint = 0xBB,
|
||||
MP42MkvElementCueTime = 0xB3,
|
||||
MP42MkvElementCueTrackPositions = 0xB7,
|
||||
MP42MkvElementCueTrack = 0xF7,
|
||||
MP42MkvElementCueClusterPosition = 0xB1,
|
||||
MP42MkvElementCueRelativePosition= 0xB0,
|
||||
|
||||
// Tagging elements (MatroskaTag spec). Note Tag and Targets are easy to
|
||||
// get wrong: Tag is 0x7373 and Targets is 0x63C0.
|
||||
MP42MkvElementTags = 0x1254C367,
|
||||
MP42MkvElementTag = 0x7373,
|
||||
MP42MkvElementTargets = 0x63C0,
|
||||
MP42MkvElementTargetTypeValue = 0x68CA, // unsigned integer
|
||||
MP42MkvElementTargetType = 0x63CA, // UTF-8 string, e.g. "MOVIE"
|
||||
MP42MkvElementTagTrackUID = 0x63C5,
|
||||
MP42MkvElementTagChapterUID = 0x63C4,
|
||||
MP42MkvElementTagAttachmentUID = 0x63C6,
|
||||
MP42MkvElementTagEditionUID = 0x63C9,
|
||||
MP42MkvElementSimpleTag = 0x67C8,
|
||||
MP42MkvElementTagName = 0x45A3,
|
||||
MP42MkvElementTagLanguage = 0x447A, // ISO-639-2/B, 3 ASCII chars
|
||||
MP42MkvElementTagLanguageIETF = 0x447B, // BCP-47, written by recent mkvtoolnix
|
||||
MP42MkvElementTagDefault = 0x4484, // unsigned integer, default 1
|
||||
MP42MkvElementTagString = 0x4487,
|
||||
MP42MkvElementTagBinary = 0x4485,
|
||||
};
|
||||
|
||||
// TargetTypeValue levels. MP42MkvTargetGlobal (0) is a synthetic level for
|
||||
// tag groups without a Targets element; the importer treats them like the
|
||||
// default (movie/album) group.
|
||||
enum {
|
||||
MP42MkvTargetGlobal = 0,
|
||||
MP42MkvTargetShot = 10,
|
||||
MP42MkvTargetScene = 20,
|
||||
MP42MkvTargetChapter = 30,
|
||||
MP42MkvTargetPart = 40,
|
||||
MP42MkvTargetMovie = 50, // also EPISODE / ALBUM
|
||||
MP42MkvTargetSeason = 60,
|
||||
MP42MkvTargetCollection = 70,
|
||||
};
|
||||
|
||||
// Read direction: SimpleTag name -> MP42 metadata key, for a target level.
|
||||
// Levels other than collection/season (including global and part) use the
|
||||
// default map, matching the importer's historical behavior.
|
||||
NSDictionary<NSString *, NSString *> *MP42MkvSimpleTagMapForTargetLevel(NSInteger level);
|
||||
|
||||
// Whether the importer models tag groups at this level at all. Groups at
|
||||
// chapter/scene/shot levels are skipped by the importer and must be carried
|
||||
// through untouched by the writer.
|
||||
BOOL MP42MkvTargetLevelIsModeled(NSInteger level);
|
||||
|
||||
// A canonical (ordered) write pair: one MP42 metadata key and the SimpleTag
|
||||
// name it is serialized as at a given level. The writer iterates these in
|
||||
// order so output is stable across saves.
|
||||
@interface MP42MkvTagPair : NSObject
|
||||
@property (nonatomic, readonly) NSString *simpleTagName;
|
||||
@property (nonatomic, readonly) NSString *metadataKey;
|
||||
- (instancetype)initWithSimpleTagName:(NSString *)name metadataKey:(NSString *)key;
|
||||
@end
|
||||
|
||||
// Write direction: ordered pairs for a target level. Derived from the read
|
||||
// map so both directions always agree.
|
||||
NSArray<MP42MkvTagPair *> *MP42MkvWritePairsForTargetLevel(NSInteger level);
|
||||
|
||||
// Whether MP42MkvTagWriter can save an MP42 metadata key to a Matroska file:
|
||||
// either it has a SimpleTag name at some modeled target level, or it is
|
||||
// regenerated (TrackNumber -> PART_NUMBER/TOTAL_PARTS), or it is stored as a
|
||||
// cover attachment (CoverArt). Keys answering NO here are silently dropped on
|
||||
// save — the UI uses this to flag such fields to the user.
|
||||
BOOL MP42MkvMetadataKeyIsPersisted(NSString *metadataKey);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,238 @@
|
||||
//
|
||||
// MP42MatroskaTagMapping.m
|
||||
// MP42Foundation
|
||||
//
|
||||
|
||||
#import "MP42MatroskaTagMapping.h"
|
||||
|
||||
#import "MP42MetadataFormat.h"
|
||||
|
||||
@implementation MP42MkvTagPair
|
||||
|
||||
- (instancetype)initWithSimpleTagName:(NSString *)name metadataKey:(NSString *)key
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_simpleTagName = [name copy];
|
||||
_metadataKey = [key copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
//
|
||||
// Read maps. These were previously inline in MP42MkvImporter's
|
||||
// readMatroskaMetadata; they live here now because the tag writer serializes
|
||||
// its inverse and any drift between the two directions silently drops tags.
|
||||
//
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvDefaultMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"TITLE": MP42MetadataKeyName,
|
||||
@"SUBTITLE": MP42MetadataKeyTrackSubTitle,
|
||||
@"ALBUM": MP42MetadataKeyAlbum,
|
||||
@"ARTIST": MP42MetadataKeyArtist,
|
||||
|
||||
@"COMMENT": MP42MetadataKeyUserComment,
|
||||
@"GENRE": MP42MetadataKeyUserGenre,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
|
||||
@"BPM": MP42MetadataKeyBeatsPerMin,
|
||||
|
||||
@"KEYWORDS": MP42MetadataKeyKeywords,
|
||||
@"THANKS_TO": MP42MetadataKeyThanks,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
|
||||
@"DESCRIPTION": MP42MetadataKeyDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeyLongDescription,
|
||||
|
||||
@"DIRECTOR_OF_PHOTOGRAPHY": MP42MetadataKeyArtDirector,
|
||||
@"COMPOSER": MP42MetadataKeyComposer,
|
||||
@"ARRANGER": MP42MetadataKeyArranger,
|
||||
@"WRITTEN_BY": MP42MetadataKeyAuthor,
|
||||
@"LYRICS": MP42MetadataKeyLyrics,
|
||||
@"CONDUCTOR": MP42MetadataKeyConductor,
|
||||
@"PUBLISHER": MP42MetadataKeyPublisher,
|
||||
@"SOUND_ENGINEER": MP42MetadataKeySoundEngineer,
|
||||
@"LEAD_PERFORMER": MP42MetadataKeySoloist,
|
||||
|
||||
@"PRODUCTION_STUDIO": MP42MetadataKeyStudio,
|
||||
@"DIRECTOR": MP42MetadataKeyDirector,
|
||||
@"PRODUCER": MP42MetadataKeyProducer,
|
||||
@"EXECUTIVE_PRODUCER": MP42MetadataKeyExecProducer,
|
||||
@"SCREENPLAY_BY": MP42MetadataKeyScreenwriters,
|
||||
@"CAST": MP42MetadataKeyCast,
|
||||
|
||||
// Movie-tab fields with no Matroska-spec equivalent; these names
|
||||
// follow the community style (uppercase words, no separators) and
|
||||
// exist mainly so values survive a Subler save/reopen round-trip.
|
||||
@"RATING": MP42MetadataKeyRating, // parental advisory string
|
||||
@"CONTENTRATING": MP42MetadataKeyContentRating, // numeric rating code
|
||||
@"MEDIAKIND": MP42MetadataKeyMediaKind,
|
||||
@"HD": MP42MetadataKeyHDVideo,
|
||||
|
||||
@"NETWORK": MP42MetadataKeyTVNetwork,
|
||||
@"EPISODEID": MP42MetadataKeyTVEpisodeID,
|
||||
|
||||
@"ENCODER": MP42MetadataKeyEncodingTool,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvCollectionMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"TITLE": MP42MetadataKeyTVShow,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvSeasonMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"PART_NUMBER": MP42MetadataKeyTVSeason,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSString *> *MP42MkvSimpleTagMapForTargetLevel(NSInteger level)
|
||||
{
|
||||
switch (level) {
|
||||
case MP42MkvTargetCollection: return MP42MkvCollectionMap();
|
||||
case MP42MkvTargetSeason: return MP42MkvSeasonMap();
|
||||
default: return MP42MkvDefaultMap();
|
||||
}
|
||||
}
|
||||
|
||||
BOOL MP42MkvTargetLevelIsModeled(NSInteger level)
|
||||
{
|
||||
// Chapter/scene/shot level tags are skipped by the importer and must be
|
||||
// preserved verbatim by the writer. Everything else (global, part, movie,
|
||||
// season, collection) feeds the metadata model.
|
||||
return level != MP42MkvTargetChapter &&
|
||||
level != MP42MkvTargetScene &&
|
||||
level != MP42MkvTargetShot;
|
||||
}
|
||||
|
||||
// Canonical SimpleTag name order per level, used to give the writer stable
|
||||
// output. Every name must exist in the read map for its level; names added
|
||||
// to a read map without being listed here are appended automatically (in
|
||||
// unspecified order) rather than silently dropped.
|
||||
static NSArray<NSString *> *MP42MkvWriteNameOrder(NSInteger level)
|
||||
{
|
||||
switch (level) {
|
||||
case MP42MkvTargetCollection:
|
||||
return @[ @"TITLE", @"SYNOPSIS", @"COPYRIGHT" ];
|
||||
case MP42MkvTargetSeason:
|
||||
return @[ @"PART_NUMBER", @"SYNOPSIS", @"DATE_RELEASED" ];
|
||||
default:
|
||||
return @[ @"TITLE", @"ALBUM", @"ARTIST", @"PART_NUMBER", @"TOTAL_PARTS",
|
||||
@"DATE_RELEASED", @"GENRE", @"DESCRIPTION", @"SYNOPSIS",
|
||||
@"COMMENT", @"COPYRIGHT", @"PRODUCTION_STUDIO",
|
||||
@"DIRECTOR", @"PRODUCER", @"EXECUTIVE_PRODUCER",
|
||||
@"SCREENPLAY_BY", @"WRITTEN_BY", @"COMPOSER", @"ARRANGER",
|
||||
@"LYRICS", @"CONDUCTOR", @"PUBLISHER", @"SOUND_ENGINEER",
|
||||
@"LEAD_PERFORMER", @"DIRECTOR_OF_PHOTOGRAPHY", @"CAST",
|
||||
@"RATING", @"CONTENTRATING", @"MEDIAKIND", @"HD",
|
||||
@"NETWORK", @"EPISODEID",
|
||||
@"KEYWORDS", @"THANKS_TO", @"BPM", @"ENCODER", @"SUBTITLE" ];
|
||||
}
|
||||
}
|
||||
|
||||
// All metadata keys MP42MkvTagWriter can round-trip, cached for the UI's
|
||||
// "can this field be saved?" hints. Kept here (next to the maps it derives
|
||||
// from) so the UI can never drift from what the writer actually writes.
|
||||
static NSSet<NSString *> *MP42MkvPersistedMetadataKeys(void)
|
||||
{
|
||||
static NSSet<NSString *> *keys;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSMutableSet<NSString *> *mutableKeys = [NSMutableSet setWithObjects:
|
||||
// Regenerated as PART_NUMBER / TOTAL_PARTS
|
||||
MP42MetadataKeyTrackNumber,
|
||||
// Fallback source for movie-level PART_NUMBER
|
||||
// when TrackNumber carries no index
|
||||
MP42MetadataKeyTVEpisodeNumber,
|
||||
// Regenerated as season-level PART_NUMBER
|
||||
// (also a season-map pair key, listed for clarity)
|
||||
MP42MetadataKeyTVSeason,
|
||||
// Stored as an AttachedFile, not a SimpleTag
|
||||
MP42MetadataKeyCoverArt,
|
||||
nil];
|
||||
for (NSNumber *level in @[ @(MP42MkvTargetMovie), @(MP42MkvTargetSeason), @(MP42MkvTargetCollection) ]) {
|
||||
for (MP42MkvTagPair *pair in MP42MkvWritePairsForTargetLevel(level.integerValue)) {
|
||||
[mutableKeys addObject:pair.metadataKey];
|
||||
}
|
||||
}
|
||||
keys = [mutableKeys copy];
|
||||
});
|
||||
return keys;
|
||||
}
|
||||
|
||||
BOOL MP42MkvMetadataKeyIsPersisted(NSString *metadataKey)
|
||||
{
|
||||
return metadataKey.length > 0 && [MP42MkvPersistedMetadataKeys() containsObject:metadataKey];
|
||||
}
|
||||
|
||||
NSArray<MP42MkvTagPair *> *MP42MkvWritePairsForTargetLevel(NSInteger level)
|
||||
{
|
||||
static NSMutableDictionary<NSNumber *, NSArray<MP42MkvTagPair *> *> *cache;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
cache = [NSMutableDictionary dictionary];
|
||||
});
|
||||
|
||||
NSNumber *levelKey = @(level);
|
||||
@synchronized (cache) {
|
||||
NSArray<MP42MkvTagPair *> *pairs = cache[levelKey];
|
||||
if (pairs) {
|
||||
return pairs;
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSString *> *readMap = MP42MkvSimpleTagMapForTargetLevel(level);
|
||||
NSMutableArray<MP42MkvTagPair *> *result = [NSMutableArray array];
|
||||
NSMutableSet<NSString *> *usedKeys = [NSMutableSet set];
|
||||
|
||||
for (NSString *name in MP42MkvWriteNameOrder(level)) {
|
||||
NSString *key = readMap[name];
|
||||
if (key && ![usedKeys containsObject:key]) {
|
||||
[usedKeys addObject:key];
|
||||
[result addObject:[[MP42MkvTagPair alloc] initWithSimpleTagName:name metadataKey:key]];
|
||||
}
|
||||
}
|
||||
|
||||
// Names present in the read map but missing from the order list still
|
||||
// need to be written; append them so both directions stay in sync.
|
||||
for (NSString *name in readMap) {
|
||||
NSString *key = readMap[name];
|
||||
if (![usedKeys containsObject:key]) {
|
||||
[usedKeys addObject:key];
|
||||
[result addObject:[[MP42MkvTagPair alloc] initWithSimpleTagName:name metadataKey:key]];
|
||||
}
|
||||
}
|
||||
|
||||
pairs = [result copy];
|
||||
cache[levelKey] = pairs;
|
||||
return pairs;
|
||||
}
|
||||
}
|
||||
@@ -91,12 +91,15 @@ enum : MP42VideoCodecType
|
||||
kMP42VideoCodecType_VP9 = 'vp09',
|
||||
kMP42VideoCodecType_AV1 = 'av01',
|
||||
|
||||
kMP42VideoCodecType_AppleProRes4444XQ = 'ap4x',
|
||||
kMP42VideoCodecType_AppleProRes4444 = 'ap4h',
|
||||
kMP42VideoCodecType_AppleProRes422HQ = 'apch',
|
||||
kMP42VideoCodecType_AppleProRes422 = 'apcn',
|
||||
kMP42VideoCodecType_AppleProRes422LT = 'apcs',
|
||||
kMP42VideoCodecType_AppleProRes422Proxy = 'apco',
|
||||
|
||||
kMP42VideoCodecType_AppleProResRAW = 'aprn',
|
||||
kMP42VideoCodecType_AppleProResRAWHQ = 'aprh',
|
||||
|
||||
kMP42VideoCodecType_DVCNTSC = 'dvc ',
|
||||
kMP42VideoCodecType_DVCPAL = 'dvcp',
|
||||
|
||||
@@ -190,6 +190,10 @@ NSString *localizedVideoDisplayName(FourCharCode mediaSubtype)
|
||||
result = NSLocalizedString(@"AV1", nil);
|
||||
break;
|
||||
|
||||
case kMP42VideoCodecType_AppleProRes4444XQ:
|
||||
result = NSLocalizedString(@"ProRes 4444 XQ", nil);
|
||||
break;
|
||||
|
||||
case kMP42VideoCodecType_AppleProRes4444:
|
||||
result = NSLocalizedString(@"ProRes 4444", nil);
|
||||
break;
|
||||
@@ -213,6 +217,11 @@ NSString *localizedVideoDisplayName(FourCharCode mediaSubtype)
|
||||
case kMP42VideoCodecType_AppleProResRAW:
|
||||
result = NSLocalizedString(@"ProRes RAW", nil);
|
||||
break;
|
||||
|
||||
case kMP42VideoCodecType_AppleProResRAWHQ:
|
||||
result = NSLocalizedString(@"ProRes RAW HQ", nil);
|
||||
break;
|
||||
|
||||
case kMP42VideoCodecType_DVCNTSC:
|
||||
result = NSLocalizedString(@"DV NTSC", nil);
|
||||
break;
|
||||
|
||||
@@ -71,6 +71,8 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
*/
|
||||
- (void)mergeMetadata:(MP42Metadata *)metadata overwrite:(BOOL)overwrite;
|
||||
|
||||
@property (nonatomic, readwrite, nullable) NSUndoManager *undo;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+37
-11
@@ -65,6 +65,24 @@
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setEdited:(BOOL)edited
|
||||
{
|
||||
if (_edited != edited) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setEdited:_edited];
|
||||
}
|
||||
|
||||
_edited = edited;
|
||||
}
|
||||
|
||||
- (void)setArtworkEdited:(BOOL)artworkEdited
|
||||
{
|
||||
if (_artworkEdited != artworkEdited) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setArtworkEdited:_artworkEdited];
|
||||
}
|
||||
|
||||
_artworkEdited = artworkEdited;
|
||||
}
|
||||
|
||||
#pragma mark - Supported metadata
|
||||
|
||||
+ (NSArray<NSString *> *)availableMetadata
|
||||
@@ -296,16 +314,23 @@
|
||||
// as we don't support multiple languages yet,
|
||||
// Allow multiple MP42MetadataKeyCoverArt items.
|
||||
if ([item.identifier isEqualToString:MP42MetadataKeyCoverArt]) {
|
||||
self.artworkEdited = YES;
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.artworkEdited = YES;
|
||||
}
|
||||
} else {
|
||||
MP42MetadataItem *existingItem = self.itemsMap[item.identifier];
|
||||
if (existingItem) {
|
||||
[self.itemsArray removeObject:existingItem];
|
||||
[self removeMetadataItem:existingItem];
|
||||
}
|
||||
}
|
||||
[self.itemsArray addObject:item];
|
||||
[self.itemsMap setObject:item forKey:item.identifier];
|
||||
self.edited = YES;
|
||||
|
||||
[[self.undo prepareWithInvocationTarget:self] removeMetadataItem:item];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)addMetadataItems:(NSArray<MP42MetadataItem *> *)items
|
||||
@@ -317,14 +342,18 @@
|
||||
|
||||
- (void)removeMetadataItem:(MP42MetadataItem *)item
|
||||
{
|
||||
[[self.undo prepareWithInvocationTarget:self] addMetadataItem:item];
|
||||
|
||||
[self.itemsArray removeObject:item];
|
||||
[self.itemsMap removeObjectForKey:item.identifier];
|
||||
|
||||
if ([item.identifier isEqualToString:MP42MetadataKeyCoverArt]) {
|
||||
self.artworkEdited = YES;
|
||||
}
|
||||
else {
|
||||
self.edited = YES;
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
if ([item.identifier isEqualToString:MP42MetadataKeyCoverArt]) {
|
||||
self.artworkEdited = YES;
|
||||
}
|
||||
else {
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,9 +463,6 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.edited = YES;
|
||||
self.artworkEdited = YES;
|
||||
}
|
||||
|
||||
#pragma mark - MP42Foundation/mp4v2 read/write mapping
|
||||
|
||||
+111
-85
@@ -15,6 +15,7 @@
|
||||
|
||||
#import "MatroskaParser.h"
|
||||
#import "MatroskaFile.h"
|
||||
#import "MP42MatroskaTagMapping.h"
|
||||
#include "avutil.h"
|
||||
|
||||
#import "MP42PrivateUtilities.h"
|
||||
@@ -79,6 +80,11 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
}
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)outError
|
||||
{
|
||||
return [self initWithURL:fileURL tagsOnly:NO error:outError];
|
||||
}
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL tagsOnly:(BOOL)tagsOnly error:(NSError * __autoreleasing *)outError
|
||||
{
|
||||
if ((self = [super initWithURL:fileURL])) {
|
||||
_ioStream = calloc(1, sizeof(StdIoStream));
|
||||
@@ -263,6 +269,15 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
}
|
||||
|
||||
if (newTrack) {
|
||||
if (tagsOnly) {
|
||||
// Tags-only documents are diffed against the file on save
|
||||
// (see MP42MkvTagWriter): the model must mirror the
|
||||
// file's own TrackFlagEnabled, otherwise the MP4-oriented
|
||||
// heuristic below would make untouched tracks look
|
||||
// edited and the first save would rewrite every flag.
|
||||
newTrack.enabled = mkvTrack->Enabled != 0;
|
||||
}
|
||||
|
||||
newTrack.format = CodecIDToFourCC(mkvTrack);
|
||||
|
||||
if ([newTrack isKindOfClass:[MP42VideoTrack class]] && ((MP42VideoTrack *)newTrack).dolbyVision.profile == 5) {
|
||||
@@ -303,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 {
|
||||
@@ -324,13 +358,28 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
UInt64 scaledDuration = (UInt64)segInfo->Duration / SCALE_FACTOR;
|
||||
[newTrack setDuration:scaledDuration];
|
||||
|
||||
// Chapter Start/End are absolute *nanoseconds* regardless of the
|
||||
// segment's TimecodeScale — libmatroska writes and reads them that
|
||||
// way (verified against mkvmerge-written files read back by both
|
||||
// mkvinfo and ffprobe), so ns -> ms is a plain /1e6. The parser's
|
||||
// Seg.Duration, by contrast, is already ns-scaled.
|
||||
for (unsigned int xi = 0; xi < chapters->nChildren; xi++) {
|
||||
uint64_t timestamp = (chapters->Children[xi].Start) / SCALE_FACTOR;
|
||||
if (!xi) {
|
||||
timestamp = 0;
|
||||
}
|
||||
if (xi && timestamp == 0) {
|
||||
continue;
|
||||
if (!tagsOnly) {
|
||||
// MP4 chapter tracks start at 0 and never carry a second
|
||||
// zero-start entry — normalize for the conversion path.
|
||||
// Matroska allows both shapes (mkvmerge writes them), and
|
||||
// in tagsOnly mode the model is the baseline a later
|
||||
// Chapters rewrite rebuilds from: dropping an atom or
|
||||
// shifting the first start here would silently corrupt
|
||||
// those chapters on the first edit. The remuxer sorts and
|
||||
// clamps ties to previous+1ms on the way out.
|
||||
if (!xi) {
|
||||
timestamp = 0;
|
||||
}
|
||||
if (xi && timestamp == 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (chapters->Children[xi].Display && strlen(chapters->Children[xi].Display->String)) {
|
||||
[newTrack addChapter:[NSString stringWithUTF8String:chapters->Children[xi].Display->String]
|
||||
@@ -340,10 +389,27 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
timestamp:timestamp];
|
||||
}
|
||||
}
|
||||
|
||||
// The model keeps one language per chapter track; ChapterDisplay
|
||||
// allows one per atom — adopt the first ChapterLanguage found.
|
||||
// Without this the remuxer's rebuild silently drops non-English
|
||||
// chapter languages (it derives ChapterLanguage from this very
|
||||
// property; absent/eng = omitted = spec default "eng").
|
||||
for (unsigned int xi = 0; xi < chapters->nChildren; xi++) {
|
||||
struct ChapterDisplay *display = chapters->Children[xi].Display;
|
||||
if (display && display->Language[0]) {
|
||||
NSString *chapterLang = [MP42Languages.defaultManager
|
||||
extendedTagForISO_639_2b:@(display->Language)];
|
||||
if (chapterLang.length) {
|
||||
newTrack.language = chapterLang;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
[self addTrack:newTrack];
|
||||
}
|
||||
|
||||
[self.metadata mergeMetadata:[self readMatroskaMetadata] overwrite:true];
|
||||
[self.metadata mergeMetadata:[self readMatroskaMetadataTagsOnly:tagsOnly] overwrite:true];
|
||||
}
|
||||
|
||||
return self;
|
||||
@@ -356,24 +422,24 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
|
||||
#pragma mark - Metadata
|
||||
|
||||
#define COLLECTION 70
|
||||
#define SEASON 60
|
||||
#define MOVIE 50
|
||||
#define PART 40
|
||||
#define CHAPTER 30
|
||||
#define SCENE 20
|
||||
#define SHOT 10
|
||||
|
||||
- (void)addMetadataItem:(id)value identifier:(NSString *)identifier metadata:(MP42Metadata *)metadata
|
||||
{
|
||||
[self addMetadataItem:value identifier:identifier language:nil metadata:metadata];
|
||||
}
|
||||
|
||||
- (void)addMetadataItem:(id)value
|
||||
identifier:(NSString *)identifier
|
||||
language:(NSString *)language
|
||||
metadata:(MP42Metadata *)metadata
|
||||
{
|
||||
MP42MetadataItem *item = [MP42MetadataItem metadataItemWithIdentifier:identifier
|
||||
value:value
|
||||
dataType:MP42MetadataItemDataTypeUnspecified
|
||||
extendedLanguageTag:nil];
|
||||
extendedLanguageTag:language];
|
||||
[metadata addMetadataItem:item];
|
||||
}
|
||||
|
||||
- (MP42Metadata *)readMatroskaMetadata
|
||||
- (MP42Metadata *)readMatroskaMetadataTagsOnly:(BOOL)tagsOnly
|
||||
{
|
||||
MP42Metadata *metadata = [[MP42Metadata alloc] init];
|
||||
|
||||
@@ -385,57 +451,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
metadata:metadata];
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSString *> *simpleMap = @{
|
||||
@"TITLE": MP42MetadataKeyName,
|
||||
@"SUBTITLE": MP42MetadataKeyTrackSubTitle,
|
||||
@"ALBUM": MP42MetadataKeyAlbum,
|
||||
@"ARTIST": MP42MetadataKeyArtist,
|
||||
|
||||
@"COMMENT": MP42MetadataKeyUserComment,
|
||||
@"GENRE": MP42MetadataKeyUserGenre,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
|
||||
@"BPM": MP42MetadataKeyBeatsPerMin,
|
||||
|
||||
@"KEYWORDS": MP42MetadataKeyKeywords,
|
||||
@"THANKS_TO": MP42MetadataKeyThanks,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
|
||||
@"DESCRIPTION": MP42MetadataKeyDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeyLongDescription,
|
||||
|
||||
@"DIRECTOR_OF_PHOTOGRAPHY": MP42MetadataKeyArtDirector,
|
||||
@"COMPOSER": MP42MetadataKeyComposer,
|
||||
@"ARRANGER": MP42MetadataKeyArranger,
|
||||
@"WRITTEN_BY": MP42MetadataKeyAuthor,
|
||||
@"LYRICS": MP42MetadataKeyLyrics,
|
||||
@"CONDUCTOR": MP42MetadataKeyConductor,
|
||||
@"PUBLISHER": MP42MetadataKeyPublisher,
|
||||
@"SOUND_ENGINEER": MP42MetadataKeySoundEngineer,
|
||||
@"LEAD_PERFORMER": MP42MetadataKeySoloist,
|
||||
|
||||
@"PRODUCTION_STUDIO": MP42MetadataKeyStudio,
|
||||
@"DIRECTOR": MP42MetadataKeyDirector,
|
||||
@"PRODUCER": MP42MetadataKeyProducer,
|
||||
@"EXECUTIVE_PRODUCER": MP42MetadataKeyExecProducer,
|
||||
@"SCREENPLAY_BY": MP42MetadataKeyScreenwriters,
|
||||
|
||||
@"ENCODER": MP42MetadataKeyEncodingTool,
|
||||
};
|
||||
|
||||
NSDictionary<NSString *, NSString *> *collectionMap = @{
|
||||
@"TITLE": MP42MetadataKeyTVShow,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
};
|
||||
|
||||
NSDictionary<NSString *, NSString *> *seasonMap = @{
|
||||
@"PART_NUMBER": MP42MetadataKeyTVSeason,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate
|
||||
};
|
||||
// The SimpleTag maps live in MP42MatroskaTagMapping.h, shared verbatim
|
||||
// with MP42MkvTagWriter so reading and writing cannot drift apart.
|
||||
|
||||
unsigned count;
|
||||
Tag *tag_groups;
|
||||
@@ -448,8 +465,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
for (unsigned int xi = 0; xi < count; xi++) {
|
||||
Tag *tags = &tag_groups[xi];
|
||||
|
||||
ulonglong UID = 0;
|
||||
NSDictionary<NSString *, NSString *> *map = simpleMap;
|
||||
NSInteger level = MP42MkvTargetGlobal;
|
||||
NSDictionary<NSString *, NSString *> *map = nil;
|
||||
|
||||
if (tags->nTargetsSize) {
|
||||
struct Target *target = &tags->Targets[0];
|
||||
@@ -458,21 +475,15 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
continue;
|
||||
}
|
||||
|
||||
UID = target->UID;
|
||||
level = (NSInteger)target->UID;
|
||||
|
||||
if (UID == CHAPTER ||
|
||||
UID == SCENE ||
|
||||
UID == SHOT) {
|
||||
if (!MP42MkvTargetLevelIsModeled(level)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (UID == COLLECTION) {
|
||||
map = collectionMap;
|
||||
} else if (UID == SEASON) {
|
||||
map = seasonMap;
|
||||
}
|
||||
}
|
||||
|
||||
map = MP42MkvSimpleTagMapForTargetLevel(level);
|
||||
|
||||
for (unsigned int yi = 0; yi < tags->nSimpleTags; yi++) {
|
||||
struct SimpleTag *tag = &tags->SimpleTags[yi];
|
||||
|
||||
@@ -480,11 +491,19 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
NSString *simpleTagKey = @(tag->Name);
|
||||
NSString *key = map[simpleTagKey];
|
||||
|
||||
// Preserve non-default tag languages for the round trip
|
||||
// back through MP42MkvTagWriter.
|
||||
NSString *language = nil;
|
||||
if (tag->Language[0] && strcasecmp(tag->Language, "und") != 0) {
|
||||
language = @(tag->Language);
|
||||
}
|
||||
|
||||
if (key && tag->Value) {
|
||||
[self addMetadataItem:@(tag->Value)
|
||||
identifier:key
|
||||
language:language
|
||||
metadata:metadata];
|
||||
} else if (UID == SEASON &&
|
||||
} else if (level == MP42MkvTargetSeason &&
|
||||
[simpleTagKey isEqualToString:@"TOTAL_PARTS"]) {
|
||||
total_parts = tag->Value;
|
||||
} else if ([simpleTagKey isEqualToString:@"PART_NUMBER"]) {
|
||||
@@ -510,11 +529,18 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
identifier:MP42MetadataKeyTVEpisodeNumber
|
||||
metadata:metadata];
|
||||
|
||||
int season = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyTVSeason].firstObject.numberValue.intValue;
|
||||
if (season) {
|
||||
[self addMetadataItem:[NSString stringWithFormat:@"%d%02d", season, track]
|
||||
identifier:MP42MetadataKeyTVEpisodeID
|
||||
metadata:metadata];
|
||||
// Synthesize a "season x episode y" ID for the MP4 conversion path.
|
||||
// In tags-only mode this is skipped: the writer now round-trips
|
||||
// MP42MetadataKeyTVEpisodeID as EPISODEID, so a synthesized value
|
||||
// would leak into the file as a tag the user never set (and would
|
||||
// never converge). An explicit EPISODEID tag maps in normally.
|
||||
if (!tagsOnly) {
|
||||
int season = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyTVSeason].firstObject.numberValue.intValue;
|
||||
if (season) {
|
||||
[self addMetadataItem:[NSString stringWithFormat:@"%d%02d", season, track]
|
||||
identifier:MP42MetadataKeyTVEpisodeID
|
||||
metadata:metadata];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//
|
||||
// MP42MkvRemuxer.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Rebuilds a whole Matroska file, stream-copying every block verbatim
|
||||
// (no decode/re-encode) except the blocks of tracks the model dropped —
|
||||
// the job mkvpropedit cannot do (it corresponds to mkvmerge's copy mode
|
||||
// with tracks deselected). Used when the user deletes tracks in a
|
||||
// tags-only document, when the user adds a subtitle file to one, and for
|
||||
// MKV Save-As to another URL.
|
||||
//
|
||||
// The Tracks, Tags and Attachments payloads are built with the exact
|
||||
// model-diff builders MP42MkvTagWriter uses, so a remux save applies
|
||||
// metadata edits, cover art and the four per-track fields in the same
|
||||
// pass. SeekHead entries and (when the source had Cues) the Cues element
|
||||
// are regenerated with fresh positions; no source block header is ever
|
||||
// modified, so the remaining tracks' TrackNumber values may be gapped
|
||||
// after a removal (valid Matroska, and what avoids any block rewrite).
|
||||
//
|
||||
// Added tracks: a model track absent from sourceTracks (by identity) must
|
||||
// be an MP42SubtitleTrack whose URL ends in .srt/.ssa/.ass; its text is
|
||||
// re-parsed from the URL at save time (the model never holds it) and
|
||||
// written as S_TEXT/UTF8 BlockGroup{Block, BlockDuration} elements, past
|
||||
// a fresh appended TrackEntry numbered past every number in the file.
|
||||
// Blocks land in the original cluster whose Timecode window contains them
|
||||
// (merged by timestamp); pathologically long clusters, emptied clusters
|
||||
// and blocks outside every cluster's int16 range get their own
|
||||
// synthesized Cluster elements instead — no original cluster is split.
|
||||
// Chapters: by default the source Chapters element is copied verbatim.
|
||||
// Setting replacementChapters regenerates it from the model track —
|
||||
// EditionEntry{ChapterAtom{ChapterTimeStart/End, ChapterDisplay{
|
||||
// ChapterString}}} — with times converted from the model's milliseconds
|
||||
// to absolute nanoseconds (chapter timecodes are ns in the wild, not
|
||||
// TimecodeScale ticks), sorted ascending (ties clamped to previous + 1
|
||||
// ms, as mkvmerge requires), each atom's end being the next atom's start
|
||||
// and the last atom ending at the track duration when known.
|
||||
// A replacement track with zero chapters removes the element (and its
|
||||
// SeekHead entry) entirely. Chapters live before the Clusters, so any
|
||||
// size change shifts every following byte — full-rebuild territory, which
|
||||
// is why chapter writing lives here and not in MP42MkvTagWriter.
|
||||
//
|
||||
// Guarantees / edges:
|
||||
// - Blocks, CodecPrivate data and Info are copied byte-for-byte, except
|
||||
// that an existing Info Duration is recomputed to the end of the last
|
||||
// written block (plus 1 ms) whenever the pass measured one, so a
|
||||
// removal no longer leaves an overstated duration behind. Files whose
|
||||
// Info never had a Duration keep having none.
|
||||
// - Dangling references to removed tracks (DefaultTrackUID,
|
||||
// ChapterTrackUID) are preserved; readers ignore unknown UIDs.
|
||||
// - In-place writes go through a temp file in the destination directory
|
||||
// and an atomic rename; the staleness guard checks the *source* size
|
||||
// and mtime as usual.
|
||||
// - Refuses: multiple Segments, unknown-size elements other than the
|
||||
// trailing cluster, unknown-size elements inside Tracks or clusters,
|
||||
// remuxes that would leave zero tracks, and added tracks that are not
|
||||
// parseable .srt/.ssa/.ass subtitle files.
|
||||
// - SSA styling is stripped to plain text (same conversion the MP4 mux
|
||||
// path applies); per-line SRT "!!!" forced markers and top-position
|
||||
// markers are not carried into the Matroska blocks.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class MP42Metadata;
|
||||
@class MP42Track;
|
||||
@class MP42ChapterTrack;
|
||||
|
||||
@interface MP42MkvRemuxer : NSObject
|
||||
|
||||
@property (nonatomic, readonly) NSURL *sourceURL;
|
||||
|
||||
// When set, the remux refuses to touch a source file whose size or
|
||||
// modification date no longer matches (callers snapshot these when the
|
||||
// document is read). Leave unset for Save-As onto a fresh destination.
|
||||
@property (nonatomic) uint64_t expectedFileSize;
|
||||
@property (nonatomic, copy, nullable) NSDate *expectedModificationDate;
|
||||
|
||||
// Called on the remuxing thread with a 0...1 estimate; may be nil.
|
||||
@property (nonatomic, copy, nullable) void (^progressHandler)(double progress);
|
||||
|
||||
// nil (default): the source Chapters element is copied verbatim. Non-nil:
|
||||
// the Chapters element is rebuilt from this track's chapters (see the
|
||||
// header notes); a track with no chapters removes the element. Timestamps
|
||||
// are model milliseconds (timescale 1000); they are written as absolute
|
||||
// nanoseconds (x1e6) — Matroska chapter timecodes are ns regardless of
|
||||
// the segment's TimecodeScale, as mkvtoolnix and ffmpeg both read them.
|
||||
@property (nonatomic, strong, nullable) MP42ChapterTrack *replacementChapters;
|
||||
|
||||
- (instancetype)initWithSourceURL:(NSURL *)sourceURL;
|
||||
|
||||
// sourceTracks must be the tracks exactly as the importer produced them
|
||||
// (file order, chapter pseudo-track filtered out) — TrackEntry elements
|
||||
// are paired with them by position. currentTracks is the document model's
|
||||
// track list after user edits; entries whose paired sourceTracks object
|
||||
// is no longer present (compared by object identity) are removed, and
|
||||
// model tracks with no sourceTracks counterpart are appended as new
|
||||
// S_TEXT/UTF8 subtitle tracks (see the header notes).
|
||||
//
|
||||
// Safe to call from another thread while -cancel may fire; the write
|
||||
// aborts at the next chunk boundary and the partial temp file is
|
||||
// discarded.
|
||||
- (BOOL)remuxToURL:(NSURL *)destURL
|
||||
metadata:(MP42Metadata *)metadata
|
||||
sourceTracks:(NSArray<MP42Track *> *)sourceTracks
|
||||
currentTracks:(NSArray<MP42Track *> *)currentTracks
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
//
|
||||
// MP42MkvTagWriter+Internal.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Internal (not framework-exported) declarations shared between
|
||||
// MP42MkvTagWriter and MP42MkvRemuxer. The scanned file model and the
|
||||
// payload builders live in the tag writer's implementation; the remuxer
|
||||
// rebuilds a whole file from the same structures and builders so the two
|
||||
// writers can never drift on what a "tagged save" means. Do not import
|
||||
// this header from outside the framework, and never add it to the public
|
||||
// headers build phase.
|
||||
//
|
||||
|
||||
#import "MP42MkvTagWriter.h"
|
||||
|
||||
#import "MP42MatroskaTagMapping.h"
|
||||
|
||||
@class MP42Metadata;
|
||||
@class MP42Track;
|
||||
|
||||
typedef NS_ENUM(NSInteger, MP42MkvKidKind) {
|
||||
MP42MkvKidKeep = 0,
|
||||
MP42MkvKidTags,
|
||||
MP42MkvKidAttachments,
|
||||
MP42MkvKidTracks,
|
||||
MP42MkvKidSeekHead,
|
||||
MP42MkvKidCues,
|
||||
MP42MkvKidCluster,
|
||||
};
|
||||
|
||||
// A direct child of the Segment element plus its rewrite plan. All "rel"
|
||||
// quantities are byte offsets relative to the segment *data* start, which is
|
||||
// the same origin SeekHead/Cue positions use; that keeps position math
|
||||
// independent of any width change to the Segment header itself.
|
||||
@interface MP42MkvKid : NSObject
|
||||
@property (nonatomic, strong) MP42EbmlElement *el;
|
||||
@property (nonatomic) MP42MkvKidKind kind;
|
||||
@property (nonatomic, strong, nullable) NSData *payload; // parsed kinds only
|
||||
@property (nonatomic, strong, nullable) NSData *pendingPayload; // set when the payload is rewritten
|
||||
@property (nonatomic) BOOL removed; // element disappears
|
||||
@property (nonatomic) BOOL materializeUnknown; // cluster header: unknown size -> known
|
||||
@property (nonatomic) uint64_t relStart; // el.start - segment data start
|
||||
@property (nonatomic) uint64_t newStart; // plan-domain, relative to data start
|
||||
- (uint64_t)oldTotal;
|
||||
@end
|
||||
|
||||
// Snapshot of the file structure the rewrite operates on.
|
||||
@interface MP42MkvFile : NSObject
|
||||
@property (nonatomic, strong) MP42EbmlElement *segment;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *kids;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *tags;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *attachments;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *tracks;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *firstCluster;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *seekHeads;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *cues;
|
||||
@property (nonatomic) BOOL segmentSizeUnknown;
|
||||
@property (nonatomic) uint64_t segDataStart; // absolute
|
||||
@property (nonatomic) uint64_t segDataLen; // old data length (to EOF when unknown)
|
||||
@end
|
||||
|
||||
// Per-field rewrite plan inside one TrackEntry (see editTrackEntry:…).
|
||||
typedef NS_ENUM(NSInteger, MP42MkvFieldAction) {
|
||||
MP42MkvFieldKeep = 0, // leave the existing element untouched
|
||||
MP42MkvFieldDrop, // remove every element with this id
|
||||
MP42MkvFieldSet, // replace the first occurrence (append if absent)
|
||||
};
|
||||
|
||||
@interface MP42MkvFieldEdit : NSObject
|
||||
@property (nonatomic) MP42MkvFieldAction action;
|
||||
@property (nonatomic, strong, nullable) NSData *payload; // Set only
|
||||
@property (nonatomic) uint32_t appendId; // id used when the file has no such element
|
||||
@end
|
||||
|
||||
// Maps an old SeekPosition (segment-data-relative) to its new value; sets
|
||||
// *drop for entries pointing into a removed element.
|
||||
typedef uint64_t (^MP42MkvPosMapper)(uint64_t relPos, BOOL *drop);
|
||||
|
||||
@interface MP42MkvTagWriter ()
|
||||
|
||||
// The members MP42MkvRemuxer drives. Semantics and nullability are as
|
||||
// documented at each implementation in MP42MkvTagWriter.m.
|
||||
|
||||
- (BOOL)checkStalenessWithError:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable MP42MkvFile *)scanFile:(MP42EbmlScanner *)scanner error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable NSData *)buildTagsPayloadForMetadata:(MP42Metadata *)metadata
|
||||
file:(MP42MkvFile *)file
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)buildAttachmentsPayloadForMetadata:(MP42Metadata *)metadata
|
||||
file:(MP42MkvFile *)file
|
||||
payload:(NSData * _Nullable *)outPayload
|
||||
changed:(BOOL *)outChanged
|
||||
shouldExist:(BOOL *)outShouldExist
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)buildTracksPayloadForTracks:(NSArray<MP42Track *> *)modelTracks
|
||||
file:(MP42MkvFile *)file
|
||||
payload:(NSData * _Nullable *)outPayload
|
||||
changed:(BOOL *)outChanged
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable NSData *)editTrackEntry:(MP42EbmlElement *)entry
|
||||
buffer:(NSData *)buffer
|
||||
regionEnd:(uint64_t)regionEnd
|
||||
track:(MP42Track *)track
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Low-level output helpers (they consult -cancel and report progress on the
|
||||
// writer instance they are called on — the remuxer drives a helper writer
|
||||
// and mirrors its own state onto it).
|
||||
|
||||
- (BOOL)writeData:(NSData *)data
|
||||
fd:(int)fd
|
||||
offset:(uint64_t)offset
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)copyFromScanner:(MP42EbmlScanner *)scanner
|
||||
source:(uint64_t)sourceAbs
|
||||
length:(uint64_t)length
|
||||
toFD:(int)outFd
|
||||
outOffset:(uint64_t *)outOffset
|
||||
totalEstimate:(uint64_t)totalEstimate
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)appendData:(NSData *)data
|
||||
toFD:(int)fd
|
||||
outOffset:(uint64_t *)outOffset
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// MP42MkvTagWriter.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Rewrites the Tags element (and, when the cover art changed, the
|
||||
// Attachments element) of an existing Matroska file in place, leaving all
|
||||
// track payloads and clusters untouched. Conceptually the same job as
|
||||
// `mkvpropedit --tags`.
|
||||
//
|
||||
// When model tracks are supplied, the per-track fields the model exposes —
|
||||
// Name, TrackLanguage/LanguageIETF, TrackFlagEnabled and (for subtitles)
|
||||
// TrackFlagForced — are diffed against each TrackEntry's effective values
|
||||
// and the Tracks element is rebuilt with only the changed fields
|
||||
// substituted. Conceptually `mkvpropedit --edit track:… --set …`; all other
|
||||
// TrackEntry children (CodecPrivate, timings, …) are copied byte-for-byte.
|
||||
//
|
||||
// When the new content fits into the old element's extent plus the Void
|
||||
// padding that follows it, the region is rewritten without shifting any
|
||||
// other byte (fast path, SeekHead/Cues/Segment stay valid). Otherwise the
|
||||
// file tail is rebuilt through a temporary file, SeekHead and Cues position
|
||||
// entries are recomputed, and the result atomically replaces the original.
|
||||
//
|
||||
// Tag groups Subler does not model (chapter/scene/shot targets, track/
|
||||
// edition/attachment targets, unmapped SimpleTag names such as ACTOR,
|
||||
// binary-valued tags) and non-cover attachments are preserved verbatim from
|
||||
// the file on disk, so saving never silently drops data the UI never showed.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <MP42Foundation/MP42Ebml.h>
|
||||
|
||||
@class MP42Metadata;
|
||||
@class MP42Track;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MP42MkvTagWriter : NSObject
|
||||
|
||||
@property (nonatomic, readonly) NSURL *fileURL;
|
||||
|
||||
// When set, the write refuses to touch a file whose size or modification
|
||||
// date no longer matches (callers snapshot these when the document is read).
|
||||
@property (nonatomic) uint64_t expectedFileSize;
|
||||
@property (nonatomic, copy, nullable) NSDate *expectedModificationDate;
|
||||
|
||||
// Called on the writing thread with a 0...1 estimate; may be nil.
|
||||
@property (nonatomic, copy, nullable) void (^progressHandler)(double progress);
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)URL;
|
||||
|
||||
- (BOOL)writeMetadata:(MP42Metadata *)metadata error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Also apply per-track edits (name, language, enabled, subtitle forced)
|
||||
// taken from the model tracks. The array must hold the document's tracks in
|
||||
// file order; chapter tracks are ignored (they are not Matroska tracks).
|
||||
// Pass nil to leave the Tracks element untouched.
|
||||
- (BOOL)writeMetadata:(MP42Metadata *)metadata
|
||||
tracks:(nullable NSArray<MP42Track *> *)tracks
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Safe to call from another thread while -writeMetadata:error: is running;
|
||||
// the write aborts at the next chunk boundary leaving the original file
|
||||
// untouched.
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
File diff suppressed because it is too large.
Load diff
@@ -338,7 +338,7 @@ typedef struct MP4DemuxHelper {
|
||||
NSUInteger tracksNumber = inputTracks.count;
|
||||
NSUInteger tracksDone = 0;
|
||||
|
||||
MP4DemuxHelper * helpers[tracksNumber];
|
||||
MP4DemuxHelper *helpers[tracksNumber];
|
||||
|
||||
for (NSUInteger index = 0; index < tracksNumber; index += 1) {
|
||||
MP42Track *track = inputTracks[index];
|
||||
|
||||
+68
-11
@@ -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];
|
||||
@@ -576,7 +613,27 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
continue;
|
||||
}
|
||||
|
||||
dstTrackId = MP4AddSubpicTrack(_fileHandle, timeScale, 640, 480);
|
||||
MP42SubtitleTrack *subTrack = (MP42SubtitleTrack *)track;
|
||||
// Prefer the user-editable scaled size (tkhd), fall back to the size
|
||||
// declared by the source subtitle itself (e.g. the vobsub idx `size:`
|
||||
// line), then to the historical 640x480 default.
|
||||
uint16_t subpicWidth = 640, subpicHeight = 480;
|
||||
if (subTrack.trackWidth >= 1 && subTrack.trackWidth <= UINT16_MAX &&
|
||||
subTrack.trackHeight >= 1 && subTrack.trackHeight <= UINT16_MAX) {
|
||||
subpicWidth = (uint16_t)subTrack.trackWidth;
|
||||
subpicHeight = (uint16_t)subTrack.trackHeight;
|
||||
} else if (subTrack.width >= 1 && subTrack.width <= UINT16_MAX &&
|
||||
subTrack.height >= 1 && subTrack.height <= UINT16_MAX) {
|
||||
subpicWidth = (uint16_t)subTrack.width;
|
||||
subpicHeight = (uint16_t)subTrack.height;
|
||||
}
|
||||
|
||||
dstTrackId = MP4AddSubpicTrack(_fileHandle, timeScale, subpicWidth, subpicHeight);
|
||||
|
||||
// Mirror the written display size back into the model, like the
|
||||
// 3GText branch does, so the GUI shows what was actually muxed.
|
||||
subTrack.trackWidth = subpicWidth;
|
||||
subTrack.trackHeight = subpicHeight;
|
||||
|
||||
uint32_t *subPalette = (uint32_t *) magicCookie.bytes;
|
||||
for (int ii = 0; ii < 16; ii++) {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+39
-20
@@ -181,13 +181,20 @@ static NSArray<NSString *> * parse(NSString * string, NSUInteger count, BOOL mkv
|
||||
NSScanner *sc = [NSScanner scannerWithString:string];
|
||||
NSMutableArray<NSString *> *valuesArray = [NSMutableArray array];
|
||||
|
||||
// No field layout (header scan found nothing): there is nothing to split
|
||||
// into. Without this guard the `count - 1` loop bound below underflows
|
||||
// and appends empty values until the array traps.
|
||||
if (count == 0) {
|
||||
return valuesArray;
|
||||
}
|
||||
|
||||
if (mkvStyle || [sc scanUpToString:@"Dialogue:" intoString:nil] || [sc scanString:@"Dialogue:" intoString:nil]) {
|
||||
[sc scanString:@"Dialogue:" intoString:nil];
|
||||
|
||||
NSString *value;
|
||||
|
||||
for (NSUInteger index = 0; index < count - 1; index += 1) {
|
||||
if ([sc scanUpToString:@"," intoString:&value]) {
|
||||
if ([sc scanUpToString:@"," intoString:&value] && value) {
|
||||
[valuesArray addObject:value];
|
||||
}
|
||||
else {
|
||||
@@ -322,24 +329,30 @@ static NSMutableString *STStandardizeStringNewlines(NSString *str)
|
||||
|
||||
- (void)parseHeader:(NSString *)header
|
||||
{
|
||||
NSString *info;
|
||||
NSString *styles;
|
||||
NSString *format;
|
||||
|
||||
NSScanner *sc = [NSScanner scannerWithString:header];
|
||||
[sc setCharactersToBeSkipped:nil];
|
||||
|
||||
if ([sc scanUpToString:@"[V4+ Styles]" intoString:&info]) {
|
||||
_info = [self parseInfo:info];
|
||||
// A failed scanUpToString: consumes the whole string here, so the
|
||||
// section markers are located explicitly: a file without a
|
||||
// "[V4+ Styles]" section (plain SSA, or no styles at all) used to leave
|
||||
// the scan position at the end of the document, and the Format: line in
|
||||
// [Events] was never found — every Dialogue line then parsed to nothing.
|
||||
NSUInteger stylesLoc = [header rangeOfString:@"[V4+ Styles]"].location;
|
||||
NSUInteger eventsLoc = [header rangeOfString:@"[Events]"].location;
|
||||
if (stylesLoc != NSNotFound && (eventsLoc == NSNotFound || stylesLoc > eventsLoc)) {
|
||||
stylesLoc = NSNotFound; // a styles marker inside/after Events is not the styles header
|
||||
}
|
||||
|
||||
if ([sc scanUpToString:@"[Events]" intoString:&styles]) {
|
||||
_styles = [self parseStyles:styles];
|
||||
if (stylesLoc != NSNotFound) {
|
||||
_info = [self parseInfo:[header substringToIndex:stylesLoc]];
|
||||
NSUInteger stylesEnd = (eventsLoc != NSNotFound) ? eventsLoc : header.length;
|
||||
_styles = [self parseStyles:[header substringWithRange:NSMakeRange(stylesLoc, stylesEnd - stylesLoc)]];
|
||||
} else {
|
||||
NSUInteger stylesEnd = (eventsLoc != NSNotFound) ? eventsLoc : header.length;
|
||||
_styles = [self parseStyles:[header substringToIndex:stylesEnd]];
|
||||
}
|
||||
|
||||
format = [sc.string substringFromIndex:sc.scanLocation];
|
||||
if (format.length) {
|
||||
_format = [self parseFormat:format];
|
||||
if (eventsLoc != NSNotFound) {
|
||||
_format = [self parseFormat:[header substringFromIndex:eventsLoc]];
|
||||
} else if (stylesLoc == NSNotFound) {
|
||||
_format = [self parseFormat:header]; // no sections at all: last resort
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,11 +412,17 @@ static NSMutableString *STStandardizeStringNewlines(NSString *str)
|
||||
[sc scanString:@"Format:" intoString:nil];
|
||||
NSString *formats;
|
||||
if ([sc scanUpToString:@"\n" intoString:&formats]) {
|
||||
NSScanner *formatScanner = [NSScanner scannerWithString:formats];
|
||||
NSString *formatName;
|
||||
while ([formatScanner scanUpToString:@"," intoString:&formatName]) {
|
||||
[formatScanner scanString:@"," intoString:nil];
|
||||
[formatsArray addObject:formatName];
|
||||
// Split on commas and trim: a scanUpToString:@"," loop silently
|
||||
// drops the final field (no trailing comma), and SSA Format
|
||||
// lines separate names with ", " — the leading space made every
|
||||
// name (" Start", " Text", …) fail its comparison in
|
||||
// MP42SSALine, so no line ever got text/timestamps.
|
||||
for (NSString *field in [formats componentsSeparatedByString:@","]) {
|
||||
NSString *formatName = [field stringByTrimmingCharactersInSet:
|
||||
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
||||
if (formatName.length) {
|
||||
[formatsArray addObject:formatName];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -121,18 +121,29 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
|
||||
- (void)setSomeSamplesAreForced:(BOOL)value
|
||||
{
|
||||
_someSamplesAreForced = value;
|
||||
self.edited = YES;
|
||||
if (_someSamplesAreForced != value) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setSomeSamplesAreForced:_someSamplesAreForced];
|
||||
}
|
||||
|
||||
self.updatedProperty[@"forcedSubtitles"] = @YES;
|
||||
_someSamplesAreForced = value;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"forcedSubtitles"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setAllSamplesAreForced:(BOOL)value
|
||||
{
|
||||
if (_allSamplesAreForced != value) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setAllSamplesAreForced:_allSamplesAreForced];
|
||||
}
|
||||
_allSamplesAreForced = value;
|
||||
self.edited = YES;
|
||||
|
||||
self.updatedProperty[@"forcedSubtitles"] = @YES;
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"forcedSubtitles"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)canExport
|
||||
@@ -385,10 +396,18 @@ fail:
|
||||
|
||||
- (void)setForcedTrack:(MP42Track *)newForcedTrack
|
||||
{
|
||||
MP42Track *forcedTrackStrongRef = _forcedTrack;
|
||||
if (forcedTrackStrongRef != newForcedTrack) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setForcedTrack:forcedTrackStrongRef];
|
||||
}
|
||||
|
||||
_forcedTrack = newForcedTrack;
|
||||
_forcedTrackId = 0;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"forced"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"forced"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//
|
||||
// SBOcr.h
|
||||
// MP42TesseractOCR.h
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 27/03/11.
|
||||
@@ -8,15 +8,12 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42Utilities.h"
|
||||
#import "MP42TextRecognizer.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
MP42_OBJC_DIRECT_MEMBERS
|
||||
@interface MP42OCRWrapper : NSObject
|
||||
|
||||
- (instancetype)initWithLanguage:(NSString *)language;
|
||||
- (nullable NSString *)performOCROnCGImage:(CGImageRef)image;
|
||||
|
||||
@interface MP42TesseractOCR : NSObject<MP42TextRecognizer>
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,12 +1,12 @@
|
||||
//
|
||||
// SBOcr.mm
|
||||
// MP42TesseractOCR.mm
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 27/03/11.
|
||||
// Copyright 2022 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MP42OCRWrapper.h"
|
||||
#import "MP42TesseractOCR.h"
|
||||
#import "MP42Languages.h"
|
||||
|
||||
// Tesseract OCR
|
||||
@@ -22,7 +22,7 @@ public:
|
||||
if (base_path) {
|
||||
path = base_path.fileSystemRepresentation;
|
||||
} else {
|
||||
path = [[NSBundle bundleForClass:[MP42OCRWrapper class]].bundlePath stringByAppendingString:@"/Versions/A/Resources/tessdata/"].fileSystemRepresentation;
|
||||
path = [[NSBundle bundleForClass:[MP42TesseractOCR class]].bundlePath stringByAppendingString:@"/Versions/A/Resources/tessdata/"].fileSystemRepresentation;
|
||||
}
|
||||
|
||||
int result = tess_base_api.Init(path, lang.UTF8String, mode);
|
||||
@@ -49,7 +49,7 @@ protected:
|
||||
};
|
||||
|
||||
MP42_OBJC_DIRECT_MEMBERS
|
||||
@implementation MP42OCRWrapper {
|
||||
@implementation MP42TesseractOCR {
|
||||
OCRWrapper *tess_base;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// MP42TextRecognizer.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 29/09/2026.
|
||||
// Copyright © 2026 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol MP42TextRecognizer <NSObject>
|
||||
|
||||
- (instancetype)initWithLanguage:(NSString *)language;
|
||||
- (nullable NSString *)performOCROnCGImage:(CGImageRef)image;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -17,7 +17,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(MP42TrackId)trackID fileHandle:(MP42FileHandle)fileHandle;
|
||||
- (BOOL)writeToFile:(MP42FileHandle)fileHandle error:(NSError * __autoreleasing *)outError;
|
||||
|
||||
@property(nonatomic, readwrite) MP42TrackId trackId;
|
||||
// Localized media-type label ("Video", "Sound", …) shown when the container
|
||||
// carries no explicit track name.
|
||||
- (NSString *)defaultName;
|
||||
|
||||
// trackId is readwrite in the public header
|
||||
@property(nonatomic, readwrite) MP42TrackId sourceId;
|
||||
|
||||
@property(nonatomic, readwrite, copy, nullable) NSURL *URL;
|
||||
|
||||
+5
-1
@@ -21,7 +21,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
*/
|
||||
@interface MP42Track : NSObject <NSSecureCoding, NSCopying, MP42SecurityScope>
|
||||
|
||||
@property(nonatomic, readonly) MP42TrackId trackId;
|
||||
// The muxer assigns the final id while writing (-[MP42File addTrack:]
|
||||
// zeroes it to mark the track as pending); hosts that build a model which
|
||||
// is never muxed (e.g. Matroska tags-only documents) can restore display
|
||||
// ids directly.
|
||||
@property(nonatomic, readwrite) MP42TrackId trackId;
|
||||
|
||||
@property(nonatomic, readonly, copy, nullable) NSURL *URL;
|
||||
|
||||
|
||||
+36
-8
@@ -28,7 +28,7 @@ typedef struct muxer_helper {
|
||||
|
||||
@interface MP42Track ()
|
||||
|
||||
@property(nonatomic, readwrite) MP42TrackId trackId;
|
||||
// trackId is already readwrite in the public header (see MP42Track.h)
|
||||
@property(nonatomic, readwrite) MP42TrackId sourceId;
|
||||
|
||||
@property(nonatomic, readwrite, copy, nullable) NSURL *URL;
|
||||
@@ -85,14 +85,24 @@ typedef struct muxer_helper {
|
||||
}
|
||||
|
||||
// Extended language tag
|
||||
NSString *mdhdLanguage = [MP42Languages.defaultManager extendedTagForISO_639_2:getTrackLanguage(fileHandle, _trackId)];
|
||||
if (MP4HaveTrackAtom(fileHandle, _trackId, "mdia.elng.")) {
|
||||
const char *elng;
|
||||
if (MP4GetTrackStringProperty(fileHandle, _trackId, "mdia.elng.extended_language", &elng)) {
|
||||
_language = [NSString stringWithCString:elng encoding:NSASCIIStringEncoding];
|
||||
if ([_language isEqualToString:@"und"] && ![mdhdLanguage isEqualToString:@"und"]) {
|
||||
_language = mdhdLanguage;
|
||||
_edited = YES;
|
||||
_updatedProperty[@"language"] = @YES;
|
||||
}
|
||||
else if (![_language isEqualToString:@"und"] && [mdhdLanguage isEqualToString:@"und"]) {
|
||||
_edited = YES;
|
||||
_updatedProperty[@"language"] = @YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
_language = [MP42Languages.defaultManager extendedTagForISO_639_2:getTrackLanguage(fileHandle, _trackId)];
|
||||
_language = mdhdLanguage;
|
||||
}
|
||||
|
||||
_timescale = MP4GetTrackTimeScale(fileHandle, _trackId);
|
||||
@@ -260,6 +270,15 @@ typedef struct muxer_helper {
|
||||
return StringFromTime(_duration, 1000);
|
||||
}
|
||||
|
||||
- (void)setEdited:(BOOL)edited
|
||||
{
|
||||
if (_edited != edited) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setEdited:_edited];
|
||||
}
|
||||
|
||||
_edited = edited;
|
||||
}
|
||||
|
||||
@synthesize name = _name;
|
||||
|
||||
- (NSString *)name {
|
||||
@@ -275,6 +294,10 @@ typedef struct muxer_helper {
|
||||
|
||||
- (void)setName:(NSString *)newName
|
||||
{
|
||||
if ([newName isEqualToString:_name] == NO) {
|
||||
[(MP42Track *)[self.undo prepareWithInvocationTarget:self] setName:_name];
|
||||
}
|
||||
|
||||
if (newName.length) {
|
||||
_name = [newName copy];
|
||||
}
|
||||
@@ -290,10 +313,11 @@ typedef struct muxer_helper {
|
||||
- (void)setLanguage:(NSString *)language
|
||||
{
|
||||
if (![_language isEqualToString:language]) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setMediaCharacteristicTags:_mediaCharacteristicTags];
|
||||
_language = [language copy];
|
||||
[(MP42Track *)[self.undo prepareWithInvocationTarget:self] setLanguage:_language];
|
||||
}
|
||||
|
||||
_language = [language copy];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_updatedProperty[@"language"] = @YES;
|
||||
@@ -304,9 +328,10 @@ typedef struct muxer_helper {
|
||||
{
|
||||
if (![_mediaCharacteristicTags isEqualToSet:mediaCharacteristicTags]) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setMediaCharacteristicTags:_mediaCharacteristicTags];
|
||||
_mediaCharacteristicTags = [mediaCharacteristicTags copy];
|
||||
}
|
||||
|
||||
_mediaCharacteristicTags = [mediaCharacteristicTags copy];
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_updatedProperty[@"mediaCharacteristicTags"] = @YES;
|
||||
@@ -317,9 +342,10 @@ typedef struct muxer_helper {
|
||||
{
|
||||
if (_enabled != enabled) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setEnabled:_enabled];
|
||||
_enabled = enabled;
|
||||
}
|
||||
|
||||
_enabled = enabled;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_updatedProperty[@"enabled"] = @YES;
|
||||
@@ -330,9 +356,10 @@ typedef struct muxer_helper {
|
||||
{
|
||||
if (_alternateGroup != alternateGroup) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setAlternateGroup:_alternateGroup];
|
||||
_alternateGroup = alternateGroup;
|
||||
}
|
||||
|
||||
_alternateGroup = alternateGroup;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_updatedProperty[@"alternate_group"] = @YES;
|
||||
@@ -343,9 +370,10 @@ typedef struct muxer_helper {
|
||||
{
|
||||
if (_startOffset != startOffset) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setStartOffset:_startOffset];
|
||||
_startOffset = startOffset;
|
||||
}
|
||||
|
||||
_startOffset = startOffset;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
_updatedProperty[@"start_offset"] = @YES;
|
||||
|
||||
+106
-21
@@ -428,82 +428,160 @@ static uint32_t convertToFixedPoint(CGFloat value) {
|
||||
|
||||
- (void)setTrackWidth:(float)trackWidth
|
||||
{
|
||||
if (_trackWidth != trackWidth) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setTrackWidth:_trackWidth];
|
||||
}
|
||||
|
||||
_trackWidth = trackWidth;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTrackHeight:(float)trackHeight
|
||||
{
|
||||
if (_trackHeight != trackHeight) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setTrackHeight:_trackHeight];
|
||||
}
|
||||
|
||||
_trackHeight = trackHeight;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTransform:(CGAffineTransform)transform
|
||||
{
|
||||
if (CGAffineTransformEqualToTransform(_transform, transform) == false) {
|
||||
[(MP42VideoTrack *)[self.undo prepareWithInvocationTarget:self] setTransform:_transform];
|
||||
}
|
||||
|
||||
_transform = transform;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setColorPrimaries:(uint16_t)colorPrimaries
|
||||
{
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
if (_colorPrimaries != colorPrimaries) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setColorPrimaries:_colorPrimaries];
|
||||
}
|
||||
|
||||
_colorPrimaries = colorPrimaries;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTransferCharacteristics:(uint16_t)transferCharacteristics
|
||||
{
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
if (_transferCharacteristics != transferCharacteristics) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setTransferCharacteristics:_transferCharacteristics];
|
||||
}
|
||||
|
||||
_transferCharacteristics = transferCharacteristics;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setMatrixCoefficients:(uint16_t)matrixCoefficients
|
||||
{
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
if (_matrixCoefficients != matrixCoefficients) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setMatrixCoefficients:_matrixCoefficients];
|
||||
}
|
||||
|
||||
_matrixCoefficients = matrixCoefficients;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setColorRange:(uint16_t)colorRange
|
||||
{
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
if (_colorRange != colorRange) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setColorRange:_colorRange];
|
||||
}
|
||||
|
||||
_colorRange = colorRange;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"colr"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setMastering:(MP42MasteringDisplayMetadata)mastering
|
||||
{
|
||||
self.updatedProperty[@"mdcv"] = @YES;
|
||||
[[self.undo prepareWithInvocationTarget:self] setMastering:_mastering];
|
||||
_mastering = mastering;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"mdcv"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setColl:(MP42ContentLightMetadata)coll
|
||||
{
|
||||
self.updatedProperty[@"coll"] = @YES;
|
||||
[[self.undo prepareWithInvocationTarget:self] setColl:_coll];
|
||||
_coll = coll;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.updatedProperty[@"coll"] = @YES;
|
||||
self.edited = YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setHSpacing:(uint64_t)newHSpacing
|
||||
{
|
||||
if (_hSpacing != newHSpacing) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setHSpacing:_hSpacing];
|
||||
}
|
||||
|
||||
_hSpacing = newHSpacing;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"hSpacing"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"hSpacing"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setVSpacing:(uint64_t)newVSpacing
|
||||
{
|
||||
if (_vSpacing != newVSpacing) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setVSpacing:_vSpacing];
|
||||
}
|
||||
|
||||
_vSpacing = newVSpacing;
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"vSpacing"] = @YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
self.updatedProperty[@"vSpacing"] = @YES;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setNewProfile:(uint8_t)newProfile
|
||||
{
|
||||
if (_newProfile != newProfile) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setNewProfile:_newProfile];
|
||||
}
|
||||
|
||||
_newProfile = newProfile;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
|
||||
if (_newProfile == _origProfile) {
|
||||
self.updatedProperty[@"profile"] = @NO;
|
||||
@@ -515,8 +593,15 @@ static uint32_t convertToFixedPoint(CGFloat value) {
|
||||
|
||||
- (void)setNewLevel:(uint8_t)newLevel
|
||||
{
|
||||
if (_newLevel != newLevel) {
|
||||
[[self.undo prepareWithInvocationTarget:self] setNewLevel:_newLevel];
|
||||
}
|
||||
|
||||
_newLevel = newLevel;
|
||||
self.edited = YES;
|
||||
|
||||
if (!(self.undo.isUndoing || self.undo.isRedoing)) {
|
||||
self.edited = YES;
|
||||
}
|
||||
|
||||
if (_newLevel == _origLevel) {
|
||||
self.updatedProperty[@"level"] = @NO;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// MP42VisionOCR.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 29/09/2026.
|
||||
// Copyright © 2026 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MP42TextRecognizer.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
API_AVAILABLE(macos(13))
|
||||
@interface MP42VisionOCR : NSObject<MP42TextRecognizer>
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,65 @@
|
||||
//
|
||||
// MP42VisionOCR.m
|
||||
// MP42Foundation
|
||||
//
|
||||
// Created by Damiano Galassi on 29/09/2026.
|
||||
// Copyright © 2026 Damiano Galassi. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MP42VisionOCR.h"
|
||||
|
||||
@import Vision;
|
||||
|
||||
@interface MP42VisionOCR ()
|
||||
@property (nonatomic, readonly) NSString *language;
|
||||
@property (nonatomic, readonly) dispatch_semaphore_t done;
|
||||
@end
|
||||
|
||||
@implementation MP42VisionOCR
|
||||
|
||||
- (nonnull instancetype)initWithLanguage:(nonnull NSString *)language
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_language = [language copy];
|
||||
_done = dispatch_semaphore_create(0);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (nullable NSString *)performOCROnCGImage:(nonnull CGImageRef)image
|
||||
{
|
||||
__block NSMutableString *text = [[NSMutableString alloc] init];
|
||||
|
||||
VNImageRequestHandler *requestHandler = [[VNImageRequestHandler alloc] initWithCGImage:image options:@{}];
|
||||
|
||||
VNRecognizeTextRequest *textRequest = [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
|
||||
NSArray<VNRecognizedTextObservation *> *observations = request.results;
|
||||
if (observations.count) {
|
||||
for (VNRecognizedTextObservation *currentObservation in request.results) {
|
||||
NSArray<VNRecognizedText *> *topCandidate = [currentObservation topCandidates:1];
|
||||
VNRecognizedText *recognizedText = topCandidate.firstObject;
|
||||
if (recognizedText) {
|
||||
if (text.length) {
|
||||
[text appendString:@"\n"];
|
||||
}
|
||||
[text appendString:recognizedText.string];
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatch_semaphore_signal(self->_done);
|
||||
}];
|
||||
textRequest.recognitionLevel = VNRequestTextRecognitionLevelAccurate;
|
||||
textRequest.recognitionLanguages = @[_language];
|
||||
textRequest.revision = VNRecognizeTextRequestRevision3;
|
||||
textRequest.usesLanguageCorrection = YES;
|
||||
|
||||
NSError *error;
|
||||
[requestHandler performRequests:@[textRequest] error:&error];
|
||||
|
||||
dispatch_semaphore_wait(_done, DISPATCH_TIME_FOREVER);
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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
|
||||
{
|
||||
@@ -37,6 +40,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
NSString *language;
|
||||
int index;
|
||||
long duration;
|
||||
int imageWidth;
|
||||
int imageHeight;
|
||||
NSMutableArray<SBVobSubSample *> *samples;
|
||||
}
|
||||
|
||||
@@ -206,6 +211,13 @@ static NSArray<SBVobSubTrack *> * LoadVobSubSubtitles(NSURL *theDirectory, NSStr
|
||||
}
|
||||
}
|
||||
|
||||
// The `size:` line is global private data that appears before the
|
||||
// first track header, so apply it to every parsed track.
|
||||
for (SBVobSubTrack *track in tracks) {
|
||||
track->imageWidth = imageWidth;
|
||||
track->imageHeight = imageHeight;
|
||||
}
|
||||
|
||||
return [tracks copy];
|
||||
}
|
||||
bail:
|
||||
@@ -218,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];
|
||||
@@ -244,9 +319,27 @@ 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;
|
||||
|
||||
// Carry the frame size declared by the idx `size:` line into the
|
||||
// model, so the muxer can mux the subpic track at the size the
|
||||
// subtitle actually uses instead of a generic default.
|
||||
// Note: trackWidth/trackHeight are intentionally left unset here:
|
||||
// the tx3g conversion path reads them as the tx3g default text box
|
||||
// size, which must keep its own 0.15-height fallback.
|
||||
if (track->imageWidth > 0 && track->imageHeight > 0) {
|
||||
newTrack.width = (uint64_t)track->imageWidth;
|
||||
newTrack.height = (uint64_t)track->imageHeight;
|
||||
}
|
||||
|
||||
[self addTrack:newTrack];
|
||||
}
|
||||
|
||||
@@ -290,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];
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -1569,10 +1569,14 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) {
|
||||
errorjmp(mf,"Duplicate Track Name");
|
||||
STRGETA(mf,t.Name,len);
|
||||
break;
|
||||
case 0x22b59c: // Language
|
||||
case 0x22b59c: // Language (ISO-639-2/B; the id mkvtoolnix & ffmpeg write)
|
||||
readLangCC(mf, len, t.Language);
|
||||
break;
|
||||
case 0x22B59D: // LanguageBCP47
|
||||
case 0x447a: // TrackLanguage (newer spec id for the same ISO-639-2/B value)
|
||||
readLangCC(mf, len, t.Language);
|
||||
break;
|
||||
case 0x22B59D: // LanguageBCP47 (IETF BCP-47 tag, e.g. "en-US"; files
|
||||
// written by modern mkvtoolnix may carry only this one)
|
||||
STRGETA(mf,t.LanguageBCP47,len);
|
||||
break;
|
||||
case 0x86: // CodecID
|
||||
|
||||
@@ -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, ); }; };
|
||||
@@ -56,8 +68,11 @@
|
||||
A910B5F718394EB20064028F /* MP42Fifo.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C22F1823923100416A4E /* MP42Fifo.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
|
||||
A910B5F918394EB20064028F /* MP42FileImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2331823923100416A4E /* MP42FileImporter.m */; };
|
||||
A910B5FA18394EB20064028F /* sfifo.c in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2641823923200416A4E /* sfifo.c */; };
|
||||
A910B5FD18394EB20064028F /* MP42OCRWrapper.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */; };
|
||||
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 */; };
|
||||
@@ -203,8 +218,8 @@
|
||||
A9B9C28C1823923200416A4E /* MP42Mp4Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2411823923100416A4E /* MP42Mp4Importer.m */; };
|
||||
A9B9C28D1823923200416A4E /* MP42Muxer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2421823923100416A4E /* MP42Muxer.h */; };
|
||||
A9B9C28E1823923200416A4E /* MP42Muxer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2431823923100416A4E /* MP42Muxer.m */; };
|
||||
A9B9C28F1823923200416A4E /* MP42OCRWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2441823923100416A4E /* MP42OCRWrapper.h */; };
|
||||
A9B9C2901823923200416A4E /* MP42OCRWrapper.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */; };
|
||||
A9B9C28F1823923200416A4E /* MP42TesseractOCR.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C2441823923100416A4E /* MP42TesseractOCR.h */; };
|
||||
A9B9C2901823923200416A4E /* MP42TesseractOCR.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2451823923100416A4E /* MP42TesseractOCR.mm */; };
|
||||
A9B9C2941823923200416A4E /* MP42SampleBuffer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2491823923100416A4E /* MP42SampleBuffer.m */; };
|
||||
A9B9C2951823923200416A4E /* MP42SrtImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9B9C24A1823923100416A4E /* MP42SrtImporter.h */; };
|
||||
A9B9C2961823923200416A4E /* MP42SrtImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24B1823923100416A4E /* MP42SrtImporter.m */; };
|
||||
@@ -256,8 +271,22 @@
|
||||
A9ED5B141F824BC100E0E4FA /* MP42SSAImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9ED5B111F824BC000E0E4FA /* MP42SSAImporter.m */; };
|
||||
A9ED5B151F824BC100E0E4FA /* MP42SSAImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9ED5B121F824BC000E0E4FA /* MP42SSAImporter.h */; };
|
||||
A9ED5B161F824BC100E0E4FA /* MP42SSAImporter.h in Headers */ = {isa = PBXBuildFile; fileRef = A9ED5B121F824BC000E0E4FA /* MP42SSAImporter.h */; };
|
||||
A9FB3C73306BB5EC000B756D /* MP42TextRecognizer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9FB3C70306BB5EC000B756D /* MP42TextRecognizer.h */; };
|
||||
A9FB3C75306BB5EC000B756D /* MP42TextRecognizer.h in Headers */ = {isa = PBXBuildFile; fileRef = A9FB3C70306BB5EC000B756D /* MP42TextRecognizer.h */; };
|
||||
A9FB3C78306BB692000B756D /* MP42VisionOCR.m in Sources */ = {isa = PBXBuildFile; fileRef = A9FB3C77306BB692000B756D /* MP42VisionOCR.m */; };
|
||||
A9FB3C79306BB692000B756D /* MP42VisionOCR.h in Headers */ = {isa = PBXBuildFile; fileRef = A9FB3C76306BB692000B756D /* MP42VisionOCR.h */; };
|
||||
A9FB3C7A306BB692000B756D /* MP42VisionOCR.m in Sources */ = {isa = PBXBuildFile; fileRef = A9FB3C77306BB692000B756D /* MP42VisionOCR.m */; };
|
||||
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 */
|
||||
@@ -279,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>"; };
|
||||
@@ -370,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>"; };
|
||||
@@ -399,8 +439,8 @@
|
||||
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>"; };
|
||||
A9B9C2431823923100416A4E /* MP42Muxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Muxer.m; sourceTree = "<group>"; };
|
||||
A9B9C2441823923100416A4E /* MP42OCRWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42OCRWrapper.h; sourceTree = "<group>"; };
|
||||
A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MP42OCRWrapper.mm; sourceTree = "<group>"; };
|
||||
A9B9C2441823923100416A4E /* MP42TesseractOCR.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42TesseractOCR.h; sourceTree = "<group>"; };
|
||||
A9B9C2451823923100416A4E /* MP42TesseractOCR.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MP42TesseractOCR.mm; sourceTree = "<group>"; };
|
||||
A9B9C2481823923100416A4E /* MP42SampleBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SampleBuffer.h; sourceTree = "<group>"; };
|
||||
A9B9C2491823923100416A4E /* MP42SampleBuffer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SampleBuffer.m; sourceTree = "<group>"; };
|
||||
A9B9C24A1823923100416A4E /* MP42SrtImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SrtImporter.h; sourceTree = "<group>"; };
|
||||
@@ -455,7 +495,14 @@
|
||||
A9ED5B0C1F824A9B00E0E4FA /* MP42SSAParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SSAParser.m; sourceTree = "<group>"; };
|
||||
A9ED5B111F824BC000E0E4FA /* MP42SSAImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42SSAImporter.m; sourceTree = "<group>"; };
|
||||
A9ED5B121F824BC000E0E4FA /* MP42SSAImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42SSAImporter.h; sourceTree = "<group>"; };
|
||||
A9FB3C70306BB5EC000B756D /* MP42TextRecognizer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MP42TextRecognizer.h; sourceTree = "<group>"; };
|
||||
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 */
|
||||
@@ -520,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 = (
|
||||
@@ -584,6 +642,7 @@
|
||||
A9B9C2301823923100416A4E /* MP42File.h */,
|
||||
A9B9C2311823923100416A4E /* MP42File.m */,
|
||||
A9FD169E27661B690096BBA8 /* SampleDescription.swift */,
|
||||
5AB1E22600000000000000D1 /* Sup2Vob */,
|
||||
A9B9C2501823923100416A4E /* MP42Track.h */,
|
||||
A9B9C2511823923100416A4E /* MP42Track.m */,
|
||||
A99FCBC31BAD65EF0058E27A /* MP42Track+Private.h */,
|
||||
@@ -678,6 +737,15 @@
|
||||
A9B9C2571823923200416A4E /* MP42VobSubImporter.m */,
|
||||
A9B9C23E1823923100416A4E /* MP42MkvImporter.h */,
|
||||
A9B9C23F1823923100416A4E /* MP42MkvImporter.m */,
|
||||
5AB1E120261124000000000001 /* MP42Ebml.h */,
|
||||
5AB1E120261124000000000002 /* MP42Ebml.m */,
|
||||
5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */,
|
||||
5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */,
|
||||
5AB1E120261124000000000005 /* MP42MkvTagWriter.h */,
|
||||
5AB1E120261124000000000006 /* MP42MkvTagWriter.m */,
|
||||
5AB1E120261124000000000023 /* MP42MkvTagWriter+Internal.h */,
|
||||
5AB1E120261124000000000021 /* MP42MkvRemuxer.h */,
|
||||
5AB1E120261124000000000022 /* MP42MkvRemuxer.m */,
|
||||
A9B9C2401823923100416A4E /* MP42Mp4Importer.h */,
|
||||
A9B9C2411823923100416A4E /* MP42Mp4Importer.m */,
|
||||
A9B9C24A1823923100416A4E /* MP42SrtImporter.h */,
|
||||
@@ -749,10 +817,15 @@
|
||||
A9B9C2651823923200416A4E /* sfifo.h */,
|
||||
A97EA7C51D4B8A2D00257CEA /* FFmpegUtils.h */,
|
||||
A97EA7C61D4B8A2D00257CEA /* FFmpegUtils.m */,
|
||||
A9B9C2441823923100416A4E /* MP42OCRWrapper.h */,
|
||||
A9B9C2451823923100416A4E /* MP42OCRWrapper.mm */,
|
||||
A9FB3C70306BB5EC000B756D /* MP42TextRecognizer.h */,
|
||||
A9FB3C76306BB692000B756D /* MP42VisionOCR.h */,
|
||||
A9FB3C77306BB692000B756D /* MP42VisionOCR.m */,
|
||||
A9B9C2441823923100416A4E /* MP42TesseractOCR.h */,
|
||||
A9B9C2451823923100416A4E /* MP42TesseractOCR.mm */,
|
||||
A9B9C2251823923100416A4E /* MP42BitmapSubConverter.h */,
|
||||
A9B9C2261823923100416A4E /* MP42BitmapSubConverter.m */,
|
||||
AA00000118394EB20064028F /* MP42PgsToVobSubConverter.h */,
|
||||
AA00000218394EB20064028F /* MP42PgsToVobSubConverter.m */,
|
||||
A941C9541F82996600FC5E8D /* MP42TextSubConverter.h */,
|
||||
A941C9551F82996600FC5E8D /* MP42TextSubConverter.m */,
|
||||
A908010C1D4B83A3002B6950 /* MP42AudioDecoder.h */,
|
||||
@@ -785,7 +858,9 @@
|
||||
A90801161D4B83A3002B6950 /* MP42AudioEncoder.h in Headers */,
|
||||
A9762BAF2660D71E0055E0B3 /* MP42Rational.h in Headers */,
|
||||
A9ED5B161F824BC100E0E4FA /* MP42SSAImporter.h in Headers */,
|
||||
A9FB3C73306BB5EC000B756D /* MP42TextRecognizer.h in Headers */,
|
||||
A9422FC81D4917AF000DB435 /* audio_resample.h in Headers */,
|
||||
A9FB3C7B306BB692000B756D /* MP42VisionOCR.h in Headers */,
|
||||
A9195F372233DD38005C4D01 /* MP42RelatedItem.h in Headers */,
|
||||
A917286719FD2BCE00348DF8 /* MP42Logging.h in Headers */,
|
||||
A941C95F1F82A9B900FC5E8D /* MP42SSAConverter.h in Headers */,
|
||||
@@ -804,6 +879,7 @@
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A9FB3C75306BB5EC000B756D /* MP42TextRecognizer.h in Headers */,
|
||||
6661A2EE20890B4400B1A669 /* MP42Foundation.h in Headers */,
|
||||
A917286619FD2BCE00348DF8 /* MP42Logging.h in Headers */,
|
||||
A9B9C27D1823923200416A4E /* MP42FileImporter.h in Headers */,
|
||||
@@ -833,7 +909,7 @@
|
||||
A941A7B41DA7B08600FB2A7C /* MP42MetadataFormat.h in Headers */,
|
||||
A99FCBC41BAD65EF0058E27A /* MP42Track+Private.h in Headers */,
|
||||
A925AAAF18379AF800BE84D4 /* MP42Utilities.h in Headers */,
|
||||
A9B9C28F1823923200416A4E /* MP42OCRWrapper.h in Headers */,
|
||||
A9B9C28F1823923200416A4E /* MP42TesseractOCR.h in Headers */,
|
||||
A941C9561F82996600FC5E8D /* MP42TextSubConverter.h in Headers */,
|
||||
A9B9C2811823923200416A4E /* MP42HtmlParser.h in Headers */,
|
||||
A9B9C2AA1823923200416A4E /* MatroskaParser.h in Headers */,
|
||||
@@ -850,10 +926,12 @@
|
||||
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 */,
|
||||
A9B9C27F1823923200416A4E /* MP42H264Importer.h in Headers */,
|
||||
A9FB3C79306BB692000B756D /* MP42VisionOCR.h in Headers */,
|
||||
A9B9C29D1823923200416A4E /* MP42PrivateUtilities.h in Headers */,
|
||||
A90801111D4B83A3002B6950 /* MP42AudioDecoder.h in Headers */,
|
||||
A9ED5B0D1F824A9B00E0E4FA /* MP42SSAParser.h in Headers */,
|
||||
@@ -867,6 +945,10 @@
|
||||
A9422FC71D4917AF000DB435 /* audio_resample.h in Headers */,
|
||||
A9B9C2AC1823923200416A4E /* mbs.h in Headers */,
|
||||
A9B9C2891823923200416A4E /* MP42MkvImporter.h in Headers */,
|
||||
5AB1E120261124000000000007 /* MP42Ebml.h in Headers */,
|
||||
5AB1E120261124000000000010 /* MP42MatroskaTagMapping.h in Headers */,
|
||||
5AB1E120261124000000000013 /* MP42MkvTagWriter.h in Headers */,
|
||||
5AB1E120261124000000000024 /* MP42MkvRemuxer.h in Headers */,
|
||||
A96D28931BAD390400403327 /* MP42Metadata+Private.h in Headers */,
|
||||
A97EA7C71D4B8A2D00257CEA /* FFmpegUtils.h in Headers */,
|
||||
);
|
||||
@@ -920,7 +1002,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
CLASSPREFIX = MP42;
|
||||
LastUpgradeCheck = 2700;
|
||||
LastUpgradeCheck = 2720;
|
||||
ORGANIZATIONNAME = "Damiano Galassi";
|
||||
TargetAttributes = {
|
||||
A910B5A218394E900064028F = {
|
||||
@@ -983,6 +1065,7 @@
|
||||
files = (
|
||||
A951C190233F4CA300D63AF8 /* MP42AC3AudioEncoder.m in Sources */,
|
||||
A9A268E2196D6367003AFF57 /* MP42EditListsReconstructor.m in Sources */,
|
||||
A9FB3C7A306BB692000B756D /* MP42VisionOCR.m in Sources */,
|
||||
A91711E9187D547D00459495 /* MP42PreviewGenerator.m in Sources */,
|
||||
A90801181D4B83A3002B6950 /* MP42AudioEncoder.m in Sources */,
|
||||
A910B5C618394EB20064028F /* MP42File.m in Sources */,
|
||||
@@ -1001,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 */,
|
||||
@@ -1015,8 +1102,9 @@
|
||||
A96523491BAC315900E994E0 /* NSString+MP42Additions.m in Sources */,
|
||||
A910B5F918394EB20064028F /* MP42FileImporter.m in Sources */,
|
||||
A910B5FA18394EB20064028F /* sfifo.c in Sources */,
|
||||
A910B5FD18394EB20064028F /* MP42OCRWrapper.mm 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 */,
|
||||
@@ -1025,6 +1113,10 @@
|
||||
A9ED5B141F824BC100E0E4FA /* MP42SSAImporter.m in Sources */,
|
||||
A91C3ACF1BF20CF1008BCF87 /* MP42FormatUtilites.mm in Sources */,
|
||||
A910B60718394EB20064028F /* MP42MkvImporter.m in Sources */,
|
||||
5AB1E120261124000000000008 /* MP42Ebml.m in Sources */,
|
||||
5AB1E120261124000000000011 /* MP42MatroskaTagMapping.m in Sources */,
|
||||
5AB1E120261124000000000014 /* MP42MkvTagWriter.m in Sources */,
|
||||
5AB1E120261124000000000025 /* MP42MkvRemuxer.m in Sources */,
|
||||
A9D764321E278B8100ED2F78 /* MP42MetadataUtilities.m in Sources */,
|
||||
A910B60918394EB20064028F /* MP42Mp4Importer.m in Sources */,
|
||||
A910B60D18394EB20064028F /* MP42SrtImporter.m in Sources */,
|
||||
@@ -1050,6 +1142,7 @@
|
||||
files = (
|
||||
A91711E8187D547D00459495 /* MP42PreviewGenerator.m in Sources */,
|
||||
A9B9C27C1823923200416A4E /* MP42File.m in Sources */,
|
||||
A9FB3C78306BB692000B756D /* MP42VisionOCR.m in Sources */,
|
||||
A9B9C29C1823923200416A4E /* MP42Track.m in Sources */,
|
||||
A9B9C2A01823923200416A4E /* MP42VideoTrack.m in Sources */,
|
||||
A930D8EA22351E2F0061CF37 /* MP42SecurityAccessToken.m in Sources */,
|
||||
@@ -1068,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 */,
|
||||
@@ -1081,6 +1179,10 @@
|
||||
7538B2052505AB1800898792 /* SampleCursor.swift in Sources */,
|
||||
A9B9C28C1823923200416A4E /* MP42Mp4Importer.m in Sources */,
|
||||
A9B9C28A1823923200416A4E /* MP42MkvImporter.m in Sources */,
|
||||
5AB1E120261124000000000009 /* MP42Ebml.m in Sources */,
|
||||
5AB1E120261124000000000012 /* MP42MatroskaTagMapping.m in Sources */,
|
||||
5AB1E120261124000000000015 /* MP42MkvTagWriter.m in Sources */,
|
||||
5AB1E120261124000000000026 /* MP42MkvRemuxer.m in Sources */,
|
||||
A9B9C2731823923200416A4E /* MP42CCImporter.m in Sources */,
|
||||
A9B9C2801823923200416A4E /* MP42H264Importer.mm in Sources */,
|
||||
A9B9C2771823923200416A4E /* MP42ClosedCaptionTrack.m in Sources */,
|
||||
@@ -1099,7 +1201,7 @@
|
||||
A97EA7C91D4B8A2D00257CEA /* FFmpegUtils.m in Sources */,
|
||||
A91C3ACE1BF20CF1008BCF87 /* MP42FormatUtilites.mm in Sources */,
|
||||
A9B9C26D1823923200416A4E /* MP42AudioTrack.m in Sources */,
|
||||
A9B9C2901823923200416A4E /* MP42OCRWrapper.mm in Sources */,
|
||||
A9B9C2901823923200416A4E /* MP42TesseractOCR.mm in Sources */,
|
||||
A9B9C2881823923200416A4E /* MP42Metadata.m in Sources */,
|
||||
A9B9C2941823923200416A4E /* MP42SampleBuffer.m in Sources */,
|
||||
A925AAB018379AF800BE84D4 /* MP42Utilities.m in Sources */,
|
||||
@@ -1171,6 +1273,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
"@loader_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
OTHER_LDFLAGS = (
|
||||
"-read_only_relocs",
|
||||
suppress,
|
||||
@@ -1201,6 +1304,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
"@loader_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = "$(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET)";
|
||||
OTHER_LDFLAGS = (
|
||||
"-read_only_relocs",
|
||||
suppress,
|
||||
@@ -1296,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;
|
||||
@@ -1391,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";
|
||||
@@ -1427,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;
|
||||
@@ -1459,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"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# build artifact (see Makefile)
|
||||
/sup2vob
|
||||
@@ -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)
|
||||
@@ -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)!)
|
||||
Reference in new issue
Block a user