diff --git a/MP42/MP42Ebml.h b/MP42/MP42Ebml.h new file mode 100644 index 0000000..e40ae53 --- /dev/null +++ b/MP42/MP42Ebml.h @@ -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 + +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 *)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 *)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 diff --git a/MP42/MP42Ebml.m b/MP42/MP42Ebml.m new file mode 100644 index 0000000..265e8d2 --- /dev/null +++ b/MP42/MP42Ebml.m @@ -0,0 +1,515 @@ +// +// MP42Ebml.m +// MP42Foundation +// + +#import "MP42Ebml.h" + +#include +#include +#include + +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 *)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 *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 *)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 *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 diff --git a/MP42/MP42FileImporter.h b/MP42/MP42FileImporter.h index eed51d5..77c422a 100644 --- a/MP42/MP42FileImporter.h +++ b/MP42/MP42FileImporter.h @@ -25,11 +25,22 @@ NS_ASSUME_NONNULL_BEGIN + (NSArray *)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 *)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 *tracks; diff --git a/MP42/MP42FileImporter.m b/MP42/MP42FileImporter.m index cafce31..a93fee6 100644 --- a/MP42/MP42FileImporter.m +++ b/MP42/MP42FileImporter.m @@ -98,6 +98,11 @@ static NSArray *_supportedContentTypes API_AVAILABLE(macos(11.0)); return [[self supportedFileFormats] containsObject:fileType.lowercaseString]; } ++ (BOOL)isMatroskaFileType:(NSString *)fileType +{ + return [[MP42MkvImporter supportedFileFormats] containsObject:fileType.lowercaseString]; +} + + (NSArray *)supportedContentTypes { return _supportedContentTypes; @@ -116,13 +121,27 @@ static NSArray *_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; diff --git a/MP42/MP42Foundation.h b/MP42/MP42Foundation.h index 8bc23a4..b62cfca 100644 --- a/MP42/MP42Foundation.h +++ b/MP42/MP42Foundation.h @@ -32,4 +32,9 @@ #import #import +#import +#import +#import +#import + #endif /* MP42Foundation_h */ diff --git a/MP42/MP42MatroskaTagMapping.h b/MP42/MP42MatroskaTagMapping.h new file mode 100644 index 0000000..dd9d942 --- /dev/null +++ b/MP42/MP42MatroskaTagMapping.h @@ -0,0 +1,138 @@ +// +// 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 + +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 + 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) + + 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 *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 *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 diff --git a/MP42/MP42MatroskaTagMapping.m b/MP42/MP42MatroskaTagMapping.m new file mode 100644 index 0000000..3af33be --- /dev/null +++ b/MP42/MP42MatroskaTagMapping.m @@ -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 *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 *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 *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 *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 *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 *MP42MkvPersistedMetadataKeys(void) +{ + static NSSet *keys; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSMutableSet *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 *MP42MkvWritePairsForTargetLevel(NSInteger level) +{ + static NSMutableDictionary *> *cache; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + cache = [NSMutableDictionary dictionary]; + }); + + NSNumber *levelKey = @(level); + @synchronized (cache) { + NSArray *pairs = cache[levelKey]; + if (pairs) { + return pairs; + } + + NSDictionary *readMap = MP42MkvSimpleTagMapForTargetLevel(level); + NSMutableArray *result = [NSMutableArray array]; + NSMutableSet *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; + } +} diff --git a/MP42/MP42MkvImporter.m b/MP42/MP42MkvImporter.m index b1cd5b0..4d0b66d 100644 --- a/MP42/MP42MkvImporter.m +++ b/MP42/MP42MkvImporter.m @@ -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) { @@ -343,7 +358,7 @@ MP42_OBJC_DIRECT_MEMBERS [self addTrack:newTrack]; } - [self.metadata mergeMetadata:[self readMatroskaMetadata] overwrite:true]; + [self.metadata mergeMetadata:[self readMatroskaMetadataTagsOnly:tagsOnly] overwrite:true]; } return self; @@ -356,24 +371,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 +400,8 @@ MP42_OBJC_DIRECT_MEMBERS metadata:metadata]; } - NSDictionary *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 *collectionMap = @{ - @"TITLE": MP42MetadataKeyTVShow, - @"COPYRIGHT": MP42MetadataKeyCopyright, - @"DESCRIPTION": MP42MetadataKeySeriesDescription, - @"SYNOPSIS": MP42MetadataKeySeriesDescription, - }; - - NSDictionary *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 +414,8 @@ MP42_OBJC_DIRECT_MEMBERS for (unsigned int xi = 0; xi < count; xi++) { Tag *tags = &tag_groups[xi]; - ulonglong UID = 0; - NSDictionary *map = simpleMap; + NSInteger level = MP42MkvTargetGlobal; + NSDictionary *map = nil; if (tags->nTargetsSize) { struct Target *target = &tags->Targets[0]; @@ -458,21 +424,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 +440,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 +478,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]; + } } } diff --git a/MP42/MP42MkvRemuxer.h b/MP42/MP42MkvRemuxer.h new file mode 100644 index 0000000..a137adc --- /dev/null +++ b/MP42/MP42MkvRemuxer.h @@ -0,0 +1,74 @@ +// +// 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, 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). +// +// Guarantees / edges: +// - Blocks, CodecPrivate data, Chapters and Info (including Duration) +// are copied byte-for-byte; a Duration may overstate the longest +// dropped track, which players tolerate. +// - 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, +// and remuxes that would leave zero tracks. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class MP42Metadata; +@class MP42Track; + +@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); + +- (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 deletions; entries whose paired sourceTracks +// object is no longer present (compared by object identity) are removed. +// +// 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 *)sourceTracks + currentTracks:(NSArray *)currentTracks + error:(NSError * _Nullable *)outError; + +- (void)cancel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/MP42/MP42MkvRemuxer.m b/MP42/MP42MkvRemuxer.m new file mode 100644 index 0000000..9ae619c --- /dev/null +++ b/MP42/MP42MkvRemuxer.m @@ -0,0 +1,962 @@ +// +// MP42MkvRemuxer.m +// MP42Foundation +// + +#import "MP42MkvRemuxer.h" + +#import "MP42MkvTagWriter+Internal.h" +#import "MP42MatroskaTagMapping.h" +#import "MP42Metadata.h" +#import "MP42Track.h" +#import "MP42ChapterTrack.h" + +#include +#include +#include +#include + +// BlockGroups put their Block first; a small peek is enough to find the +// track number that decides keep/drop for the whole group. +static const uint64_t kBlockGroupPeekSize = 64 * 1024; + +static NSError *RemuxError(MP42MkvError code, NSString *format, ...) +{ + va_list args; + va_start(args, format); + NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; + va_end(args); + return [MP42Ebml errorWithCode:code message:@"%@", message]; +} + +// Subdata of a whole element (header + payload) within a scanned buffer. +static NSData *RemuxBufferSlice(NSData *buffer, MP42EbmlElement *el, uint64_t regionEnd) +{ + uint64_t end = [MP42Ebml payloadEndForElement:el regionEnd:regionEnd]; + return [buffer subdataWithRange:NSMakeRange((NSUInteger)el.start, (NSUInteger)(end - el.start))]; +} + +// Big-endian payload for an unsigned-integer element, minimal width unless +// a wider one is requested (SeekHead positions stay 8 bytes so the element +// size never changes when they are patched). +static NSData *MkvUIntData(uint64_t value, NSUInteger minWidth) +{ + NSUInteger width = 1; + while (width < 8 && value >= ((uint64_t)1 << (8 * width))) { + width++; + } + width = MAX(width, minWidth); + + NSMutableData *data = [NSMutableData dataWithLength:width]; + uint8_t *bytes = data.mutableBytes; + for (NSUInteger i = 0; i < width; i++) { + bytes[width - 1 - i] = (uint8_t)(value & 0xFF); + value >>= 8; + } + return data; +} + +// Signed integer payload in minimal two's-complement big-endian width +// (CueRelativePosition). Zero encodes as the single byte 0x00. +static NSData *MkvSIntData(int64_t value) +{ + NSUInteger width = 1; + while (width < 8) { + int64_t lo = -(INT64_C(1) << (8 * width - 1)); + int64_t hi = (INT64_C(1) << (8 * width - 1)) - 1; + if (value >= lo && value <= hi) { + break; + } + width++; + } + + NSMutableData *data = [NSMutableData dataWithLength:width]; + uint8_t *bytes = data.mutableBytes; + for (NSUInteger i = 0; i < width; i++) { + bytes[width - 1 - i] = (uint8_t)((value >> (8 * (width - 1 - i))) & 0xFF); + } + return data; +} + +static NSUInteger MkvIdWidth(uint32_t identifier) +{ + if (identifier >= 0x10000000u) return 4; + if (identifier >= 0x200000u) return 3; + if (identifier >= 0x4000u) return 2; + return 1; +} + +@interface MP42MkvRemuxer () { + NSURL *_sourceURL; + volatile BOOL _cancelled; +} +// Set while a remux runs so -cancel can abort the shared I/O helpers too. +@property (nonatomic, strong, nullable) MP42MkvTagWriter *activeHelper; +@end + +@implementation MP42MkvRemuxer + +- (instancetype)initWithSourceURL:(NSURL *)sourceURL +{ + self = [super init]; + if (self) { + _sourceURL = [sourceURL copy]; + } + return self; +} + +- (NSURL *)sourceURL +{ + return _sourceURL; +} + +- (void)cancel +{ + _cancelled = YES; + [self.activeHelper cancel]; +} + +- (BOOL)checkCancelledWithError:(NSError **)outError +{ + if (_cancelled) { + if (outError) { + *outError = RemuxError(MP42MkvErrorCancelled, @"cancelled"); + } + return NO; + } + return YES; +} + +#pragma mark - Entry point + +- (BOOL)remuxToURL:(NSURL *)destURL + metadata:(MP42Metadata *)metadata + sourceTracks:(NSArray *)sourceTracks + currentTracks:(NSArray *)currentTracks + error:(NSError **)outError +{ + _cancelled = NO; + + NSString *tempPath = nil; + NSError *innerError = nil; + BOOL ok = [self remuxToTempPath:&tempPath + dest:destURL + metadata:metadata + sourceTracks:sourceTracks + currentTracks:currentTracks + error:&innerError]; + if (ok) { + // Temp lives in the destination directory, so the rename is atomic. + if (rename([tempPath fileSystemRepresentation], + [destURL.path fileSystemRepresentation]) != 0) { + ok = NO; + innerError = RemuxError(MP42MkvErrorWriteFailed, @"Could not install %@ (%d)", + destURL.lastPathComponent, errno); + } + } + if (!ok && tempPath) { + unlink([tempPath fileSystemRepresentation]); + } + if (!ok && outError) { + *outError = innerError; + } + return ok; +} + +- (BOOL)remuxToTempPath:(NSString **)outTempPath + dest:(NSURL *)destURL + metadata:(MP42Metadata *)metadata + sourceTracks:(NSArray *)sourceTracks + currentTracks:(NSArray *)currentTracks + error:(NSError **)outError +{ + NSURL *destDir = destURL.URLByDeletingLastPathComponent; + NSString *tempPath = [destDir.path stringByAppendingPathComponent: + [NSString stringWithFormat:@".subler-remux-%@.tmp", [[NSUUID UUID] UUIDString]]]; + int outFd = open([tempPath fileSystemRepresentation], O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (outFd < 0) { + if (outError) { + *outError = RemuxError(MP42MkvErrorWriteFailed, @"Could not create %@ (%d)", + tempPath.lastPathComponent, errno); + } + return NO; + } + *outTempPath = tempPath; + + BOOL ok = [self remuxToFD:outFd + dest:destURL + metadata:metadata + sourceTracks:sourceTracks + currentTracks:currentTracks + error:outError]; + + // Match the source file's permission bits for the replaced file. + if (ok) { + struct stat st; + if (stat(_sourceURL.fileSystemRepresentation, &st) == 0) { + fchmod(outFd, st.st_mode & 07777); + } + if (fsync(outFd) != 0) { + ok = NO; + if (outError) { + *outError = RemuxError(MP42MkvErrorWriteFailed, @"Sync error (%d)", errno); + } + } + } + close(outFd); + return ok; +} + +#pragma mark - Track pairing / payload building + +// Filtered copy without the chapter pseudo-track (not a Matroska track). +static NSArray *RealTracksFromArray(NSArray *tracks) +{ + NSMutableArray *out = [NSMutableArray array]; + for (MP42Track *track in tracks) { + if (![track isMemberOfClass:MP42ChapterTrack.class]) { + [out addObject:track]; + } + } + return out; +} + +// TrackNumber of a TrackEntry's payload; entries without one cannot be +// dropped (their blocks would be unidentifiable). +- (BOOL)trackNumberForEntry:(MP42EbmlElement *)entry + buffer:(NSData *)buffer + regionEnd:(uint64_t)regionEnd + value:(uint32_t *)outValue + error:(NSError **)outError +{ + NSArray *kids = [MP42Ebml scanBuffer:buffer + from:entry.dataStart + length:entry.dataSize + error:outError]; + if (!kids) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"A track in %@ could not be parsed", _sourceURL.lastPathComponent); + return NO; + } + for (MP42EbmlElement *kid in kids) { + if (kid.identifier == MP42MkvElementTrackNumber && !kid.sizeIsUnknown && kid.dataSize > 0) { + NSData *data = [buffer subdataWithRange:NSMakeRange((NSUInteger)kid.dataStart, + (NSUInteger)kid.dataSize)]; + uint64_t value = [MP42Ebml unsignedIntValueAt:data.bytes length:data.length]; + if (value > 0 && value <= 255) { + *outValue = (uint32_t)value; + return YES; + } + } + } + *outError = RemuxError(MP42MkvErrorUnsupported, + @"A removed track in %@ has no usable TrackNumber, so its data could not be located", + _sourceURL.lastPathComponent); + return NO; +} + +// Builds the new Tracks payload: kept entries run through the tag writer's +// field-diff edit (so name/language/enabled/forced edits ride along), +// dropped entries disappear. Collects the dropped TrackNumbers and an +// approximate dropped-payload size for the progress estimate. +- (BOOL)buildRemuxedTracksPayloadForFile:(MP42MkvFile *)file + sourceTracks:(NSArray *)realSource + currentTracks:(NSArray *)currentReal + helper:(MP42MkvTagWriter *)helper + payload:(NSData **)outPayload + droppedNumbers:(NSMutableSet *)droppedNumbers + droppedBytes:(uint64_t *)outDroppedBytes + error:(NSError **)outError +{ + NSData *buf = file.tracks.payload; + uint64_t regionEnd = buf.length; + NSArray *kids = [MP42Ebml scanBuffer:buf from:0 length:regionEnd error:outError]; + if (!kids) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"The tracks in %@ could not be parsed", _sourceURL.lastPathComponent); + return NO; + } + + NSUInteger entryCount = 0; + for (MP42EbmlElement *kid in kids) { + if (kid.identifier == MP42MkvElementTrackEntry) { + entryCount++; + } + } + if (entryCount != realSource.count) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"%@ contains %lu tracks but the document started with %lu; revert the document before saving", + _sourceURL.lastPathComponent, (unsigned long)entryCount, (unsigned long)realSource.count); + return NO; + } + for (MP42Track *track in currentReal) { + if ([realSource indexOfObjectIdenticalTo:track] == NSNotFound) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"The document contains a track that is not stored in %@; only removal is supported", + _sourceURL.lastPathComponent); + return NO; + } + } + + NSMutableData *out = [NSMutableData data]; + NSUInteger modelIndex = 0; + NSUInteger droppedCount = 0; + uint64_t droppedBytes = 0; + + for (MP42EbmlElement *kid in kids) { + BOOL isEntry = (kid.identifier == MP42MkvElementTrackEntry); + if (!isEntry) { + [out appendData:RemuxBufferSlice(buf, kid, regionEnd)]; + continue; + } + + MP42Track *src = modelIndex < realSource.count ? realSource[modelIndex] : nil; + modelIndex++; + BOOL drop = src != nil && [currentReal indexOfObjectIdenticalTo:src] == NSNotFound; + + if (!drop) { + if (kid.sizeIsUnknown || !src) { + [out appendData:RemuxBufferSlice(buf, kid, regionEnd)]; + continue; + } + NSData *edited = [helper editTrackEntry:kid buffer:buf regionEnd:regionEnd track:src error:outError]; + if (!edited) { + return NO; + } + [out appendData:edited]; + } else { + if (kid.sizeIsUnknown) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"A removed track in %@ has an unknown-size element we cannot rewrite", + _sourceURL.lastPathComponent); + return NO; + } + uint32_t number = 0; + if (![self trackNumberForEntry:kid buffer:buf regionEnd:regionEnd value:&number error:outError]) { + return NO; + } + [droppedNumbers addObject:@(number)]; + droppedCount++; + droppedBytes += src.dataLength; + } + } + + if (droppedCount == realSource.count) { + *outError = RemuxError(MP42MkvErrorUnsupported, @"At least one track must remain in %@", + _sourceURL.lastPathComponent); + return NO; + } + + *outPayload = out; + *outDroppedBytes = droppedBytes; + return YES; +} + +#pragma mark - Block helpers + +// Track number carried by a SimpleBlock/Block payload, plus the block's +// signed 16-bit timecode relative to its cluster (outRelTC may be NULL). +- (BOOL)trackNumberAtBlockPayload:(uint64_t)payloadStart + limit:(uint64_t)limitEnd + scanner:(MP42EbmlScanner *)scanner + value:(uint32_t *)outValue + timecode:(int16_t *)outRelTC + error:(NSError **)outError +{ + NSUInteger avail = (NSUInteger)MIN((uint64_t)16, limitEnd - payloadStart); + if (avail == 0) { + *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ is truncated", + _sourceURL.lastPathComponent); + return NO; + } + NSData *head = [scanner readAtOffset:payloadStart length:avail error:outError]; + if (!head) { + return NO; + } + uint32_t value = 0; + NSUInteger consumed = [MP42Ebml blockTrackNumberAt:head.bytes available:head.length value:&value]; + if (consumed == 0 || value == 0 || value > 255) { + *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ has an invalid track number", + _sourceURL.lastPathComponent); + return NO; + } + int16_t relTC = 0; + if (outRelTC) { + if (consumed + 2 > head.length) { + *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ is truncated", + _sourceURL.lastPathComponent); + return NO; + } + const uint8_t *tc = (const uint8_t *)head.bytes + consumed; + relTC = (int16_t)((tc[0] << 8) | tc[1]); + } + *outValue = value; + if (outRelTC) { + *outRelTC = relTC; + } + return YES; +} + +// Track number of a BlockGroup, taken from its Block child (BlockAdditions +// belong to that block's track, so deciding on the group is enough). +- (BOOL)trackNumberForBlockGroup:(MP42EbmlElement *)group + scanner:(MP42EbmlScanner *)scanner + value:(uint32_t *)outValue + timecode:(int16_t *)outRelTC + error:(NSError **)outError +{ + uint64_t peek = MIN(group.dataSize, kBlockGroupPeekSize); + NSData *buf = [scanner readAtOffset:group.dataStart length:peek error:outError]; + if (!buf) { + return NO; + } + NSArray *kids = [MP42Ebml scanBuffer:buf from:0 length:buf.length error:outError]; + if (!kids) { + *outError = RemuxError(MP42MkvErrorParse, @"A block group in %@ could not be parsed", + _sourceURL.lastPathComponent); + return NO; + } + for (MP42EbmlElement *kid in kids) { + if (kid.identifier == MP42MkvElementBlock) { + return [self trackNumberAtBlockPayload:group.dataStart + kid.dataStart + limit:group.dataStart + group.dataSize + scanner:scanner + value:outValue + timecode:outRelTC + error:outError]; + } + } + *outError = RemuxError(MP42MkvErrorUnsupported, @"A block group in %@ has no Block element", + _sourceURL.lastPathComponent); + return NO; +} + +#pragma mark - Cluster rewriting + +// Writes one filtered cluster (or skips it entirely when every block +// belonged to removed tracks). Appends a cue point for written clusters +// when the source had Cues. +- (BOOL)remuxClusterKid:(MP42MkvKid *)kid + scanner:(MP42EbmlScanner *)scanner + helper:(MP42MkvTagWriter *)helper + fd:(int)fd + cursor:(uint64_t *)cursor + segDataStart:(uint64_t)segDataStartAbs + dataEnd:(uint64_t)dataEnd + droppedNumbers:(NSSet *)droppedNumbers + wantCues:(BOOL)wantCues + cuesPayload:(NSMutableData *)cuesPayload + totalEstimate:(uint64_t)totalEstimate + error:(NSError **)outError +{ + if (![self checkCancelledWithError:outError]) { + return NO; + } + + uint64_t payloadStart = kid.el.dataStart; + // An unknown-size cluster (only ever the last child) runs to the end of + // the segment data — EOF for unknown-size segments, else the old segment + // end (trailing padding is dropped with the rebuild). + uint64_t payloadEnd = kid.el.sizeIsUnknown ? dataEnd : kid.el.end; + + NSArray *kids = [scanner scanChildrenFrom:payloadStart + length:payloadEnd - payloadStart + error:outError]; + if (!kids) { + return NO; + } + + NSMutableArray *kept = [NSMutableArray array]; + uint64_t keptTotal = 0; + BOOL hadBlock = NO, keptBlock = NO; + uint64_t timecode = 0; + BOOL hasTimecode = NO; + // First surviving block element per track (+ its block timecode): the + // cue point references land on these once their output position is known. + NSMutableDictionary *firstBlockByTrack = [NSMutableDictionary dictionary]; + NSMutableDictionary *blockRelTCByTrack = [NSMutableDictionary dictionary]; + + for (MP42EbmlElement *child in kids) { + if (child.sizeIsUnknown) { + *outError = RemuxError(MP42MkvErrorUnsupported, + @"A cluster in %@ contains an unknown-size element we cannot rewrite", + _sourceURL.lastPathComponent); + return NO; + } + + switch (child.identifier) { + case MP42MkvElementVoid: + break; // padding: dropped + + case MP42MkvElementClusterTimeCode: { + NSData *data = [scanner readAtOffset:child.dataStart length:child.dataSize error:outError]; + if (!data) { + return NO; + } + timecode = [MP42Ebml unsignedIntValueAt:data.bytes length:data.length]; + hasTimecode = YES; + [kept addObject:child]; + keptTotal += child.totalSize; + break; + } + + case MP42MkvElementSimpleBlock: { + hadBlock = YES; + uint32_t number = 0; + int16_t relTC = 0; + if (![self trackNumberAtBlockPayload:child.dataStart + limit:payloadEnd + scanner:scanner + value:&number + timecode:&relTC + error:outError]) { + return NO; + } + if ([droppedNumbers containsObject:@(number)]) { + break; // dropped + } + keptBlock = YES; + if (!firstBlockByTrack[@(number)]) { + firstBlockByTrack[@(number)] = child; + blockRelTCByTrack[@(number)] = @(relTC); + } + [kept addObject:child]; + keptTotal += child.totalSize; + break; + } + + case MP42MkvElementBlockGroup: { + hadBlock = YES; + uint32_t number = 0; + int16_t relTC = 0; + if (![self trackNumberForBlockGroup:child scanner:scanner value:&number timecode:&relTC error:outError]) { + return NO; + } + if ([droppedNumbers containsObject:@(number)]) { + break; // dropped (BlockAdditions of this group go with it) + } + keptBlock = YES; + if (!firstBlockByTrack[@(number)]) { + firstBlockByTrack[@(number)] = child; + blockRelTCByTrack[@(number)] = @(relTC); + } + [kept addObject:child]; + keptTotal += child.totalSize; + break; + } + + default: + // Position, PrevSize, PrevDuration, unknown children: verbatim. + [kept addObject:child]; + keptTotal += child.totalSize; + break; + } + } + + if (!hadBlock) { + // Nothing block-like: copy the raw region (keeps the unknown-size + // trailing form intact for a final blockless cluster). + return [helper copyFromScanner:scanner + source:kid.el.start + length:payloadEnd - kid.el.start + toFD:fd + outOffset:cursor + totalEstimate:totalEstimate + error:outError]; + } + if (!keptBlock) { + return YES; // cluster emptied by the removal: skip it whole + } + + uint64_t clusterRel = *cursor - segDataStartAbs; + + NSMutableData *header = [NSMutableData data]; + [MP42Ebml appendId:MP42MkvElementCluster to:header]; + [MP42Ebml appendSize:keptTotal to:header]; // materializes an unknown-size header + if (![helper appendData:header toFD:fd outOffset:cursor error:outError]) { + return NO; + } + + NSMutableDictionary *firstOutRelByTrack = [NSMutableDictionary dictionary]; + for (MP42EbmlElement *child in kept) { + uint64_t outPos = *cursor; + for (NSNumber *num in firstBlockByTrack) { + if (firstBlockByTrack[num] == child) { + firstOutRelByTrack[num] = @(outPos - segDataStartAbs); + } + } + if (![helper copyFromScanner:scanner + source:child.start + length:child.totalSize + toFD:fd + outOffset:cursor + totalEstimate:totalEstimate + error:outError]) { + return NO; + } + } + + // One CuePoint per written cluster, with a CueTrackPositions for every + // surviving track present in it — same shape libebml/mkvmerge emit, so + // readers see the same index entries they saw before the removal. + if (wantCues && hasTimecode) { + NSMutableData *point = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementCueTime payload:MkvUIntData(timecode, 1) to:point]; + NSArray *numbers = [firstOutRelByTrack.allKeys sortedArrayUsingSelector:@selector(compare:)]; + for (NSNumber *num in numbers) { + NSMutableData *trackPositions = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementCueTrack payload:MkvUIntData(num.unsignedLongLongValue, 1) to:trackPositions]; + [MP42Ebml appendElement:MP42MkvElementCueClusterPosition payload:MkvUIntData(clusterRel, 1) to:trackPositions]; + int64_t relative = (int64_t)firstOutRelByTrack[num].longLongValue - (int64_t)clusterRel; + if (relative != 0) { + [MP42Ebml appendElement:MP42MkvElementCueRelativePosition payload:MkvSIntData(relative) to:trackPositions]; + } + [MP42Ebml appendElement:MP42MkvElementCueTrackPositions payload:trackPositions to:point]; + } + [MP42Ebml appendElement:MP42MkvElementCuePoint payload:point to:cuesPayload]; + } + return YES; +} + +#pragma mark - SeekHead + +// A Seek entry whose SeekPosition payload is a fixed-width placeholder; +// records where that payload sits relative to the SeekHead payload start +// so it can be pwrite-patched once final positions are known. +static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload, + uint32_t targetID, + NSUInteger *outPatchRel) +{ + NSMutableData *idBytes = [NSMutableData data]; + [MP42Ebml appendId:targetID to:idBytes]; + + NSMutableData *seekPayload = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementSeekID payload:idBytes to:seekPayload]; + NSUInteger positionPayloadOffset = seekPayload.length + MkvIdWidth(MP42MkvElementSeekPosition) + + [MP42Ebml encodedLengthForSizeValue:8]; + [MP42Ebml appendElement:MP42MkvElementSeekPosition payload:MkvUIntData(0, 8) to:seekPayload]; + + NSUInteger seekElementOffset = seekHeadPayload.length; + [MP42Ebml appendElement:MP42MkvElementSeek payload:seekPayload to:seekHeadPayload]; + + if (outPatchRel) { + NSUInteger seekHeaderSize = MkvIdWidth(MP42MkvElementSeek) + + [MP42Ebml encodedLengthForSizeValue:seekPayload.length]; + *outPatchRel = seekElementOffset + seekHeaderSize + positionPayloadOffset; + } +} + +#pragma mark - Main remux + +- (BOOL)remuxToFD:(int)outFd + dest:(NSURL *)destURL + metadata:(MP42Metadata *)metadata + sourceTracks:(NSArray *)sourceTracks + currentTracks:(NSArray *)currentTracks + error:(NSError **)outError +{ + MP42MkvTagWriter *helper = [[MP42MkvTagWriter alloc] initWithURL:_sourceURL]; + helper.expectedFileSize = self.expectedFileSize; + helper.expectedModificationDate = self.expectedModificationDate; + helper.progressHandler = self.progressHandler; + self.activeHelper = helper; + + MP42EbmlScanner *scanner = [MP42EbmlScanner scannerWithURL:_sourceURL error:outError]; + if (!scanner) { + self.activeHelper = nil; + return NO; + } + + BOOL ok = NO; + do { + if (![helper checkStalenessWithError:outError]) { + break; + } + MP42MkvFile *file = [helper scanFile:scanner error:outError]; + if (!file || !file.tracks) { + if (file && outError) { + *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ has no Tracks element", + _sourceURL.lastPathComponent); + } + break; + } + + NSArray *realSource = RealTracksFromArray(sourceTracks); + NSArray *currentReal = RealTracksFromArray(currentTracks); + + NSMutableSet *droppedNumbers = [NSMutableSet set]; + uint64_t droppedBytes = 0; + NSData *newTracks = nil; + if (![self buildRemuxedTracksPayloadForFile:file + sourceTracks:realSource + currentTracks:currentReal + helper:helper + payload:&newTracks + droppedNumbers:droppedNumbers + droppedBytes:&droppedBytes + error:outError]) { + break; + } + + NSData *newTags = [helper buildTagsPayloadForMetadata:metadata file:file error:outError]; + if (!newTags) { + break; + } + BOOL tagsShouldExist = newTags.length > 0; + + NSData *newAtt = nil; + BOOL attChanged = NO, attShouldExist = NO; + if (![helper buildAttachmentsPayloadForMetadata:metadata + file:file + payload:&newAtt + changed:&attChanged + shouldExist:&attShouldExist + error:outError]) { + break; + } + BOOL writeAttPayload = attShouldExist && attChanged && newAtt != nil; + + BOOL wantCues = file.cues.count > 0; + + // Locate the verbatim-carry top-level elements. + MP42MkvKid *infoKid = nil, *chaptersKid = nil; + NSMutableArray *extras = [NSMutableArray array]; + for (MP42MkvKid *kid in file.kids) { + if (kid.kind != MP42MkvKidKeep) { + continue; + } + uint32_t identifier = kid.el.identifier; + if (identifier == MP42MkvElementSegmentInfo && !infoKid) { + infoKid = kid; + } else if (identifier == MP42MkvElementChapters && !chaptersKid) { + chaptersKid = kid; + } else if (identifier != MP42MkvElementVoid) { + [extras addObject:kid]; + } + } + + // Progress: the output is roughly the input minus the dropped payload. + uint64_t totalEstimate = scanner.fileSize > droppedBytes ? scanner.fileSize - droppedBytes + : scanner.fileSize; + + // ---- SeekHead plan (fixed size, placeholder positions) ---- + NSMutableArray *seekIds = [NSMutableArray array]; + NSMutableArray *seekPatchRels = [NSMutableArray array]; + NSMutableData *seekHeadPayload = [NSMutableData data]; + NSUInteger patchRel = 0; + MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementTracks, &patchRel); + [seekIds addObject:@(MP42MkvElementTracks)]; + [seekPatchRels addObject:@(patchRel)]; + if (chaptersKid) { + MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementChapters, &patchRel); + [seekIds addObject:@(MP42MkvElementChapters)]; + [seekPatchRels addObject:@(patchRel)]; + } + if (attShouldExist) { + MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementAttachments, &patchRel); + [seekIds addObject:@(MP42MkvElementAttachments)]; + [seekPatchRels addObject:@(patchRel)]; + } + if (tagsShouldExist) { + MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementTags, &patchRel); + [seekIds addObject:@(MP42MkvElementTags)]; + [seekPatchRels addObject:@(patchRel)]; + } + if (wantCues) { + MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementCues, &patchRel); + [seekIds addObject:@(MP42MkvElementCues)]; + [seekPatchRels addObject:@(patchRel)]; + } + NSData *seekHeadElement = nil; + { + NSMutableData *data = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementSeekHead payload:seekHeadPayload to:data]; + seekHeadElement = data; + } + NSUInteger seekHeadPayloadRelInElement = MkvIdWidth(MP42MkvElementSeekHead) + + [MP42Ebml encodedLengthForSizeValue:seekHeadPayload.length]; + + // ---- Write ---- + uint64_t cursor = 0; + + // EBML header (and any bytes before the Segment) verbatim. + if (![helper copyFromScanner:scanner + source:0 + length:file.segment.start + toFD:outFd + outOffset:&cursor + totalEstimate:totalEstimate + error:outError]) { + break; + } + + // Segment: unknown size (the stream-copy equivalent of mkvmerge). + NSMutableData *segHeader = [NSMutableData data]; + [MP42Ebml appendId:MP42MkvElementSegment to:segHeader]; + [MP42Ebml appendUnknownSizeOfWidth:8 to:segHeader]; + if (![helper appendData:segHeader toFD:outFd outOffset:&cursor error:outError]) { + break; + } + uint64_t segDataStartAbs = cursor; + + if (![helper appendData:seekHeadElement toFD:outFd outOffset:&cursor error:outError]) { + break; + } + uint64_t seekHeadPayloadAbs = cursor - seekHeadElement.length + seekHeadPayloadRelInElement; + + if (infoKid && + ![helper copyFromScanner:scanner + source:infoKid.el.start + length:infoKid.el.totalSize + toFD:outFd + outOffset:&cursor + totalEstimate:totalEstimate + error:outError]) { + break; + } + BOOL extrasFailed = NO; + for (MP42MkvKid *kid in extras) { + if (![helper copyFromScanner:scanner + source:kid.el.start + length:kid.el.totalSize + toFD:outFd + outOffset:&cursor + totalEstimate:totalEstimate + error:outError]) { + extrasFailed = YES; + break; + } + } + if (extrasFailed) { + break; + } + + NSMutableDictionary *finalRels = [NSMutableDictionary dictionary]; + + // Tracks (new payload). + NSMutableData *tracksElement = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementTracks payload:newTracks to:tracksElement]; + finalRels[@(MP42MkvElementTracks)] = @(cursor - segDataStartAbs); + if (![helper appendData:tracksElement toFD:outFd outOffset:&cursor error:outError]) { + break; + } + + // Chapters verbatim. + if (chaptersKid) { + finalRels[@(MP42MkvElementChapters)] = @(cursor - segDataStartAbs); + if (![helper copyFromScanner:scanner + source:chaptersKid.el.start + length:chaptersKid.el.totalSize + toFD:outFd + outOffset:&cursor + totalEstimate:totalEstimate + error:outError]) { + break; + } + } + + // Clusters, filtered. + uint64_t segmentDataEnd = file.segmentSizeUnknown ? scanner.fileSize + : file.segDataStart + file.segDataLen; + NSMutableData *cuesPayload = [NSMutableData data]; + BOOL clustersFailed = NO; + for (MP42MkvKid *kid in file.kids) { + if (kid.kind != MP42MkvKidCluster) { + continue; + } + if (![self remuxClusterKid:kid + scanner:scanner + helper:helper + fd:outFd + cursor:&cursor + segDataStart:segDataStartAbs + dataEnd:segmentDataEnd + droppedNumbers:droppedNumbers + wantCues:wantCues + cuesPayload:cuesPayload + totalEstimate:totalEstimate + error:outError]) { + clustersFailed = YES; + break; + } + } + if (clustersFailed) { + break; + } + + // Attachments. + if (attShouldExist) { + finalRels[@(MP42MkvElementAttachments)] = @(cursor - segDataStartAbs); + if (writeAttPayload) { + NSMutableData *attElement = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementAttachments payload:newAtt to:attElement]; + if (![helper appendData:attElement toFD:outFd outOffset:&cursor error:outError]) { + break; + } + } else if (![helper copyFromScanner:scanner + source:file.attachments.el.start + length:file.attachments.el.totalSize + toFD:outFd + outOffset:&cursor + totalEstimate:totalEstimate + error:outError]) { + break; + } + } + + // Tags. + if (tagsShouldExist) { + finalRels[@(MP42MkvElementTags)] = @(cursor - segDataStartAbs); + NSMutableData *tagsElement = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementTags payload:newTags to:tagsElement]; + if (![helper appendData:tagsElement toFD:outFd outOffset:&cursor error:outError]) { + break; + } + } + + // Cues at the very end (only when the source had them). + if (wantCues) { + finalRels[@(MP42MkvElementCues)] = @(cursor - segDataStartAbs); + NSMutableData *cuesElement = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementCues payload:cuesPayload to:cuesElement]; + if (![helper appendData:cuesElement toFD:outFd outOffset:&cursor error:outError]) { + break; + } + } + + // Patch the SeekHead placeholders with their final positions. + BOOL patchFailed = NO; + for (NSUInteger i = 0; i < seekIds.count; i++) { + NSNumber *rel = finalRels[seekIds[i]]; + if (!rel) { + continue; + } + uint64_t patchOffset = seekHeadPayloadAbs + seekPatchRels[i].unsignedLongLongValue; + if (![helper writeData:MkvUIntData(rel.unsignedLongLongValue, 8) + fd:outFd + offset:patchOffset + error:outError]) { + patchFailed = YES; + break; + } + } + if (patchFailed) { + if (outError && !*outError) { + *outError = RemuxError(MP42MkvErrorWriteFailed, @"Could not patch the SeekHead of %@", + destURL.lastPathComponent); + } + break; + } + + if (self.progressHandler) { + self.progressHandler(1.0); + } + ok = YES; + } while (0); + + [scanner close]; + self.activeHelper = nil; + return ok; +} + +@end diff --git a/MP42/MP42MkvTagWriter+Internal.h b/MP42/MP42MkvTagWriter+Internal.h new file mode 100644 index 0000000..d165a53 --- /dev/null +++ b/MP42/MP42MkvTagWriter+Internal.h @@ -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 *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 *seekHeads; +@property (nonatomic, strong) NSArray *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 *)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 diff --git a/MP42/MP42MkvTagWriter.h b/MP42/MP42MkvTagWriter.h new file mode 100644 index 0000000..48f7d4b --- /dev/null +++ b/MP42/MP42MkvTagWriter.h @@ -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 + +#import + +@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 *)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 diff --git a/MP42/MP42MkvTagWriter.m b/MP42/MP42MkvTagWriter.m new file mode 100644 index 0000000..91d910a --- /dev/null +++ b/MP42/MP42MkvTagWriter.m @@ -0,0 +1,1985 @@ +// +// MP42MkvTagWriter.m +// MP42Foundation +// + +#import "MP42MkvTagWriter.h" + +#import "MP42MkvTagWriter+Internal.h" + +#import "MP42MatroskaTagMapping.h" +#import "MP42Metadata.h" +#import "MP42MetadataItem.h" +#import "MP42MetadataFormat.h" +#import "MP42Image.h" +#import "MP42Track.h" +#import "MP42Track+Private.h" +#import "MP42SubtitleTrack.h" +#import "MP42ChapterTrack.h" +#import "MP42Languages.h" + +#include +#include +#include +#include +#include + +static const uint64_t kMkvChunkSize = 4 * 1024 * 1024; + +// MP42MkvKidKind / MP42MkvKid / MP42MkvFile / MP42MkvFieldEdit are declared +// in MP42MkvTagWriter+Internal.h so the remuxer can share them. + +@implementation MP42MkvKid + +- (uint64_t)oldTotal +{ + return self.el.totalSize; +} + +@end + +@implementation MP42MkvFile +@end + +@implementation MP42MkvFieldEdit +@end + +@interface MP42MkvTagWriter () +{ + NSURL *_URL; + volatile BOOL _cancelled; + uint64_t _fileSize; +} +@end + +@implementation MP42MkvTagWriter + +- (instancetype)initWithURL:(NSURL *)URL +{ + self = [super init]; + if (self) { + _URL = [URL copy]; + } + return self; +} + +- (NSURL *)fileURL +{ + return _URL; +} + +- (void)cancel +{ + _cancelled = YES; +} + +#pragma mark - Errors + +static NSError *MkvError(MP42MkvError code, NSString *format, ...) +{ + va_list args; + va_start(args, format); + NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; + va_end(args); + return [MP42Ebml errorWithCode:code message:@"%@", message]; +} + +#pragma mark - Entry point + +- (BOOL)writeMetadata:(MP42Metadata *)metadata error:(NSError **)outError +{ + return [self writeMetadata:metadata tracks:nil error:outError]; +} + +- (BOOL)writeMetadata:(MP42Metadata *)metadata tracks:(NSArray *)tracks error:(NSError **)outError +{ + _cancelled = NO; + + MP42EbmlScanner *scanner = [MP42EbmlScanner scannerWithURL:_URL error:outError]; + if (!scanner) { + return NO; + } + + _fileSize = scanner.fileSize; + + if (![self checkStalenessWithError:outError]) { + return NO; + } + + MP42MkvFile *file = [self scanFile:scanner error:outError]; + if (!file) { + return NO; + } + + // Build the new Tags payload (modeled groups + carried-through originals). + NSData *newTagsPayload = [self buildTagsPayloadForMetadata:metadata file:file error:outError]; + if (!newTagsPayload) { + return NO; + } + + BOOL tagsShouldExist = newTagsPayload.length > 0; + BOOL tagsChanged; + if (tagsShouldExist) { + tagsChanged = !file.tags || ![newTagsPayload isEqualToData:file.tags.payload]; + } else { + tagsChanged = file.tags != nil; // nothing to write: remove the old element + } + + // Cover art handling: rebuild Attachments only when the cover actually changed. + NSData *newAttPayload = nil; + BOOL attChanged = NO, attShouldExist = NO; + if (![self buildAttachmentsPayloadForMetadata:metadata + file:file + payload:&newAttPayload + changed:&attChanged + shouldExist:&attShouldExist + error:outError]) { + return NO; + } + + // Per-track field edits (name / language / enabled / subtitle forced). + NSData *newTracksPayload = nil; + BOOL tracksChanged = NO; + if (tracks.count > 0) { + if (![self buildTracksPayloadForTracks:tracks + file:file + payload:&newTracksPayload + changed:&tracksChanged + error:outError]) { + return NO; + } + } + + if (!tagsChanged && !attChanged && !tracksChanged) { + return YES; // nothing to do + } + + return [self rewriteFile:scanner + file:file + newTagsPayload:tagsChanged ? newTagsPayload : nil + tagsShouldExist:tagsShouldExist + newAttPayload:attChanged ? newAttPayload : nil + attShouldExist:attShouldExist + newTracksPayload:tracksChanged ? newTracksPayload : nil + error:outError]; +} + +- (BOOL)checkStalenessWithError:(NSError **)outError +{ + if (self.expectedFileSize == 0 && self.expectedModificationDate == nil) { + return YES; + } + + struct stat st; + if (stat(_URL.fileSystemRepresentation, &st) != 0) { + if (outError) { + *outError = MkvError(MP42MkvErrorStaleFile, @"%@ no longer exists", _URL.lastPathComponent); + } + return NO; + } + + if (self.expectedFileSize != 0 && (uint64_t)st.st_size != self.expectedFileSize) { + if (outError) { + *outError = MkvError(MP42MkvErrorStaleFile, + @"%@ changed on disk since it was opened", _URL.lastPathComponent); + } + return NO; + } + + if (self.expectedModificationDate) { + NSDate *mtime = [NSDate dateWithTimeIntervalSince1970:st.st_mtimespec.tv_sec]; + if (fabs([mtime timeIntervalSinceDate:self.expectedModificationDate]) > 1.0) { + if (outError) { + *outError = MkvError(MP42MkvErrorStaleFile, + @"%@ changed on disk since it was opened", _URL.lastPathComponent); + } + return NO; + } + } + + return YES; +} + +#pragma mark - Scanning + +- (MP42MkvFile *)scanFile:(MP42EbmlScanner *)scanner error:(NSError **)outError +{ + NSArray *top = [scanner scanChildrenFrom:0 + length:MP42EbmlScanToEnd + error:outError]; + if (!top) { + return nil; + } + + NSMutableArray *segments = [NSMutableArray array]; + for (MP42EbmlElement *el in top) { + if (el.identifier == MP42MkvElementSegment) { + [segments addObject:el]; + } + } + + if (segments.count == 0) { + *outError = MkvError(MP42MkvErrorParse, @"%@ is not a Matroska file", _URL.lastPathComponent); + return nil; + } + if (segments.count > 1) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"%@ contains multiple segments (chained files); tagging it is not supported", + _URL.lastPathComponent); + return nil; + } + + MP42EbmlElement *segment = segments.firstObject; + + MP42MkvFile *file = [[MP42MkvFile alloc] init]; + file.segment = segment; + file.segmentSizeUnknown = segment.sizeIsUnknown; + file.segDataStart = segment.dataStart; + file.segDataLen = segment.sizeIsUnknown ? (scanner.fileSize - segment.dataStart) : segment.dataSize; + + NSArray *elements = [scanner scanChildrenFrom:segment.dataStart + length:file.segDataLen + error:outError]; + if (!elements || elements.count == 0) { + if (elements && outError) { + *outError = MkvError(MP42MkvErrorParse, @"%@ contains an empty segment", _URL.lastPathComponent); + } + return nil; + } + + NSMutableArray *kids = [NSMutableArray array]; + NSMutableArray *seekHeads = [NSMutableArray array]; + NSMutableArray *cues = [NSMutableArray array]; + + for (NSUInteger i = 0; i < elements.count; i++) { + MP42EbmlElement *el = elements[i]; + + MP42MkvKid *kid = [[MP42MkvKid alloc] init]; + kid.el = el; + kid.relStart = el.start - segment.dataStart; + + switch (el.identifier) { + case MP42MkvElementTags: + if (file.tags) { + *outError = MkvError(MP42MkvErrorUnsupported, @"%@ contains multiple Tags elements", _URL.lastPathComponent); + return nil; + } + kid.kind = MP42MkvKidTags; + file.tags = kid; + break; + + case MP42MkvElementAttachments: + if (file.attachments) { + *outError = MkvError(MP42MkvErrorUnsupported, @"%@ contains multiple Attachments elements", _URL.lastPathComponent); + return nil; + } + kid.kind = MP42MkvKidAttachments; + file.attachments = kid; + break; + + case MP42MkvElementTracks: + if (file.tracks) { + *outError = MkvError(MP42MkvErrorUnsupported, @"%@ contains multiple Tracks elements", _URL.lastPathComponent); + return nil; + } + kid.kind = MP42MkvKidTracks; + file.tracks = kid; + break; + + case MP42MkvElementSeekHead: + kid.kind = MP42MkvKidSeekHead; + [seekHeads addObject:kid]; + break; + + case MP42MkvElementCues: + kid.kind = MP42MkvKidCues; + [cues addObject:kid]; + break; + + case MP42MkvElementCluster: + kid.kind = MP42MkvKidCluster; + if (!file.firstCluster) { + file.firstCluster = kid; + } + break; + + default: + kid.kind = MP42MkvKidKeep; + break; + } + + if (el.sizeIsUnknown) { + // Only the trailing child may have an unknown size (streamed + // files: the final cluster). Anything else we refuse to touch. + BOOL isLast = (i == elements.count - 1); + if (!isLast || kid.kind != MP42MkvKidCluster) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"%@ contains an unknown-size element 0x%x we cannot rewrite", + _URL.lastPathComponent, el.identifier); + return nil; + } + } + + // Load payloads for the elements we plan to rewrite. + if (kid.kind == MP42MkvKidTags || kid.kind == MP42MkvKidAttachments || + kid.kind == MP42MkvKidTracks || + kid.kind == MP42MkvKidSeekHead || kid.kind == MP42MkvKidCues) { + kid.payload = [scanner readAtOffset:el.dataStart length:el.dataSize error:outError]; + if (!kid.payload) { + return nil; + } + } + + [kids addObject:kid]; + } + + file.kids = kids; + file.seekHeads = seekHeads; + file.cues = cues; + return file; +} + +#pragma mark - Tags serialization + +// A modeled/mapped tag value as it should appear in TagString. +static NSString *MP42MkvStringFromValue(id value) +{ + if (!value || value == [NSNull null]) { + return nil; + } + if ([value isKindOfClass:NSString.class]) { + NSString *string = (NSString *)value; + return string.length ? string : nil; + } + if ([value isKindOfClass:NSNumber.class]) { + return [(NSNumber *)value stringValue]; + } + if ([value isKindOfClass:NSArray.class]) { + // Person fields (Cast, Director, Screenwriters, …) are StringArray in + // the model; join with the same ", " separator + // -[MP42MetadataItem stringFromStringArray:] uses, so the importer's + // comma-split reads the list back verbatim. + NSMutableArray *parts = [NSMutableArray array]; + for (id element in (NSArray *)value) { + NSString *part = MP42MkvStringFromValue(element); + if (part.length) { + [parts addObject:part]; + } + } + return parts.count ? [parts componentsJoinedByString:@", "] : nil; + } + if ([value isKindOfClass:NSDate.class]) { + static NSDateFormatter *formatter; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + formatter = [[NSDateFormatter alloc] init]; + formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; + formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + formatter.dateFormat = @"yyyy-MM-dd"; + }); + return [formatter stringFromDate:(NSDate *)value]; + } + return nil; +} + +// Legacy 3-char ISO-639-2/B TagLanguage, written only when the item carries +// one and it is not the implicit default "und". +static NSString *MP42MkvTagLanguageOfItem(MP42MetadataItem *item) +{ + NSString *tag = item.extendedLanguageTag; + if (tag.length != 3) { + return nil; + } + for (NSUInteger i = 0; i < 3; i++) { + unichar c = [tag characterAtIndex:i]; + BOOL alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + if (!alpha) { + return nil; + } + } + tag = tag.lowercaseString; + if ([tag isEqualToString:@"und"]) { + return nil; // the spec default + } + return tag; +} + +static void MP42MkvAppendSimpleTag(NSMutableData *out, NSString *name, NSString *value, NSString *language) +{ + NSMutableData *payload = [NSMutableData data]; + [MP42Ebml appendStringElement:MP42MkvElementTagName string:name to:payload]; + if (language) { + [MP42Ebml appendStringElement:MP42MkvElementTagLanguage string:language to:payload]; + } + [MP42Ebml appendStringElement:MP42MkvElementTagString string:value to:payload]; + [MP42Ebml appendElement:MP42MkvElementSimpleTag payload:payload to:out]; +} + +// Subdata of a whole element (header + payload) within a scanned buffer. +static NSData *MP42MkvBufferSlice(NSData *buffer, MP42EbmlElement *el, uint64_t regionEnd) +{ + uint64_t end = [MP42Ebml payloadEndForElement:el regionEnd:regionEnd]; + return [buffer subdataWithRange:NSMakeRange((NSUInteger)el.start, (NSUInteger)(end - el.start))]; +} + +- (NSData *)buildTagsPayloadForMetadata:(MP42Metadata *)metadata + file:(MP42MkvFile *)file + error:(NSError **)outError +{ + NSMutableArray *foreignGroups = [NSMutableArray array]; // whole Tag elements, verbatim + NSMutableArray *otherTagsChildren = [NSMutableArray array]; // unknown direct children of Tags + NSMutableDictionary *> *carry = [NSMutableDictionary dictionary]; + NSMutableDictionary *> *extras = [NSMutableDictionary dictionary]; + NSMutableArray *trackSpecials = [NSMutableArray array]; // PART_NUMBER/TOTAL_PARTS, deferred + + void (^addCarry)(NSInteger, NSData *) = ^(NSInteger level, NSData *raw) { + NSNumber *key = @(level); + NSMutableArray *bucket = carry[key]; + if (!bucket) { + bucket = [NSMutableArray array]; + carry[key] = bucket; + } + [bucket addObject:raw]; + }; + void (^addExtra)(NSInteger, NSData *) = ^(NSInteger level, NSData *raw) { + NSNumber *key = @(level); + NSMutableArray *bucket = extras[key]; + if (!bucket) { + bucket = [NSMutableArray array]; + extras[key] = bucket; + } + [bucket addObject:raw]; + }; + + if (file.tags) { + NSData *tagsBuf = file.tags.payload; + uint64_t tagsEnd = tagsBuf.length; + + NSArray *groups = [MP42Ebml scanBuffer:tagsBuf from:0 length:MP42EbmlScanToEnd error:outError]; + if (!groups) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"Existing tags in %@ could not be parsed (%@); refusing to overwrite them", + _URL.lastPathComponent, (*outError).localizedDescription); + return nil; + } + + for (MP42EbmlElement *group in groups) { + if (group.identifier != MP42MkvElementTag || group.sizeIsUnknown) { + [otherTagsChildren addObject:MP42MkvBufferSlice(tagsBuf, group, tagsEnd)]; + continue; + } + + NSArray *groupKids = [MP42Ebml scanBuffer:tagsBuf + from:group.dataStart + length:group.dataSize + error:outError]; + if (!groupKids) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"A tag group in %@ could not be parsed; refusing to overwrite it", + _URL.lastPathComponent); + return nil; + } + + // Classify: modelled (global/part/movie/season/collection with + // only a TargetTypeValue) or foreign (UID targets, chapter/scene/ + // shot levels, ambiguous targets). + BOOL foreign = NO; + BOOL levelFound = NO; + NSInteger level = MP42MkvTargetGlobal; + NSMutableArray *simpleTags = [NSMutableArray array]; + NSMutableArray *groupExtras = [NSMutableArray array]; + + for (MP42EbmlElement *gk in groupKids) { + if (gk.sizeIsUnknown) { + foreign = YES; + break; + } + + if (gk.identifier == MP42MkvElementTargets) { + NSArray *targetKids = [MP42Ebml scanBuffer:tagsBuf + from:gk.dataStart + length:gk.dataSize + error:NULL]; + if (!targetKids) { + foreign = YES; + break; + } + for (MP42EbmlElement *tk in targetKids) { + if (tk.identifier == MP42MkvElementTargetTypeValue && !tk.sizeIsUnknown && !levelFound) { + NSData *levelData = [tagsBuf subdataWithRange:NSMakeRange((NSUInteger)tk.dataStart, (NSUInteger)tk.dataSize)]; + level = (NSInteger)[MP42Ebml unsignedIntValueAt:levelData.bytes length:levelData.length]; + levelFound = YES; + } else if (tk.identifier == MP42MkvElementTargetType) { + // human-readable level name; dropped on rewrite, harmless + } else { + foreign = YES; // track/chapter/edition/attachment UIDs or unknown target kinds + break; + } + } + if (foreign) { + break; + } + } else if (gk.identifier == MP42MkvElementSimpleTag) { + [simpleTags addObject:gk]; + } else { + [groupExtras addObject:MP42MkvBufferSlice(tagsBuf, gk, tagsEnd)]; + } + } + + if (!foreign && !MP42MkvTargetLevelIsModeled(level)) { + foreign = YES; + } + + if (foreign) { + [foreignGroups addObject:MP42MkvBufferSlice(tagsBuf, group, tagsEnd)]; + continue; + } + + NSDictionary *map = MP42MkvSimpleTagMapForTargetLevel(level); + NSInteger bucket; + switch (level) { + case MP42MkvTargetGlobal: + case MP42MkvTargetPart: + case MP42MkvTargetSeason: + case MP42MkvTargetCollection: bucket = level; break; + default: bucket = MP42MkvTargetMovie; break; + } + + for (MP42EbmlElement *st in simpleTags) { + NSData *stRaw = MP42MkvBufferSlice(tagsBuf, st, tagsEnd); + + NSArray *stKids = [MP42Ebml scanBuffer:tagsBuf + from:st.dataStart + length:st.dataSize + error:NULL]; + NSString *name = nil; + BOOL hasString = NO; + for (MP42EbmlElement *sk in stKids) { + if (sk.identifier == MP42MkvElementTagName && !name && !sk.sizeIsUnknown) { + NSData *nameData = [tagsBuf subdataWithRange:NSMakeRange((NSUInteger)sk.dataStart, (NSUInteger)sk.dataSize)]; + name = [[NSString alloc] initWithData:nameData encoding:NSUTF8StringEncoding]; + } else if (sk.identifier == MP42MkvElementTagString) { + hasString = YES; + } + } + + BOOL consumed = (name && map[name] && hasString); + + // PART_NUMBER/TOTAL_PARTS are regenerated from TrackNumber + // and TVSeason (which are themselves read from these tags); + // whether the originals are consumed depends on the model, + // so defer the decision until after all groups are scanned. + // This mirroring keeps saves idempotent: exactly the tags + // the writer cannot regenerate are carried through. + if (!consumed && hasString && + ([name isEqualToString:@"PART_NUMBER"] || [name isEqualToString:@"TOTAL_PARTS"])) { + [trackSpecials addObject:@{ @"bucket": @(bucket), + @"name": name, + @"raw": stRaw }]; + continue; + } + + if (!consumed) { + addCarry(bucket, stRaw); // unmapped name, missing value, or binary tag: keep verbatim + } + } + + for (NSData *raw in groupExtras) { + addExtra(bucket, raw); + } + } + } + + // What the writer will regenerate from the model, mirrored exactly so + // each original PART_NUMBER/TOTAL_PARTS is either reproduced or carried. + MP42MetadataItem *trackItem = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyTrackNumber].firstObject; + NSArray *trackArray = [trackItem.arrayValue isKindOfClass:NSArray.class] ? trackItem.arrayValue : nil; + NSInteger modelTrack = trackArray.count > 0 && [trackArray[0] respondsToSelector:@selector(intValue)] ? [trackArray[0] intValue] : 0; + NSInteger modelTotal = trackArray.count > 1 && [trackArray[1] respondsToSelector:@selector(intValue)] ? [trackArray[1] intValue] : 0; + NSInteger modelSeason = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyTVSeason].firstObject.numberValue.intValue; + // The file stores a single movie-level PART_NUMBER; the importer fills + // both TrackNumber and TVEpisodeNumber from it, so mirror that here: + // TrackNumber wins, TVEpisodeNumber is the fallback (the app also keeps + // the two model items in sync when the user edits either one). + NSInteger modelEpisode = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyTVEpisodeNumber].firstObject.numberValue.intValue; + NSInteger modelPart = modelTrack > 0 ? modelTrack : modelEpisode; + + for (NSDictionary *entry in trackSpecials) { + NSInteger bucket = [entry[@"bucket"] integerValue]; + NSString *tagName = entry[@"name"]; + BOOL regenerated; + if (bucket == MP42MkvTargetSeason) { + regenerated = [tagName isEqualToString:@"PART_NUMBER"] && modelSeason > 0; + } else if (bucket == MP42MkvTargetMovie) { + regenerated = ([tagName isEqualToString:@"PART_NUMBER"] && modelPart > 0) || + ([tagName isEqualToString:@"TOTAL_PARTS"] && modelTotal > 0); + } else { + regenerated = NO; // e.g. collection/group level originals: keep verbatim + } + if (!regenerated) { + addCarry(bucket, entry[@"raw"]); + } + } + + NSMutableData *out = [NSMutableData data]; + + NSArray *levelOrder = @[ @(MP42MkvTargetCollection), + @(MP42MkvTargetSeason), + @(MP42MkvTargetMovie), + @(MP42MkvTargetPart), + @(MP42MkvTargetGlobal) ]; + + // Keys with a canonical home level, skipped in other groups. + NSSet *collectionSkip = [NSSet setWithObject:MP42MetadataKeyCopyright]; + NSSet *seasonSkip = [NSSet setWithObjects:MP42MetadataKeySeriesDescription, + MP42MetadataKeyReleaseDate, nil]; + + for (NSNumber *levelNumber in levelOrder) { + NSInteger level = levelNumber.integerValue; + NSInteger bucket = level; + + NSMutableData *groupPayload = [NSMutableData data]; + NSUInteger simpleTagCount = 0; + + if (level != MP42MkvTargetGlobal) { + NSMutableData *targets = [NSMutableData data]; + NSMutableData *levelValue = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:(uint64_t)level width:1 to:levelValue]; + [MP42Ebml appendElement:MP42MkvElementTargetTypeValue payload:levelValue to:targets]; + [MP42Ebml appendElement:MP42MkvElementTargets payload:targets to:groupPayload]; + } + + // Mapped values (movie/season/collection groups only; part and + // global groups are regenerated carry-only, their mapped values all + // live in the movie group). + if (level == MP42MkvTargetCollection || level == MP42MkvTargetSeason || level == MP42MkvTargetMovie) { + NSArray *pairs = MP42MkvWritePairsForTargetLevel(level); + NSSet *skip = (level == MP42MkvTargetCollection) ? collectionSkip + : (level == MP42MkvTargetSeason) ? seasonSkip + : [NSSet set]; + + for (MP42MkvTagPair *pair in pairs) { + if ([skip containsObject:pair.metadataKey]) { + continue; + } + MP42MetadataItem *item = [metadata metadataItemsFilteredByIdentifier:pair.metadataKey].firstObject; + NSString *value = MP42MkvStringFromValue(item.value); + if (!value) { + continue; + } + MP42MkvAppendSimpleTag(groupPayload, pair.simpleTagName, value, MP42MkvTagLanguageOfItem(item)); + simpleTagCount++; + } + + if (level == MP42MkvTargetMovie && (modelPart > 0 || modelTotal > 0)) { + // [track, total] (or TVEpisodeNumber fallback) -> PART_NUMBER / + // TOTAL_PARTS (the importer reads these back into + // TrackNumber/TVEpisodeNumber). + if (modelPart > 0) { + MP42MkvAppendSimpleTag(groupPayload, @"PART_NUMBER", [@(modelPart) stringValue], nil); + simpleTagCount++; + } + if (modelTotal > 0) { + MP42MkvAppendSimpleTag(groupPayload, @"TOTAL_PARTS", [@(modelTotal) stringValue], nil); + simpleTagCount++; + } + } + } + + NSArray *carried = carry[@(bucket)]; + NSArray *groupExtra = extras[@(bucket)]; + for (NSData *raw in carried) { + [groupPayload appendData:raw]; + simpleTagCount++; + } + for (NSData *raw in groupExtra) { + [groupPayload appendData:raw]; + } + + if (simpleTagCount > 0) { + [MP42Ebml appendElement:MP42MkvElementTag payload:groupPayload to:out]; + } + } + + for (NSData *raw in otherTagsChildren) { + [out appendData:raw]; + } + for (NSData *raw in foreignGroups) { + [out appendData:raw]; + } + + return out; +} + +#pragma mark - Attachments / cover art + +- (BOOL)buildAttachmentsPayloadForMetadata:(MP42Metadata *)metadata + file:(MP42MkvFile *)file + payload:(NSData **)outPayload + changed:(BOOL *)outChanged + shouldExist:(BOOL *)outShouldExist + error:(NSError **)outError +{ + *outChanged = NO; + *outShouldExist = file.attachments != nil; + + MP42MetadataItem *artItem = [metadata metadataItemsFilteredByIdentifier:MP42MetadataKeyCoverArt].firstObject; + MP42Image *modelImage = nil; + if (artItem.value && artItem.value != [NSNull null]) { + if (![artItem.value isKindOfClass:MP42Image.class]) { + *outError = MkvError(MP42MkvErrorUnsupported, @"Unsupported artwork type for Matroska tagging"); + return NO; + } + modelImage = (MP42Image *)artItem.value; + if (modelImage.type != MP42_ART_JPEG && modelImage.type != MP42_ART_PNG) { + *outError = MkvError(MP42MkvErrorUnsupported, @"Matroska cover art must be JPEG or PNG"); + return NO; + } + } + NSData *modelData = modelImage.data; + if (modelData.length == 0) { + modelData = nil; + } + + // Parse the existing attachments (if any). The "cover" is the first + // image/jpeg|png attachment — exactly what the importer reads. + NSData *oldCoverData = nil; + NSMutableArray *otherAttachments = [NSMutableArray array]; + uint64_t maxUID = 0; + BOOL haveOldCover = NO; + + if (file.attachments) { + NSData *buf = file.attachments.payload; + uint64_t regionEnd = buf.length; + + NSArray *files = [MP42Ebml scanBuffer:buf from:0 length:MP42EbmlScanToEnd error:outError]; + if (!files) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"Existing attachments in %@ could not be parsed; refusing to rewrite them", + _URL.lastPathComponent); + return NO; + } + + for (MP42EbmlElement *fileEl in files) { + if (fileEl.identifier != MP42MkvElementAttachedFile || fileEl.sizeIsUnknown) { + [otherAttachments addObject:MP42MkvBufferSlice(buf, fileEl, regionEnd)]; + continue; + } + + NSArray *kids = [MP42Ebml scanBuffer:buf + from:fileEl.dataStart + length:fileEl.dataSize + error:NULL]; + NSString *mime = nil; + uint64_t uid = 0; + NSData *fileData = nil; + for (MP42EbmlElement *k in kids) { + if (k.sizeIsUnknown) continue; + if (k.identifier == MP42MkvElementFileMimeType) { + NSData *d = [buf subdataWithRange:NSMakeRange((NSUInteger)k.dataStart, (NSUInteger)k.dataSize)]; + mime = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]; + } else if (k.identifier == MP42MkvElementFileUID) { + NSData *d = [buf subdataWithRange:NSMakeRange((NSUInteger)k.dataStart, (NSUInteger)k.dataSize)]; + uid = [MP42Ebml unsignedIntValueAt:d.bytes length:d.length]; + } else if (k.identifier == MP42MkvElementFileData) { + fileData = [buf subdataWithRange:NSMakeRange((NSUInteger)k.dataStart, (NSUInteger)k.dataSize)]; + } + } + if (uid > maxUID) { + maxUID = uid; + } + + BOOL isImage = [mime isEqualToString:@"image/jpeg"] || [mime isEqualToString:@"image/png"]; + if (isImage && !haveOldCover) { + haveOldCover = YES; + oldCoverData = fileData; + // the cover element itself is not copied; rebuilt if needed + } else { + [otherAttachments addObject:MP42MkvBufferSlice(buf, fileEl, regionEnd)]; + } + } + } + + BOOL same = (!modelData && !oldCoverData) || + (modelData && oldCoverData && [modelData isEqualToData:oldCoverData]); + if (same) { + return YES; // attachments untouched: fast path or no-op + } + + NSMutableData *payload = [NSMutableData data]; + + if (modelData) { + BOOL isPng = modelImage.type == MP42_ART_PNG; + NSMutableData *cover = [NSMutableData data]; + [MP42Ebml appendStringElement:MP42MkvElementFileDescription string:@"cover front" to:cover]; + [MP42Ebml appendStringElement:MP42MkvElementFileName string:(isPng ? @"cover.png" : @"cover.jpg") to:cover]; + [MP42Ebml appendStringElement:MP42MkvElementFileMimeType + string:(isPng ? @"image/png" : @"image/jpeg") to:cover]; + [MP42Ebml appendElement:MP42MkvElementFileData payload:modelData to:cover]; + NSMutableData *uidData = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:(maxUID + 1) width:1 to:uidData]; + [MP42Ebml appendElement:MP42MkvElementFileUID payload:uidData to:cover]; + [MP42Ebml appendElement:MP42MkvElementAttachedFile payload:cover to:payload]; + } + for (NSData *raw in otherAttachments) { + [payload appendData:raw]; + } + + *outPayload = payload; + *outChanged = YES; + *outShouldExist = payload.length > 0; + return YES; +} + +#pragma mark - Track field editing + +// Defined with the rewrite engine below. +static NSData *MP42MkvEncodedElement(uint32_t identifier, NSData *payload); + +static NSData *MP42MkvUTF8Data(NSString *string) +{ + return [string dataUsingEncoding:NSUTF8StringEncoding]; +} + +// UTF-8 payload of a string element, trailing NULs trimmed; empty ≙ absent. +static NSString *MP42MkvStringForElement(NSData *buffer, MP42EbmlElement *el) +{ + if (!el || el.sizeIsUnknown || el.dataSize == 0) { + return nil; + } + NSData *data = [buffer subdataWithRange:NSMakeRange((NSUInteger)el.dataStart, (NSUInteger)el.dataSize)]; + const uint8_t *bytes = data.bytes; + NSUInteger length = data.length; + while (length > 0 && bytes[length - 1] == 0) { + length--; + } + if (length == 0) { + return nil; + } + return [[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding]; +} + +static BOOL MP42MkvFlagForElement(NSData *buffer, MP42EbmlElement *el, BOOL defaultValue) +{ + if (!el || el.sizeIsUnknown || el.dataSize == 0) { + return defaultValue; + } + NSData *data = [buffer subdataWithRange:NSMakeRange((NSUInteger)el.dataStart, (NSUInteger)el.dataSize)]; + return [MP42Ebml unsignedIntValueAt:data.bytes length:data.length] != 0; +} + +static MP42MkvFieldEdit *MP42MkvSetEdit(uint32_t appendId, NSData *payload) +{ + MP42MkvFieldEdit *edit = [[MP42MkvFieldEdit alloc] init]; + edit.action = MP42MkvFieldSet; + edit.appendId = appendId; + edit.payload = payload; + return edit; +} + +// Rebuilds one TrackEntry with the model's field values substituted; only +// Name / TrackLanguage / LanguageIETF / TrackFlagEnabled / TrackFlagForced +// are ever touched, every other child (and every unedited entry as a whole) +// is copied byte-for-byte. Returns the original bytes when nothing differs. +- (nullable NSData *)editTrackEntry:(MP42EbmlElement *)entry + buffer:(NSData *)buffer + regionEnd:(uint64_t)regionEnd + track:(MP42Track *)track + error:(NSError **)outError +{ + NSData *original = MP42MkvBufferSlice(buffer, entry, regionEnd); + + uint64_t entryEnd = entry.dataStart + entry.dataSize; + NSArray *kids = [MP42Ebml scanBuffer:buffer + from:entry.dataStart + length:entry.dataSize + error:outError]; + if (!kids) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"A track in %@ could not be parsed; refusing to rewrite it", + _URL.lastPathComponent); + return nil; + } + for (MP42EbmlElement *kid in kids) { + if (kid.sizeIsUnknown) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"A track in %@ contains an unknown-size element we cannot rewrite", + _URL.lastPathComponent); + return nil; + } + } + + MP42EbmlElement *nameEl = nil, *langEl = nil, *ietfEl = nil, *enabledEl = nil, *forcedEl = nil; + for (MP42EbmlElement *kid in kids) { + switch (kid.identifier) { + case MP42MkvElementTrackName: + if (!nameEl) nameEl = kid; + break; + case MP42MkvElementTrackLanguage: + case MP42MkvElementTrackLanguageSpec: // same ISO value, newer spec id + if (!langEl) langEl = kid; + break; + case MP42MkvElementTrackLanguageIETF: + if (!ietfEl) ietfEl = kid; + break; + case MP42MkvElementTrackFlagEnabled: + if (!enabledEl) enabledEl = kid; + break; + case MP42MkvElementTrackFlagForced: + if (!forcedEl) forcedEl = kid; + break; + default: + break; + } + } + + // Effective current values, computed exactly like MP42MkvImporter reads + // them, so an untouched model never registers as a change. + NSString *currentName = MP42MkvStringForElement(buffer, nameEl); + NSString *currentIETF = MP42MkvStringForElement(buffer, ietfEl); + NSString *currentLang3 = MP42MkvStringForElement(buffer, langEl); + if (currentLang3.length != 3) { + currentLang3 = nil; + } + + MP42Languages *langs = MP42Languages.defaultManager; + NSString *currentLanguage = currentIETF ? [langs normalizedExtendedTag:currentIETF] + : [langs extendedTagForISO_639_2b:(currentLang3 ?: @"")]; + BOOL currentEnabled = MP42MkvFlagForElement(buffer, enabledEl, YES); + BOOL currentForced = MP42MkvFlagForElement(buffer, forcedEl, NO); + + NSMutableDictionary *edits = [NSMutableDictionary dictionary]; + + // Name: the localized default label is expressed by the element's absence. + NSString *targetName = track.name; + if ([targetName isEqualToString:[track defaultName]]) { + targetName = nil; + } + BOOL nameSame = (!targetName && !currentName) || + (targetName && currentName && [targetName isEqualToString:currentName]); + if (!nameSame) { + if (targetName) { + edits[@(MP42MkvElementTrackName)] = MP42MkvSetEdit(MP42MkvElementTrackName, MP42MkvUTF8Data(targetName)); + } else if (nameEl) { + MP42MkvFieldEdit *drop = [[MP42MkvFieldEdit alloc] init]; + drop.action = MP42MkvFieldDrop; + edits[@(MP42MkvElementTrackName)] = drop; + } + } + + // Language: always a TrackLanguage 3-tag; LanguageIETF only for extended + // tags that carry a region ("eng-US"), mirroring what mkvmerge writes. + NSString *targetLanguage = track.language ?: @"und"; + if (![targetLanguage isEqualToString:currentLanguage]) { + edits[@(MP42MkvElementTrackLanguage)] = + MP42MkvSetEdit(MP42MkvElementTrackLanguage, MP42MkvUTF8Data([langs ISO_639_2CodeForExtendedTag:targetLanguage])); + + BOOL hasRegion = [targetLanguage rangeOfString:@"-"].location != NSNotFound; + if (hasRegion) { + NSString *ietfTag = [targetLanguage stringByReplacingOccurrencesOfString:@"_" withString:@"-"]; + if (!currentIETF || ![ietfTag isEqualToString:currentIETF]) { + edits[@(MP42MkvElementTrackLanguageIETF)] = + MP42MkvSetEdit(MP42MkvElementTrackLanguageIETF, MP42MkvUTF8Data(ietfTag)); + } + } else if (ietfEl) { + MP42MkvFieldEdit *drop = [[MP42MkvFieldEdit alloc] init]; + drop.action = MP42MkvFieldDrop; + edits[@(MP42MkvElementTrackLanguageIETF)] = drop; + } + } + + if (track.isEnabled != currentEnabled) { + NSMutableData *flag = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:(track.isEnabled ? 1 : 0) width:1 to:flag]; + edits[@(MP42MkvElementTrackFlagEnabled)] = MP42MkvSetEdit(MP42MkvElementTrackFlagEnabled, flag); + } + + if ([track isKindOfClass:MP42SubtitleTrack.class]) { + BOOL targetForced = ((MP42SubtitleTrack *)track).allSamplesAreForced; + if (targetForced != currentForced) { + NSMutableData *flag = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:(targetForced ? 1 : 0) width:1 to:flag]; + edits[@(MP42MkvElementTrackFlagForced)] = MP42MkvSetEdit(MP42MkvElementTrackFlagForced, flag); + } + } + + if (edits.count == 0) { + return original; + } + + static NSDictionary *sFieldKeys = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sFieldKeys = @{ @(MP42MkvElementTrackName): @(MP42MkvElementTrackName), + @(MP42MkvElementTrackLanguage): @(MP42MkvElementTrackLanguage), + @(MP42MkvElementTrackLanguageSpec): @(MP42MkvElementTrackLanguage), + @(MP42MkvElementTrackLanguageIETF): @(MP42MkvElementTrackLanguageIETF), + @(MP42MkvElementTrackFlagEnabled): @(MP42MkvElementTrackFlagEnabled), + @(MP42MkvElementTrackFlagForced): @(MP42MkvElementTrackFlagForced) }; + }); + + NSMutableData *payload = [NSMutableData data]; + NSMutableSet *handled = [NSMutableSet set]; + for (MP42EbmlElement *kid in kids) { + NSNumber *key = sFieldKeys[@(kid.identifier)]; + MP42MkvFieldEdit *edit = key ? edits[key] : nil; + if (!edit) { + [payload appendData:MP42MkvBufferSlice(buffer, kid, entryEnd)]; + } else if (edit.action == MP42MkvFieldDrop) { + [handled addObject:key]; // every occurrence disappears + } else if (![handled containsObject:key]) { + // Replace in place, preserving the original element id (a newer + // spec 0x447A language id is normalized to the practical 0x22B59C). + uint32_t writeId = (kid.identifier == MP42MkvElementTrackLanguageSpec) + ? MP42MkvElementTrackLanguage : kid.identifier; + [MP42Ebml appendElement:writeId payload:edit.payload to:payload]; + [handled addObject:key]; + } // Set: later duplicates are dropped + + } + + // Fields the file never carried: append (EBML readers key by id; the + // documented ordering inside a TrackEntry is advisory). + for (NSNumber *key in edits) { + MP42MkvFieldEdit *edit = edits[key]; + if (edit.action == MP42MkvFieldSet && ![handled containsObject:key]) { + [MP42Ebml appendElement:edit.appendId payload:edit.payload to:payload]; + [handled addObject:key]; + } + } + + return MP42MkvEncodedElement(MP42MkvElementTrackEntry, payload); +} + +// Rebuilds the whole Tracks payload from the model's per-track field values. +// Model tracks map to TrackEntry elements by file order; chapter tracks (a +// Subler-only concept) are skipped. +- (BOOL)buildTracksPayloadForTracks:(NSArray *)modelTracks + file:(MP42MkvFile *)file + payload:(NSData **)outPayload + changed:(BOOL *)outChanged + error:(NSError **)outError +{ + *outChanged = NO; + *outPayload = nil; + + if (!file.tracks) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"%@ has no Tracks element to edit", _URL.lastPathComponent); + return NO; + } + + NSMutableArray *realTracks = [NSMutableArray array]; + for (MP42Track *track in modelTracks) { + if (![track isMemberOfClass:MP42ChapterTrack.class]) { + [realTracks addObject:track]; + } + } + + NSData *buf = file.tracks.payload; + uint64_t regionEnd = buf.length; + NSArray *kids = [MP42Ebml scanBuffer:buf from:0 length:MP42EbmlScanToEnd error:outError]; + if (!kids) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"The tracks in %@ could not be parsed; refusing to rewrite them", + _URL.lastPathComponent); + return NO; + } + + NSUInteger entryCount = 0; + for (MP42EbmlElement *kid in kids) { + if (kid.identifier == MP42MkvElementTrackEntry) { + entryCount++; + } + } + if (entryCount != realTracks.count) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"%@ contains %lu tracks but the document has %lu; revert the document before saving", + _URL.lastPathComponent, (unsigned long)entryCount, (unsigned long)realTracks.count); + return NO; + } + + NSMutableData *out = [NSMutableData data]; + NSUInteger modelIndex = 0; + for (MP42EbmlElement *kid in kids) { + if (kid.identifier == MP42MkvElementTrackEntry && !kid.sizeIsUnknown) { + NSData *edited = [self editTrackEntry:kid + buffer:buf + regionEnd:regionEnd + track:realTracks[modelIndex] + error:outError]; + modelIndex++; + if (!edited) { + return NO; + } + [out appendData:edited]; + } else { + if (kid.identifier == MP42MkvElementTrackEntry) { + modelIndex++; // copied verbatim, alignment still advances + } + [out appendData:MP42MkvBufferSlice(buf, kid, regionEnd)]; + } + } + + *outPayload = out; + *outChanged = ![out isEqualToData:buf]; + return YES; +} + +#pragma mark - Rewrite engine + +static const uint64_t kMkvNoPosition = UINT64_MAX; + +static NSUInteger MP42MkvIdWidth(uint32_t identifier) +{ + if (identifier >= 0x10000000u) return 4; + if (identifier >= 0x200000u) return 3; + if (identifier >= 0x4000u) return 2; + return 1; +} + +// Number of bytes a kid occupies in the rewritten file (plan domain: +// offsets relative to the segment data start, which is also the origin +// SeekHead and Cues positions use — so header-width changes cancel out). +static uint64_t MP42MkvKidNewTotal(MP42MkvKid *kid) +{ + if (kid.removed) { + return 0; + } + if (kid.pendingPayload) { + NSUInteger idW = MP42MkvIdWidth(kid.el.identifier); + return idW + [MP42Ebml encodedLengthForSizeValue:kid.pendingPayload.length] + kid.pendingPayload.length; + } + if (kid.materializeUnknown) { + NSUInteger idW = MP42MkvIdWidth(kid.el.identifier); + return idW + [MP42Ebml encodedLengthForSizeValue:kid.el.dataSize] + kid.el.dataSize; + } + return kid.oldTotal; +} + +static NSData *MP42MkvEncodedElement(uint32_t identifier, NSData *payload) +{ + NSMutableData *data = [NSMutableData data]; + [MP42Ebml appendElement:identifier payload:payload to:data]; + return data; +} + +// MP42MkvPosMapper is declared in MP42MkvTagWriter+Internal.h. + +#pragma mark Low-level I/O helpers + +- (BOOL)writeData:(NSData *)data + fd:(int)fd + offset:(uint64_t)offset + error:(NSError **)outError +{ + const uint8_t *bytes = data.bytes; + uint64_t done = 0; + + while (done < data.length) { + if (_cancelled) { + if (outError) { + *outError = MkvError(MP42MkvErrorCancelled, @"cancelled"); + } + return NO; + } + ssize_t n = pwrite(fd, bytes + done, (size_t)(data.length - done), (off_t)(offset + done)); + if (n < 0) { + if (errno == EINTR) { + continue; + } + if (outError) { + *outError = MkvError(MP42MkvErrorWriteFailed, @"Write error (%d)", errno); + } + return NO; + } + done += (uint64_t)n; + } + return YES; +} + +// Copies `length` bytes from the source file into the output at *outOffset, +// advancing the output cursor. Progress is reported against totalEstimate. +- (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 **)outError +{ + uint64_t done = 0; + while (done < length) { + if (_cancelled) { + if (outError) { + *outError = MkvError(MP42MkvErrorCancelled, @"cancelled"); + } + return NO; + } + uint64_t chunkLen = MIN(kMkvChunkSize, length - done); + NSData *chunk = [scanner readAtOffset:sourceAbs + done length:chunkLen error:outError]; + if (!chunk) { + return NO; + } + if (![self writeData:chunk fd:outFd offset:*outOffset error:outError]) { + return NO; + } + *outOffset += chunkLen; + done += chunkLen; + + if (self.progressHandler && totalEstimate > 0) { + self.progressHandler(MIN(0.99, (double)*outOffset / (double)totalEstimate)); + } + } + return YES; +} + +- (BOOL)appendData:(NSData *)data + toFD:(int)fd + outOffset:(uint64_t *)outOffset + error:(NSError **)outError +{ + if (![self writeData:data fd:fd offset:*outOffset error:outError]) { + return NO; + } + *outOffset += data.length; + return YES; +} + +#pragma mark Fast path + +// Slack = the element's own extent plus any immediately following Void +// elements, plus (when the element is the last child) any zero padding at +// the tail of the segment. +- (uint64_t)voidSlackAfterKid:(MP42MkvKid *)kid inFile:(MP42MkvFile *)file +{ + NSUInteger idx = [file.kids indexOfObjectIdenticalTo:kid]; + if (idx == NSNotFound) { + return 0; + } + + // The region the replacement may span is the element's own extent plus + // any immediately-following contiguous Void elements (and, for the last + // element, trailing zero padding inside the segment). + uint64_t cursor = kid.relStart + kid.oldTotal; // end of the element itself + uint64_t slack = kid.oldTotal; // its extent is reusable + NSUInteger j = idx + 1; + for (; j < file.kids.count; j++) { + MP42MkvKid *next = file.kids[j]; + if (next.el.identifier != MP42MkvElementVoid) { + break; + } + slack += next.oldTotal; + cursor = next.relStart + next.oldTotal; + } + if (j == file.kids.count && cursor < file.segDataLen) { + slack += file.segDataLen - cursor; + } + return slack; +} + +- (BOOL)seekHeadsReferenceElement:(uint32_t)identifier file:(MP42MkvFile *)file +{ + for (MP42MkvKid *kid in file.seekHeads) { + NSArray *seeks = [MP42Ebml scanBuffer:kid.payload from:0 length:MP42EbmlScanToEnd error:NULL]; + for (MP42EbmlElement *seek in seeks) { + if (seek.identifier != MP42MkvElementSeek || seek.sizeIsUnknown) { + continue; + } + NSArray *parts = [MP42Ebml scanBuffer:kid.payload from:seek.dataStart length:seek.dataSize error:NULL]; + for (MP42EbmlElement *part in parts) { + if (part.identifier == MP42MkvElementSeekID && !part.sizeIsUnknown && part.dataSize <= 4) { + NSData *idData = [kid.payload subdataWithRange:NSMakeRange((NSUInteger)part.dataStart, (NSUInteger)part.dataSize)]; + if ([MP42Ebml idValueAt:idData.bytes length:idData.length] == identifier) { + return YES; + } + } + } + } + } + return NO; +} + +// Builds the complete region bytes (element + Void filler) for an in-place +// rewrite of `kid`, sized to absorb exactly the element extent plus trailing +// Void slack. Returns NO when the new content does not fit. +- (BOOL)buildFastRegionForKid:(MP42MkvKid *)kid + newPayload:(NSData *)payload + removed:(BOOL)removed + file:(MP42MkvFile *)file + outBytes:(NSData **)outBytes +{ + uint64_t slack = [self voidSlackAfterKid:kid inFile:file]; + NSMutableData *bytes = [NSMutableData data]; + uint64_t newTotal = 0; + + if (!removed && payload.length > 0) { + NSUInteger idW = MP42MkvIdWidth(kid.el.identifier); + NSUInteger oldSizeW = kid.el.headerSize - idW; + NSUInteger canonW = [MP42Ebml encodedLengthForSizeValue:payload.length]; + NSUInteger sizeW = MAX(oldSizeW, canonW); + if (sizeW > 8) { + return NO; + } + [MP42Ebml appendId:kid.el.identifier to:bytes]; + [MP42Ebml appendSize:payload.length width:sizeW to:bytes]; + [bytes appendData:payload]; + newTotal = (uint64_t)sizeW + idW + payload.length; + } + + if (newTotal > slack) { + return NO; + } + uint64_t filler = slack - newTotal; + if (filler == 1) { + return NO; // cannot represent a single spare byte + } + if (filler > 0) { + [MP42Ebml appendVoidOfLength:filler to:bytes]; + } + + *outBytes = bytes; + return YES; +} + +- (BOOL)fastPathWriteFile:(MP42MkvFile *)file + tagsRegionBytes:(NSData *)tagsRegionBytes + attRegionBytes:(NSData *)attRegionBytes + tracksRegionBytes:(NSData *)tracksRegionBytes + tagsInsertBytes:(NSData *)tagsInsertBytes + attInsertBytes:(NSData *)attInsertBytes + newSegDataSize:(uint64_t)newSegDataSize + segSizeWidth:(NSUInteger)segSizeWidth + appendRel:(uint64_t)appendRel + error:(NSError **)outError +{ + int fd = open(_URL.fileSystemRepresentation, O_WRONLY); + if (fd < 0) { + if (outError) { + *outError = MkvError(MP42MkvErrorWriteFailed, @"Cannot open %@ for writing (%d)", _URL.lastPathComponent, errno); + } + return NO; + } + + BOOL ok = YES; + + if (ok && file.tags && tagsRegionBytes) { + ok = [self writeData:tagsRegionBytes fd:fd offset:file.tags.el.start error:outError]; + } + if (ok && file.attachments && attRegionBytes) { + ok = [self writeData:attRegionBytes fd:fd offset:file.attachments.el.start error:outError]; + } + if (ok && file.tracks && tracksRegionBytes) { + ok = [self writeData:tracksRegionBytes fd:fd offset:file.tracks.el.start error:outError]; + } + if (ok && attInsertBytes.length + tagsInsertBytes.length > 0) { + uint64_t cursor = file.segDataStart + appendRel; + if (attInsertBytes) { + ok = [self writeData:attInsertBytes fd:fd offset:cursor error:outError]; + cursor += attInsertBytes.length; + } + if (ok && tagsInsertBytes) { + ok = [self writeData:tagsInsertBytes fd:fd offset:cursor error:outError]; + } + } + if (ok && newSegDataSize != UINT64_MAX) { + NSMutableData *patch = [NSMutableData data]; + [MP42Ebml appendSize:newSegDataSize width:segSizeWidth to:patch]; + ok = [self writeData:patch fd:fd offset:file.segment.start + MP42MkvIdWidth(MP42MkvElementSegment) error:outError]; + } + + if (ok) { + fsync(fd); + } + close(fd); + + if (ok && self.progressHandler) { + self.progressHandler(1.0); + } + return ok; +} + +#pragma mark SeekHead / Cues rewriting + +- (NSData *)rebuildSeekHead:(NSData *)payload + map:(MP42MkvPosMapper)map // nil = identity, no drops + addTagsEntryRel:(uint64_t)addTagsRel // kMkvNoPosition = nothing to add + addAttachmentsEntryRel:(uint64_t)addAttRel + error:(NSError **)outError +{ + NSArray *kids = [MP42Ebml scanBuffer:payload from:0 length:MP42EbmlScanToEnd error:NULL]; + if (!kids) { + *outError = MkvError(MP42MkvErrorUnsupported, @"A SeekHead in %@ could not be parsed", _URL.lastPathComponent); + return nil; + } + + NSMutableData *out = [NSMutableData data]; + BOOL hasTagsEntry = NO, hasAttachmentsEntry = NO; + + for (MP42EbmlElement *seek in kids) { + if (seek.identifier != MP42MkvElementSeek || seek.sizeIsUnknown) { + [out appendData:MP42MkvBufferSlice(payload, seek, payload.length)]; + continue; + } + + NSArray *parts = [MP42Ebml scanBuffer:payload from:seek.dataStart length:seek.dataSize error:NULL]; + if (!parts) { + *outError = MkvError(MP42MkvErrorUnsupported, @"A Seek entry in %@ could not be parsed", _URL.lastPathComponent); + return nil; + } + + NSData *targetIDRaw = nil; + uint64_t position = 0; + NSMutableData *extras = [NSMutableData data]; + + for (MP42EbmlElement *part in parts) { + if (part.identifier == MP42MkvElementSeekID && !part.sizeIsUnknown && !targetIDRaw) { + targetIDRaw = [payload subdataWithRange:NSMakeRange((NSUInteger)part.dataStart, (NSUInteger)part.dataSize)]; + } else if (part.identifier == MP42MkvElementSeekPosition && !part.sizeIsUnknown) { + NSData *posData = [payload subdataWithRange:NSMakeRange((NSUInteger)part.dataStart, (NSUInteger)part.dataSize)]; + position = [MP42Ebml unsignedIntValueAt:posData.bytes length:posData.length]; + } else { + [extras appendData:MP42MkvBufferSlice(payload, part, payload.length)]; + } + } + + if (!targetIDRaw || targetIDRaw.length > 4) { + // Not a target we can reason about: preserve verbatim. + [out appendData:MP42MkvBufferSlice(payload, seek, payload.length)]; + continue; + } + + uint32_t targetID = [MP42Ebml idValueAt:targetIDRaw.bytes length:targetIDRaw.length]; + if (targetID == MP42MkvElementTags) { + hasTagsEntry = YES; + } else if (targetID == MP42MkvElementAttachments) { + hasAttachmentsEntry = YES; + } + + BOOL drop = NO; + uint64_t newPosition = map ? map(position, &drop) : position; + if (drop) { + continue; + } + + NSMutableData *seekPayload = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementSeekID payload:targetIDRaw to:seekPayload]; + NSMutableData *posData = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:newPosition width:8 to:posData]; + [MP42Ebml appendElement:MP42MkvElementSeekPosition payload:posData to:seekPayload]; + [seekPayload appendData:extras]; + [MP42Ebml appendElement:MP42MkvElementSeek payload:seekPayload to:out]; + } + + // Add index entries for elements we know exist now but are not indexed + // yet. Positions are relative to the segment data start; entries are + // fixed-width 8 so the SeekHead size is layout-independent. + if (addTagsRel != kMkvNoPosition && !hasTagsEntry) { + [out appendData:[self encodedSeekEntryForID:MP42MkvElementTags position:addTagsRel]]; + } + if (addAttRel != kMkvNoPosition && !hasAttachmentsEntry) { + [out appendData:[self encodedSeekEntryForID:MP42MkvElementAttachments position:addAttRel]]; + } + + return out; +} + +- (NSData *)encodedSeekEntryForID:(uint32_t)identifier position:(uint64_t)position +{ + NSMutableData *idData = [NSMutableData data]; + [MP42Ebml appendId:identifier to:idData]; + NSMutableData *posData = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:position width:8 to:posData]; + + NSMutableData *seekPayload = [NSMutableData data]; + [MP42Ebml appendElement:MP42MkvElementSeekID payload:idData to:seekPayload]; + [MP42Ebml appendElement:MP42MkvElementSeekPosition payload:posData to:seekPayload]; + return MP42MkvEncodedElement(MP42MkvElementSeek, seekPayload); +} + +- (NSData *)rebuildCues:(NSData *)payload + delta:(int64_t)delta + error:(NSError **)outError +{ + NSArray *kids = [MP42Ebml scanBuffer:payload from:0 length:MP42EbmlScanToEnd error:NULL]; + if (!kids) { + *outError = MkvError(MP42MkvErrorUnsupported, @"The Cues element in %@ could not be parsed", _URL.lastPathComponent); + return nil; + } + + NSMutableData *out = [NSMutableData data]; + + for (MP42EbmlElement *cuePoint in kids) { + if (cuePoint.identifier != MP42MkvElementCuePoint || cuePoint.sizeIsUnknown) { + [out appendData:MP42MkvBufferSlice(payload, cuePoint, payload.length)]; + continue; + } + + NSArray *parts = [MP42Ebml scanBuffer:payload from:cuePoint.dataStart length:cuePoint.dataSize error:NULL]; + if (!parts) { + *outError = MkvError(MP42MkvErrorUnsupported, @"A CuePoint in %@ could not be parsed", _URL.lastPathComponent); + return nil; + } + + NSMutableData *pointPayload = [NSMutableData data]; + for (MP42EbmlElement *part in parts) { + if (part.identifier == MP42MkvElementCueTrackPositions && !part.sizeIsUnknown) { + NSArray *subParts = [MP42Ebml scanBuffer:payload from:part.dataStart length:part.dataSize error:NULL]; + if (!subParts) { + *outError = MkvError(MP42MkvErrorUnsupported, @"A CueTrackPositions in %@ could not be parsed", _URL.lastPathComponent); + return nil; + } + + NSMutableData *positionsPayload = [NSMutableData data]; + for (MP42EbmlElement *sub in subParts) { + if (sub.identifier == MP42MkvElementCueClusterPosition && !sub.sizeIsUnknown) { + NSData *posData = [payload subdataWithRange:NSMakeRange((NSUInteger)sub.dataStart, (NSUInteger)sub.dataSize)]; + int64_t newValue = (int64_t)[MP42Ebml unsignedIntValueAt:posData.bytes length:posData.length] + delta; + if (newValue < 0) { + *outError = MkvError(MP42MkvErrorUnsupported, @"Corrupt Cues in %@ (position before segment start)", _URL.lastPathComponent); + return nil; + } + NSMutableData *fixed = [NSMutableData data]; + [MP42Ebml appendUnsignedInt:(uint64_t)newValue width:8 to:fixed]; + [MP42Ebml appendElement:MP42MkvElementCueClusterPosition payload:fixed to:positionsPayload]; + } else { + // CueTime stays, CueRelativePosition is cluster-relative + // and unaffected, track numbers and anything else raw. + [positionsPayload appendData:MP42MkvBufferSlice(payload, sub, payload.length)]; + } + } + [MP42Ebml appendElement:MP42MkvElementCueTrackPositions payload:positionsPayload to:pointPayload]; + } else { + [pointPayload appendData:MP42MkvBufferSlice(payload, part, payload.length)]; + } + } + [MP42Ebml appendElement:MP42MkvElementCuePoint payload:pointPayload to:out]; + } + + return out; +} + +#pragma mark Slow path + +- (BOOL)rewriteFile:(MP42EbmlScanner *)scanner + file:(MP42MkvFile *)file + newTagsPayload:(NSData *)newTags + tagsShouldExist:(BOOL)tagsShouldExist + newAttPayload:(NSData *)newAtt + attShouldExist:(BOOL)attShouldExist + newTracksPayload:(NSData *)newTracks + error:(NSError **)outError +{ + BOOL tagsRemove = file.tags && !tagsShouldExist; + BOOL tagsReplace = file.tags && tagsShouldExist && newTags != nil; + BOOL tagsInsert = !file.tags && tagsShouldExist; + BOOL attRemove = file.attachments && !attShouldExist; + BOOL attReplace = file.attachments && attShouldExist && newAtt != nil; + BOOL attInsert = !file.attachments && attShouldExist; + + // Inserted element bytes; order when appending: Attachments then Tags. + NSData *attInsertBytes = attInsert ? MP42MkvEncodedElement(MP42MkvElementAttachments, newAtt) : nil; + NSData *tagsInsertBytes = tagsInsert ? MP42MkvEncodedElement(MP42MkvElementTags, newTags) : nil; + uint64_t appendedTotal = attInsertBytes.length + tagsInsertBytes.length; + + // + // ---- Fast path attempt ---- + // + + // A removal with live SeekHead entries pointing at it would leave the + // entries dangling; that needs the slow path's entry rewriting. + BOOL removalNeedsSeekHeads = + (tagsRemove && [self seekHeadsReferenceElement:MP42MkvElementTags file:file]) || + (attRemove && [self seekHeadsReferenceElement:MP42MkvElementAttachments file:file]); + + BOOL fast = !removalNeedsSeekHeads; + NSData *tagsRegionBytes = nil, *attRegionBytes = nil, *tracksRegionBytes = nil; + + if (fast && tagsReplace) { + fast = [self buildFastRegionForKid:file.tags newPayload:newTags removed:NO file:file outBytes:&tagsRegionBytes]; + } + if (fast && tagsRemove) { + fast = [self buildFastRegionForKid:file.tags newPayload:nil removed:YES file:file outBytes:&tagsRegionBytes]; + } + if (fast && attReplace) { + fast = [self buildFastRegionForKid:file.attachments newPayload:newAtt removed:NO file:file outBytes:&attRegionBytes]; + } + if (fast && attRemove) { + fast = [self buildFastRegionForKid:file.attachments newPayload:nil removed:YES file:file outBytes:&attRegionBytes]; + } + if (fast && newTracks) { + // Tracks is never inserted or removed, only replaced. + fast = [self buildFastRegionForKid:file.tracks newPayload:newTracks removed:NO file:file outBytes:&tracksRegionBytes]; + } + + // Append-insertions are also in-place when the segment size stays + // patchable at its current width and nothing depends on the old EOF. + uint64_t appendRel = 0; + uint64_t fastNewSegSize = UINT64_MAX; + NSUInteger fastSegSizeWidth = 0; + + if (fast && appendedTotal > 0) { + MP42MkvKid *lastKid = file.kids.lastObject; + if (file.segmentSizeUnknown || lastKid.el.sizeIsUnknown) { + fast = NO; + } else { + appendRel = lastKid.relStart + lastKid.oldTotal; + // Trailing zero padding inside the segment is overwritten. + fastNewSegSize = appendRel + appendedTotal; + NSUInteger segIdW = MP42MkvIdWidth(MP42MkvElementSegment); + NSUInteger oldSegSizeW = file.segment.headerSize - segIdW; + if ([MP42Ebml encodedLengthForSizeValue:fastNewSegSize] > oldSegSizeW) { + fast = NO; + } else { + fastSegSizeWidth = oldSegSizeW; + } + } + } + + if (fast) { + return [self fastPathWriteFile:file + tagsRegionBytes:tagsRegionBytes + attRegionBytes:attRegionBytes + tracksRegionBytes:tracksRegionBytes + tagsInsertBytes:tagsInsertBytes + attInsertBytes:attInsertBytes + newSegDataSize:fastNewSegSize + segSizeWidth:fastSegSizeWidth + appendRel:appendRel + error:outError]; + } + + // + // ---- Slow path ---- + // + + // Rewriting Cues that precede the first cluster would need a recursive + // position fixup; no real muxer does this, so refuse instead. + if (file.firstCluster) { + for (MP42MkvKid *kid in file.cues) { + if (kid.relStart < file.firstCluster.relStart) { + *outError = MkvError(MP42MkvErrorUnsupported, + @"%@ has Cues before its first Cluster; tagging it is not supported", + _URL.lastPathComponent); + return NO; + } + } + } + + if (file.tags) { + if (tagsReplace) { + file.tags.pendingPayload = newTags; + } else if (tagsRemove) { + file.tags.removed = YES; + } + } + if (file.attachments) { + if (attReplace) { + file.attachments.pendingPayload = newAtt; + } else if (attRemove) { + file.attachments.removed = YES; + } + } + if (file.tracks && newTracks) { + file.tracks.pendingPayload = newTracks; + } + + if (appendedTotal > 0) { + MP42MkvKid *lastKid = file.kids.lastObject; + if (lastKid.el.sizeIsUnknown) { + lastKid.materializeUnknown = YES; // must bound the region we append after + } + } + + BOOL tagsExistNow = (file.tags && !file.tags.removed) || tagsInsert; + BOOL attachmentsExistNow = (file.attachments && !file.attachments.removed) || attInsert; + + // SeekHead pass 1: positions are placeholders, but the entry *set* is + // already final — entries for removed elements drop in both passes, and + // entries are added/omitted by the same flags — so the SeekHead size + // (fixed-width 8 positions) computed here is the size used for layout. + MP42MkvFile *planRef = file; + MP42MkvPosMapper dropOnlyMapper = ^uint64_t(uint64_t P, BOOL *drop) { + for (MP42MkvKid *k in planRef.kids) { + if (k.relStart <= P && P < k.relStart + k.oldTotal) { + if (k.removed && drop) { + *drop = YES; + } + break; + } + } + return P; + }; + + BOOL firstSeekHead = YES; + for (MP42MkvKid *kid in file.seekHeads) { + NSData *rebuilt = [self rebuildSeekHead:kid.payload + map:dropOnlyMapper + addTagsEntryRel:(firstSeekHead && tagsExistNow) ? 0 : kMkvNoPosition + addAttachmentsEntryRel:(firstSeekHead && attachmentsExistNow) ? 0 : kMkvNoPosition + error:outError]; + if (!rebuilt) { + return NO; + } + kid.pendingPayload = rebuilt; + firstSeekHead = NO; + } + + // Clusters shift by the net size change of everything before them; only + // then do Cues need rewriting. + int64_t deltaClusters = 0; + if (file.firstCluster) { + for (MP42MkvKid *kid in file.kids) { + if (kid.relStart >= file.firstCluster.relStart) { + break; + } + deltaClusters += (int64_t)MP42MkvKidNewTotal(kid) - (int64_t)kid.oldTotal; + } + } + if (deltaClusters != 0) { + for (MP42MkvKid *kid in file.cues) { + kid.pendingPayload = [self rebuildCues:kid.payload delta:deltaClusters error:outError]; + if (!kid.pendingPayload) { + return NO; + } + } + } + + // Layout pass: assign plan-domain starts (relative to data start). + uint64_t cur = 0; + for (MP42MkvKid *kid in file.kids) { + kid.newStart = cur; + cur += MP42MkvKidNewTotal(kid); + } + uint64_t attAppendRel = kMkvNoPosition, tagsAppendRel = kMkvNoPosition; + if (attInsertBytes) { + attAppendRel = cur; + cur += attInsertBytes.length; + } + if (tagsInsertBytes) { + tagsAppendRel = cur; + cur += tagsInsertBytes.length; + } + uint64_t childrenEnd = cur; + + // Position mapper over the finished layout. + MP42MkvFile *fileRef = file; + MP42MkvPosMapper mapper = ^uint64_t(uint64_t P, BOOL *drop) { + MP42MkvKid *containing = nil; + for (MP42MkvKid *k in fileRef.kids) { + if (k.relStart <= P) { + containing = k; + } else { + break; + } + } + if (!containing || P >= containing.relStart + containing.oldTotal) { + return P; // points into padding we keep out of the math + } + if (containing.removed) { + if (drop) { + *drop = YES; + } + return 0; + } + return containing.newStart + (P - containing.relStart); + }; + + // SeekHead pass 2: real positions. Byte-identical in size to pass 1. + firstSeekHead = YES; + for (MP42MkvKid *kid in file.seekHeads) { + NSData *rebuilt = [self rebuildSeekHead:kid.payload + map:mapper + addTagsEntryRel:(firstSeekHead && tagsExistNow) + ? (file.tags ? file.tags.newStart : tagsAppendRel) : kMkvNoPosition + addAttachmentsEntryRel:(firstSeekHead && attachmentsExistNow) + ? (file.attachments ? file.attachments.newStart : attAppendRel) : kMkvNoPosition + error:outError]; + if (!rebuilt) { + return NO; + } + kid.pendingPayload = rebuilt; + firstSeekHead = NO; + } + + // Segment header. + NSUInteger segIdW = MP42MkvIdWidth(MP42MkvElementSegment); + NSUInteger oldSegSizeW = file.segment.headerSize - segIdW; + uint64_t newSegDataSize = childrenEnd; + NSUInteger newSegSizeW = file.segmentSizeUnknown + ? [MP42Ebml encodedLengthForSizeValue:newSegDataSize] + : MAX(oldSegSizeW, [MP42Ebml encodedLengthForSizeValue:newSegDataSize]); + if (newSegSizeW > 8) { + *outError = MkvError(MP42MkvErrorUnsupported, @"%@ would grow past the largest addressable segment", _URL.lastPathComponent); + return NO; + } + NSInteger k = (NSInteger)(segIdW + newSegSizeW) - (NSInteger)file.segment.headerSize; + BOOL segHdrChanged = (newSegDataSize != file.segDataLen) || file.segmentSizeUnknown || k != 0; + + // First byte (plan-domain) that actually changes; everything before is + // copied verbatim. + uint64_t splitPoint = k != 0 ? 0 : UINT64_MAX; + for (MP42MkvKid *kid in file.kids) { + // Anything rewritten, removed, resized or materialized must lie at + // or after the split point, even when its size happens to be + // unchanged (a rewritten SeekHead of identical length still carries + // new positions and must not be skipped by the prefix copy). + if (kid.removed || kid.materializeUnknown || kid.pendingPayload != nil || + MP42MkvKidNewTotal(kid) != kid.oldTotal) { + splitPoint = MIN(splitPoint, kid.relStart); + } + } + if (appendedTotal > 0) { + splitPoint = MIN(splitPoint, childrenEnd - appendedTotal); + } + if (splitPoint == UINT64_MAX) { + splitPoint = 0; // should not happen; be conservative + } + + // + // ---- Emit ---- + // + + struct stat origStat; + if (stat(_URL.fileSystemRepresentation, &origStat) != 0) { + *outError = MkvError(MP42MkvErrorStaleFile, @"Cannot stat %@", _URL.lastPathComponent); + return NO; + } + + NSString *directory = _URL.URLByDeletingLastPathComponent.path; + NSString *tmpName = [NSString stringWithFormat:@".%@.subler-%u.tmp", + _URL.lastPathComponent, (unsigned)arc4random_uniform(UINT32_MAX)]; + NSString *tmpPath = [directory stringByAppendingPathComponent:tmpName]; + + int outFd = open([tmpPath fileSystemRepresentation], O_RDWR | O_CREAT | O_TRUNC, origStat.st_mode & 0777); + if (outFd < 0) { + *outError = MkvError(MP42MkvErrorWriteFailed, @"Cannot create %@ (%d)", tmpName, errno); + return NO; + } + + uint64_t outputSize = (uint64_t)file.segment.start + (segHdrChanged ? (segIdW + newSegSizeW) : file.segment.headerSize) + newSegDataSize; + BOOL ok = YES; + + // Single sequential output cursor. + uint64_t outCursor = 0; + + if (segHdrChanged) { + // Bytes before the Segment element are always identity-copied. + ok = [self copyFromScanner:scanner source:0 length:file.segment.start toFD:outFd outOffset:&outCursor totalEstimate:outputSize error:outError]; + if (ok) { + NSMutableData *header = [NSMutableData data]; + [MP42Ebml appendId:MP42MkvElementSegment to:header]; + [MP42Ebml appendSize:newSegDataSize width:newSegSizeW to:header]; + ok = [self appendData:header toFD:outFd outOffset:&outCursor error:outError]; + } + // Unchanged segment-data prefix, if any. + if (ok && splitPoint > 0) { + ok = [self copyFromScanner:scanner source:file.segDataStart length:splitPoint toFD:outFd outOffset:&outCursor totalEstimate:outputSize error:outError]; + } + } else { + // EBML header, segment header, and unchanged data prefix in one pass. + ok = [self copyFromScanner:scanner source:0 length:file.segDataStart + splitPoint toFD:outFd outOffset:&outCursor totalEstimate:outputSize error:outError]; + } + + if (ok) { + uint64_t cursorRel = splitPoint; // cursor in the OLD file, plan domain + for (MP42MkvKid *kid in file.kids) { + uint64_t kidOldEnd = kid.relStart + kid.oldTotal; + if (kidOldEnd <= splitPoint) { + continue; + } + + if (kid.relStart > cursorRel) { + ok = [self copyFromScanner:scanner + source:file.segDataStart + cursorRel + length:kid.relStart - cursorRel + toFD:outFd + outOffset:&outCursor + totalEstimate:outputSize + error:outError]; + if (!ok) break; + } + + if (kid.removed) { + // disappears entirely + } else if (kid.pendingPayload) { + NSData *element = MP42MkvEncodedElement(kid.el.identifier, kid.pendingPayload); + ok = [self appendData:element toFD:outFd outOffset:&outCursor error:outError]; + } else if (kid.materializeUnknown) { + NSMutableData *header = [NSMutableData data]; + [MP42Ebml appendId:kid.el.identifier to:header]; + [MP42Ebml appendSize:kid.el.dataSize to:header]; + ok = [self appendData:header toFD:outFd outOffset:&outCursor error:outError]; + if (ok) { + ok = [self copyFromScanner:scanner + source:file.segDataStart + kid.relStart + kid.el.headerSize + length:kid.el.dataSize + toFD:outFd + outOffset:&outCursor + totalEstimate:outputSize + error:outError]; + } + } else { + ok = [self copyFromScanner:scanner + source:file.segDataStart + kid.relStart + length:kid.oldTotal + toFD:outFd + outOffset:&outCursor + totalEstimate:outputSize + error:outError]; + } + + if (!ok) break; + cursorRel = kidOldEnd; + } + + if (ok && attInsertBytes) { + ok = [self appendData:attInsertBytes toFD:outFd outOffset:&outCursor error:outError]; + } + if (ok && tagsInsertBytes) { + ok = [self appendData:tagsInsertBytes toFD:outFd outOffset:&outCursor error:outError]; + } + } + + if (ok) { + if (fsync(outFd) != 0) { + *outError = MkvError(MP42MkvErrorWriteFailed, @"fsync failed (%d)", errno); + ok = NO; + } + } + close(outFd); + + if (!ok) { + unlink([tmpPath fileSystemRepresentation]); + return NO; + } + + // The source may have changed while we were writing. + if (![self checkStalenessWithError:outError]) { + unlink([tmpPath fileSystemRepresentation]); + return NO; + } + + NSURL *tmpURL = [NSURL fileURLWithPath:tmpPath]; + NSURL *resultingURL = nil; + NSError *replaceError = nil; + if (![[NSFileManager defaultManager] replaceItemAtURL:_URL + withItemAtURL:tmpURL + backupItemName:nil + options:0 + resultingItemURL:&resultingURL + error:&replaceError]) { + unlink([tmpPath fileSystemRepresentation]); + if (outError) { + *outError = replaceError ?: MkvError(MP42MkvErrorWriteFailed, @"Could not replace %@", _URL.lastPathComponent); + } + return NO; + } + + if (self.progressHandler) { + self.progressHandler(1.0); + } + return YES; +} + +@end diff --git a/MP42/MP42Track+Private.h b/MP42/MP42Track+Private.h index adcae26..c645d47 100644 --- a/MP42/MP42Track+Private.h +++ b/MP42/MP42Track+Private.h @@ -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; diff --git a/MP42/MP42Track.h b/MP42/MP42Track.h index 7e9be72..5d65f08 100644 --- a/MP42/MP42Track.h +++ b/MP42/MP42Track.h @@ -21,7 +21,11 @@ NS_ASSUME_NONNULL_BEGIN */ @interface MP42Track : NSObject -@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; diff --git a/MP42/MP42Track.m b/MP42/MP42Track.m index dd384a3..d3b6991 100644 --- a/MP42/MP42Track.m +++ b/MP42/MP42Track.m @@ -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; diff --git a/MP42/muxer/MatroskaParser.c b/MP42/muxer/MatroskaParser.c index fd86d26..7578258 100644 --- a/MP42/muxer/MatroskaParser.c +++ b/MP42/muxer/MatroskaParser.c @@ -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 diff --git a/MP42Foundation.xcodeproj/project.pbxproj b/MP42Foundation.xcodeproj/project.pbxproj index ca6c4ee..252f1d6 100644 --- a/MP42Foundation.xcodeproj/project.pbxproj +++ b/MP42Foundation.xcodeproj/project.pbxproj @@ -62,6 +62,18 @@ A910B60318394EB20064028F /* MP42H264Importer.mm in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2351823923100416A4E /* MP42H264Importer.mm */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-checker"; }; }; A910B60518394EB20064028F /* MP42VobSubImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2571823923200416A4E /* MP42VobSubImporter.m */; }; A910B60718394EB20064028F /* MP42MkvImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C23F1823923100416A4E /* MP42MkvImporter.m */; }; + 5AB1E120261124000000000007 /* MP42Ebml.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000001 /* MP42Ebml.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5AB1E120261124000000000008 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; }; + 5AB1E120261124000000000009 /* MP42Ebml.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000002 /* MP42Ebml.m */; }; + 5AB1E120261124000000000010 /* MP42MatroskaTagMapping.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5AB1E120261124000000000011 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; }; + 5AB1E120261124000000000012 /* MP42MatroskaTagMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */; }; + 5AB1E120261124000000000013 /* MP42MkvTagWriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000005 /* MP42MkvTagWriter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5AB1E120261124000000000014 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; }; + 5AB1E120261124000000000015 /* MP42MkvTagWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */; }; + 5AB1E120261124000000000024 /* MP42MkvRemuxer.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000021 /* MP42MkvRemuxer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5AB1E120261124000000000025 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; }; + 5AB1E120261124000000000026 /* MP42MkvRemuxer.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */; }; A910B60918394EB20064028F /* MP42Mp4Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2411823923100416A4E /* MP42Mp4Importer.m */; }; A910B60D18394EB20064028F /* MP42SrtImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C24B1823923100416A4E /* MP42SrtImporter.m */; }; A910B60F18394EB20064028F /* MP42AVFImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = A9B9C2241823923100416A4E /* MP42AVFImporter.m */; }; @@ -401,6 +413,15 @@ A9B9C23D1823923100416A4E /* MP42Metadata.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Metadata.m; sourceTree = ""; }; A9B9C23E1823923100416A4E /* MP42MkvImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvImporter.h; sourceTree = ""; }; A9B9C23F1823923100416A4E /* MP42MkvImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvImporter.m; sourceTree = ""; }; + 5AB1E120261124000000000001 /* MP42Ebml.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Ebml.h; sourceTree = ""; }; + 5AB1E120261124000000000002 /* MP42Ebml.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Ebml.m; sourceTree = ""; }; + 5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MatroskaTagMapping.h; sourceTree = ""; }; + 5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MatroskaTagMapping.m; sourceTree = ""; }; + 5AB1E120261124000000000005 /* MP42MkvTagWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvTagWriter.h; sourceTree = ""; }; + 5AB1E120261124000000000006 /* MP42MkvTagWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvTagWriter.m; sourceTree = ""; }; + 5AB1E120261124000000000021 /* MP42MkvRemuxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvRemuxer.h; sourceTree = ""; }; + 5AB1E120261124000000000022 /* MP42MkvRemuxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvRemuxer.m; sourceTree = ""; }; + 5AB1E120261124000000000023 /* MP42MkvTagWriter+Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MP42MkvTagWriter+Internal.h"; sourceTree = ""; }; A9B9C2401823923100416A4E /* MP42Mp4Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Mp4Importer.h; sourceTree = ""; }; A9B9C2411823923100416A4E /* MP42Mp4Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Mp4Importer.m; sourceTree = ""; }; A9B9C2421823923100416A4E /* MP42Muxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Muxer.h; sourceTree = ""; }; @@ -687,6 +708,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 */, @@ -883,6 +913,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 */, ); @@ -1042,6 +1076,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 */, @@ -1099,6 +1137,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 */,