Add Matroska tagging and track-removal support
- MP42Ebml: EBML vint/ID primitives, flat Segment scanner, block track number decoding, and element builders shared by all Matroska writers. - MP42MkvImporter / MP42FileImporter: tagsOnly mode that mirrors the file's own track flags instead of the MP4 conversion heuristics. - MP42MatroskaTagMapping: read/write SimpleTag maps shared by importer and writer, including community names for MP4-only movie fields. - MP42MkvTagWriter: mkvpropedit-style in-place rewrite of Tags, cover art, and per-track name/language/enabled/forced fields with a size+mtime staleness guard; an untouched save is a byte-for-byte no-op. - MP42MkvRemuxer: stream-copy rebuild that drops the blocks of removed tracks (TrackNumbers keep their gaps; block bytes are never rewritten), regenerates SeekHead and Cues, carries metadata edits in the same pass, and writes via temp file + atomic rename. - MP42MkvTagWriter+Internal.h exposes the tag writer's scanning and payload builders so the remuxer reuses them unchanged. Verified with the external matrix harness: 241 assertions green across layout fixtures (ffmpeg/mkvmerge/streamed), removal scenarios, cue parity, and idempotency. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
bfa477b799
commit
1040f47542
18 files changed
+4397
-86
No files matched your search
+133
@@ -0,0 +1,133 @@
|
||||
//
|
||||
// MP42Ebml.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Minimal EBML (Extensible Binary Meta Language) primitives: variable-size
|
||||
// integer coding, flat element scanning over a file descriptor, and element
|
||||
// serialization helpers. Sufficient to read and rewrite the metadata-side
|
||||
// elements of Matroska files (Tags, Attachments, SeekHead, Cues, Void); it
|
||||
// deliberately knows nothing about track/cluster payload contents.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
FOUNDATION_EXPORT NSErrorDomain const MP42MkvErrorDomain;
|
||||
|
||||
typedef NS_ERROR_ENUM(MP42MkvErrorDomain, MP42MkvError) {
|
||||
MP42MkvErrorParse = 1, // malformed / truncated EBML structure
|
||||
MP42MkvErrorUnsupported = 2, // layout we refuse to rewrite (multiple segments, stray unknown sizes…)
|
||||
MP42MkvErrorStaleFile = 3, // file changed on disk since it was opened
|
||||
MP42MkvErrorWriteFailed = 4,
|
||||
MP42MkvErrorCancelled = 5,
|
||||
};
|
||||
|
||||
// Pass as the `length` argument of -scanChildrenFrom:length: to scan to the
|
||||
// end of the file.
|
||||
FOUNDATION_EXPORT const uint64_t MP42EbmlScanToEnd;
|
||||
|
||||
// One EBML element header + extent found by a flat scan.
|
||||
@interface MP42EbmlElement : NSObject
|
||||
|
||||
@property (nonatomic) uint32_t identifier; // raw ID, marker bit included
|
||||
@property (nonatomic) uint64_t start; // absolute offset of the first ID byte
|
||||
@property (nonatomic) uint64_t headerSize; // ID bytes + size vint bytes
|
||||
@property (nonatomic) uint64_t dataSize; // decoded payload length
|
||||
@property (nonatomic) BOOL sizeIsUnknown; // unknown-size vint: payload runs to parent end
|
||||
|
||||
- (uint64_t)dataStart; // start + headerSize
|
||||
- (uint64_t)end; // only meaningful when !sizeIsUnknown
|
||||
|
||||
// Total extent (header + payload) of a known-size element.
|
||||
- (uint64_t)totalSize;
|
||||
|
||||
@end
|
||||
|
||||
@interface MP42EbmlScanner : NSObject
|
||||
|
||||
@property (nonatomic, readonly) uint64_t fileSize;
|
||||
|
||||
// Opens the file at URL for reading. The scanner owns the descriptor; call
|
||||
// -close when done (also called from dealloc).
|
||||
+ (nullable instancetype)scannerWithURL:(NSURL *)URL error:(NSError * _Nullable *)outError;
|
||||
- (void)close;
|
||||
|
||||
- (nullable NSData *)readAtOffset:(uint64_t)offset
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Flat scan of direct children covering [start, start+length) (or to EOF for
|
||||
// MP42EbmlScanToEnd). Elements are returned in file order; payloads are not
|
||||
// descended into. An element with an unknown-size vint consumes the rest of
|
||||
// the region and terminates the scan — callers must only tolerate that for
|
||||
// trailing elements (clusters in streamed files).
|
||||
//
|
||||
// Returns nil (and sets *outError) on malformed or truncated data. Runs of
|
||||
// 0x00 padding are treated as end-of-structure, not an error.
|
||||
- (nullable NSArray<MP42EbmlElement *> *)scanChildrenFrom:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
@end
|
||||
|
||||
//
|
||||
// EBML vint primitives and element builders (all class methods, no I/O).
|
||||
//
|
||||
@interface MP42Ebml : NSObject
|
||||
|
||||
+ (NSError *)errorWithCode:(MP42MkvError)code message:(NSString *)format, ... NS_FORMAT_FUNCTION(2, 3);
|
||||
|
||||
// Size vints: marker bit is stripped from the value. An all-ones value bits
|
||||
// pattern decodes as "unknown size".
|
||||
|
||||
// Returns the byte length of the size vint at buf (1...8), or 0 if the
|
||||
// leading byte is invalid or `available` is too small.
|
||||
+ (NSUInteger)sizeVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available;
|
||||
// Decodes a size vint of the given length. Sets *unknown for all-ones values.
|
||||
+ (uint64_t)sizeVintValueAt:(const uint8_t *)buf length:(NSUInteger)length unknown:(nullable BOOL *)unknown;
|
||||
// Canonical minimal width for encoding a size value.
|
||||
+ (NSUInteger)encodedLengthForSizeValue:(uint64_t)value;
|
||||
|
||||
// ID vints: the marker bit is part of the ID value.
|
||||
+ (NSUInteger)idVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available;
|
||||
+ (uint32_t)idValueAt:(const uint8_t *)buf length:(NSUInteger)length;
|
||||
|
||||
// Block-header track number: an "unmarked" vint whose marker bit only codes
|
||||
// the length. Returns the bytes consumed (0 when invalid/truncated) and the
|
||||
// decoded value in *outValue.
|
||||
+ (NSUInteger)blockTrackNumberAt:(const uint8_t *)buf available:(NSUInteger)available value:(nullable uint32_t *)outValue;
|
||||
|
||||
// Unsigned integer element payloads (SeekPosition, CueClusterPosition…).
|
||||
+ (uint64_t)unsignedIntValueAt:(const uint8_t *)buf length:(NSUInteger)length;
|
||||
|
||||
// Appends a size vint using the canonical minimal width.
|
||||
+ (void)appendSize:(uint64_t)value to:(NSMutableData *)data;
|
||||
// Appends a size vint at a fixed width (width must be >= canonical width).
|
||||
+ (void)appendSize:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data;
|
||||
// Appends an unknown-size vint of the given width (1...8).
|
||||
+ (void)appendUnknownSizeOfWidth:(NSUInteger)width to:(NSMutableData *)data;
|
||||
|
||||
+ (void)appendId:(uint32_t)identifier to:(NSMutableData *)data;
|
||||
+ (void)appendUnsignedInt:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data;
|
||||
|
||||
// Complete elements.
|
||||
+ (void)appendElement:(uint32_t)identifier payload:(nullable NSData *)payload to:(NSMutableData *)data;
|
||||
+ (void)appendStringElement:(uint32_t)identifier string:(NSString *)string to:(NSMutableData *)data;
|
||||
+ (void)appendVoidOfLength:(uint64_t)length to:(NSMutableData *)data;
|
||||
|
||||
// Flat scan of direct children inside an in-memory buffer, mirroring
|
||||
// -[MP42EbmlScanner scanChildrenFrom:length: semantics]. Returned elements
|
||||
// carry offsets relative to the buffer's own byte 0.
|
||||
+ (nullable NSArray<MP42EbmlElement *> *)scanBuffer:(NSData *)buffer
|
||||
from:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Where an element's payload ends within a region, tolerating the
|
||||
// truncated/unknown-size case: min(payload end or region end).
|
||||
+ (uint64_t)payloadEndForElement:(MP42EbmlElement *)element regionEnd:(uint64_t)regionEnd;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
//
|
||||
// MP42Ebml.m
|
||||
// MP42Foundation
|
||||
//
|
||||
|
||||
#import "MP42Ebml.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
|
||||
NSErrorDomain const MP42MkvErrorDomain = @"org.galad.MP42Foundation.Matroska";
|
||||
|
||||
const uint64_t MP42EbmlScanToEnd = UINT64_MAX;
|
||||
|
||||
@implementation MP42EbmlElement
|
||||
|
||||
- (uint64_t)dataStart
|
||||
{
|
||||
return self.start + self.headerSize;
|
||||
}
|
||||
|
||||
- (uint64_t)end
|
||||
{
|
||||
NSAssert(!self.sizeIsUnknown, @"unknown-size element has no end");
|
||||
return [self dataStart] + self.dataSize;
|
||||
}
|
||||
|
||||
- (uint64_t)totalSize
|
||||
{
|
||||
return self.headerSize + self.dataSize;
|
||||
}
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ 0x%x start=%llu hdr=%llu size=%@>",
|
||||
NSStringFromClass(self.class), self.identifier, self.start, self.headerSize,
|
||||
self.sizeIsUnknown ? @"UNKNOWN" : @(self.dataSize).stringValue];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42Ebml
|
||||
|
||||
+ (NSError *)errorWithCode:(MP42MkvError)code message:(NSString *)format, ...
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
|
||||
va_end(args);
|
||||
|
||||
return [NSError errorWithDomain:MP42MkvErrorDomain
|
||||
code:code
|
||||
userInfo:@{ NSLocalizedDescriptionKey: message }];
|
||||
}
|
||||
|
||||
#pragma mark - vints
|
||||
|
||||
+ (NSUInteger)vintLengthAt:(const uint8_t *)buf available:(NSUInteger)available max:(NSUInteger)max
|
||||
{
|
||||
if (available == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t first = buf[0];
|
||||
for (NSUInteger len = 1; len <= max; len++) {
|
||||
if (first & (0x80 >> (len - 1))) {
|
||||
return len <= available ? len : 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
+ (NSUInteger)sizeVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available
|
||||
{
|
||||
return [self vintLengthAt:buf available:available max:8];
|
||||
}
|
||||
|
||||
+ (uint64_t)sizeVintValueAt:(const uint8_t *)buf length:(NSUInteger)length unknown:(BOOL *)unknown
|
||||
{
|
||||
uint64_t value = 0;
|
||||
for (NSUInteger i = 0; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
|
||||
// Strip the marker bit: it is the high bit of the leading byte, i.e.
|
||||
// (0x80 >> (length-1)) shifted up to the top of a `length`-byte value.
|
||||
value &= ~(((uint64_t)(0x80 >> (length - 1))) << (8 * (length - 1)));
|
||||
|
||||
if (unknown) {
|
||||
// All value bits set == "unknown size"
|
||||
*unknown = value == ((uint64_t)1 << (7 * length)) - 1;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
+ (NSUInteger)encodedLengthForSizeValue:(uint64_t)value
|
||||
{
|
||||
for (NSUInteger width = 1; width <= 8; width++) {
|
||||
// width w encodes values 0 ... 2^(7w)-2; all-ones means "unknown".
|
||||
if (7 * width < 64 && value < ((uint64_t)1 << (7 * width)) - 1) {
|
||||
return width;
|
||||
}
|
||||
}
|
||||
return 8;
|
||||
}
|
||||
|
||||
+ (NSUInteger)idVintLengthAt:(const uint8_t *)buf available:(NSUInteger)available
|
||||
{
|
||||
return [self vintLengthAt:buf available:available max:4];
|
||||
}
|
||||
|
||||
+ (uint32_t)idValueAt:(const uint8_t *)buf length:(NSUInteger)length
|
||||
{
|
||||
uint32_t value = 0;
|
||||
for (NSUInteger i = 0; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
return value; // marker bit stays part of the ID
|
||||
}
|
||||
|
||||
+ (NSUInteger)blockTrackNumberAt:(const uint8_t *)buf available:(NSUInteger)available value:(uint32_t *)outValue
|
||||
{
|
||||
// Block headers open with an "unmarked" vint: same leading-zero length
|
||||
// coding as IDs/sizes, but the length-marker bit is NOT part of the
|
||||
// value (this is what MatroskaParser.c's readVLUInt decodes).
|
||||
NSUInteger length = [self vintLengthAt:buf available:available max:8];
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
uint32_t value = (uint32_t)(buf[0] & (0xFF >> length));
|
||||
for (NSUInteger i = 1; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
if (outValue) {
|
||||
*outValue = value;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
+ (uint64_t)unsignedIntValueAt:(const uint8_t *)buf length:(NSUInteger)length
|
||||
{
|
||||
uint64_t value = 0;
|
||||
// Per the spec, integers are at most 8 bytes; be tolerant of longer.
|
||||
NSUInteger start = length > 8 ? length - 8 : 0;
|
||||
for (NSUInteger i = start; i < length; i++) {
|
||||
value = (value << 8) | buf[i];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
#pragma mark - encoding
|
||||
|
||||
+ (void)appendSize:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
uint64_t encoded = value | ((uint64_t)1 << (7 * width));
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(encoded >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendSize:(uint64_t)value to:(NSMutableData *)data
|
||||
{
|
||||
[self appendSize:value width:[self encodedLengthForSizeValue:value] to:data];
|
||||
}
|
||||
|
||||
+ (void)appendUnknownSizeOfWidth:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
// Value bits all ones, marker set: 0xFF, 0x7FFF, 0x3FFFFF, …
|
||||
[self appendSize:((uint64_t)1 << (7 * width)) - 1 width:width to:data];
|
||||
}
|
||||
|
||||
+ (void)appendId:(uint32_t)identifier to:(NSMutableData *)data
|
||||
{
|
||||
NSUInteger width = 0;
|
||||
if (identifier >= 0x10000000u) {
|
||||
width = 4;
|
||||
} else if (identifier >= 0x200000u) {
|
||||
width = 3;
|
||||
} else if (identifier >= 0x4000u) {
|
||||
width = 2;
|
||||
} else if (identifier >= 0x80u) {
|
||||
width = 1;
|
||||
} else {
|
||||
NSCAssert(NO, @"invalid element identifier 0x%x", identifier);
|
||||
return;
|
||||
}
|
||||
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(identifier >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendUnsignedInt:(uint64_t)value width:(NSUInteger)width to:(NSMutableData *)data
|
||||
{
|
||||
for (NSUInteger i = width; i > 0; i--) {
|
||||
uint8_t byte = (uint8_t)(value >> (8 * (i - 1)));
|
||||
[data appendBytes:&byte length:1];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)appendElement:(uint32_t)identifier payload:(NSData *)payload to:(NSMutableData *)data
|
||||
{
|
||||
[self appendId:identifier to:data];
|
||||
[self appendSize:payload.length to:data];
|
||||
[data appendData:payload];
|
||||
}
|
||||
|
||||
+ (void)appendStringElement:(uint32_t)identifier string:(NSString *)string to:(NSMutableData *)data
|
||||
{
|
||||
[self appendElement:identifier payload:[string dataUsingEncoding:NSUTF8StringEncoding] to:data];
|
||||
}
|
||||
|
||||
+ (void)appendVoidOfLength:(uint64_t)length to:(NSMutableData *)data
|
||||
{
|
||||
NSCAssert(length >= 2, @"cannot build a Void element shorter than 2 bytes");
|
||||
if (length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
// total = 1 (ID) + width (size vint) + payload zeros
|
||||
for (NSUInteger width = 1; width <= 8; width++) {
|
||||
if (width > length - 1) {
|
||||
break;
|
||||
}
|
||||
uint64_t payload = length - 1 - width;
|
||||
if ([self encodedLengthForSizeValue:payload] <= width) {
|
||||
uint8_t voidId = 0xEC;
|
||||
[data appendBytes:&voidId length:1];
|
||||
[self appendSize:payload width:width to:data]; // non-minimal width allowed
|
||||
if (payload > 0) {
|
||||
NSMutableData *zeros = [NSMutableData dataWithLength:(NSUInteger)payload];
|
||||
[data appendData:zeros];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
NSCAssert(NO, @"no Void encoding fits %llu bytes", length);
|
||||
}
|
||||
|
||||
#pragma mark - buffer scanning
|
||||
|
||||
+ (NSArray<MP42EbmlElement *> *)scanBuffer:(NSData *)buffer
|
||||
from:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError **)outError
|
||||
{
|
||||
if (start > buffer.length) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse message:@"Buffer scan past end of data"];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
uint64_t end = (length == MP42EbmlScanToEnd) ? buffer.length : MIN(start + length, buffer.length);
|
||||
const uint8_t *bytes = buffer.bytes;
|
||||
|
||||
NSMutableArray<MP42EbmlElement *> *elements = [NSMutableArray array];
|
||||
uint64_t cursor = start;
|
||||
|
||||
while (cursor < end) {
|
||||
NSUInteger avail = (NSUInteger)MIN((uint64_t)12, end - cursor);
|
||||
|
||||
if (bytes[cursor] == 0x00) {
|
||||
break; // zero padding ends the structure
|
||||
}
|
||||
|
||||
NSUInteger idLen = [self idVintLengthAt:bytes + cursor available:avail];
|
||||
if (idLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element ID at offset %llu", cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUInteger sizeLen = [self sizeVintLengthAt:bytes + cursor + idLen available:avail - idLen];
|
||||
if (sizeLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element size at offset %llu", cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
BOOL unknown = NO;
|
||||
uint64_t dataSize = [self sizeVintValueAt:bytes + cursor + idLen length:sizeLen unknown:&unknown];
|
||||
|
||||
MP42EbmlElement *element = [[MP42EbmlElement alloc] init];
|
||||
element.identifier = [self idValueAt:bytes + cursor length:idLen];
|
||||
element.start = cursor;
|
||||
element.headerSize = idLen + sizeLen;
|
||||
|
||||
if (unknown) {
|
||||
element.sizeIsUnknown = YES;
|
||||
element.dataSize = end - element.dataStart;
|
||||
[elements addObject:element];
|
||||
break;
|
||||
}
|
||||
|
||||
if (element.dataStart + dataSize > end) {
|
||||
if (outError) {
|
||||
*outError = [self errorWithCode:MP42MkvErrorParse
|
||||
message:@"Element 0x%x at offset %llu extends past its parent",
|
||||
element.identifier, cursor];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
element.dataSize = dataSize;
|
||||
[elements addObject:element];
|
||||
cursor = element.dataStart + dataSize;
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
+ (uint64_t)payloadEndForElement:(MP42EbmlElement *)element regionEnd:(uint64_t)regionEnd
|
||||
{
|
||||
uint64_t end = element.dataStart + element.dataSize;
|
||||
return MIN(end, regionEnd);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MP42EbmlScanner {
|
||||
NSURL *_URL;
|
||||
int _fd;
|
||||
uint64_t _fileSize;
|
||||
}
|
||||
|
||||
+ (instancetype)scannerWithURL:(NSURL *)URL error:(NSError **)outError
|
||||
{
|
||||
int fd = open(URL.fileSystemRepresentation, O_RDONLY);
|
||||
if (fd < 0) {
|
||||
if (outError) {
|
||||
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
|
||||
code:NSFileReadUnknownError
|
||||
userInfo:@{ NSLocalizedDescriptionKey:
|
||||
[NSString stringWithFormat:@"Cannot open %@ (%d)", URL.lastPathComponent, errno] }];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
off_t size = lseek(fd, 0, SEEK_END);
|
||||
if (size < 0) {
|
||||
close(fd);
|
||||
if (outError) {
|
||||
*outError = [NSError errorWithDomain:NSCocoaErrorDomain
|
||||
code:NSFileReadUnknownError
|
||||
userInfo:@{ NSLocalizedDescriptionKey:
|
||||
[NSString stringWithFormat:@"Cannot determine size of %@ (%d)", URL.lastPathComponent, errno] }];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
MP42EbmlScanner *scanner = [[MP42EbmlScanner alloc] init];
|
||||
scanner->_URL = URL;
|
||||
scanner->_fd = fd;
|
||||
scanner->_fileSize = (uint64_t)size;
|
||||
return scanner;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self close];
|
||||
}
|
||||
|
||||
- (void)close
|
||||
{
|
||||
if (_fd >= 0) {
|
||||
close(_fd);
|
||||
_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
- (NSData *)readAtOffset:(uint64_t)offset length:(uint64_t)length error:(NSError **)outError
|
||||
{
|
||||
if (length == 0) {
|
||||
return [NSData data];
|
||||
}
|
||||
if (length > SIZE_MAX || offset + length > _fileSize) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Read past end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableData *data = [NSMutableData dataWithLength:(NSUInteger)length];
|
||||
uint8_t *bytes = data.mutableBytes;
|
||||
uint64_t done = 0;
|
||||
|
||||
while (done < length) {
|
||||
ssize_t n = pread(_fd, bytes + done, (size_t)(length - done), (off_t)(offset + done));
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorWriteFailed
|
||||
message:@"Read error in %@ (%d)", _URL.lastPathComponent, errno];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
if (n == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Unexpected end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
done += (uint64_t)n;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
- (NSArray<MP42EbmlElement *> *)scanChildrenFrom:(uint64_t)start
|
||||
length:(uint64_t)length
|
||||
error:(NSError **)outError
|
||||
{
|
||||
if (start > _fileSize) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Scan past end of %@", _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
uint64_t end = (length == MP42EbmlScanToEnd) ? _fileSize : MIN(start + length, _fileSize);
|
||||
|
||||
NSMutableArray<MP42EbmlElement *> *elements = [NSMutableArray array];
|
||||
uint64_t cursor = start;
|
||||
|
||||
while (cursor < end) {
|
||||
uint8_t buf[12]; // up to 4 ID bytes + 8 size bytes
|
||||
NSUInteger avail = (NSUInteger)MIN((uint64_t)sizeof(buf), end - cursor);
|
||||
|
||||
ssize_t n = pread(_fd, buf, avail, (off_t)cursor);
|
||||
if (n <= 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (n <= 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Truncated EBML header at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
avail = (NSUInteger)n;
|
||||
|
||||
// Zero padding (some muxers pad allocations) ends the structure.
|
||||
if (buf[0] == 0x00) {
|
||||
break;
|
||||
}
|
||||
|
||||
NSUInteger idLen = [MP42Ebml idVintLengthAt:buf available:avail];
|
||||
if (idLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element ID at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUInteger sizeLen = [MP42Ebml sizeVintLengthAt:buf + idLen available:avail - idLen];
|
||||
if (sizeLen == 0) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Invalid element size at %llu in %@", cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
BOOL unknown = NO;
|
||||
uint64_t dataSize = [MP42Ebml sizeVintValueAt:buf + idLen length:sizeLen unknown:&unknown];
|
||||
|
||||
MP42EbmlElement *element = [[MP42EbmlElement alloc] init];
|
||||
element.identifier = [MP42Ebml idValueAt:buf length:idLen];
|
||||
element.start = cursor;
|
||||
element.headerSize = idLen + sizeLen;
|
||||
|
||||
if (unknown) {
|
||||
// Unknown size runs to the end of the parent region and, in
|
||||
// practice, only ever occurs on the trailing element (streamed
|
||||
// clusters). It terminates the scan.
|
||||
element.sizeIsUnknown = YES;
|
||||
element.dataSize = end - element.dataStart;
|
||||
[elements addObject:element];
|
||||
break;
|
||||
}
|
||||
|
||||
if (element.dataStart + dataSize > end) {
|
||||
if (outError) {
|
||||
*outError = [MP42Ebml errorWithCode:MP42MkvErrorParse
|
||||
message:@"Element 0x%x at %llu in %@ extends past its parent",
|
||||
element.identifier, cursor, _URL.lastPathComponent];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
element.dataSize = dataSize;
|
||||
[elements addObject:element];
|
||||
cursor = element.dataStart + dataSize;
|
||||
}
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -25,11 +25,22 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
+ (NSArray<NSString *> *)supportedFileFormats;
|
||||
+ (BOOL)canInitWithFileType:(NSString *)fileType;
|
||||
|
||||
// YES for the extensions handled by the Matroska importer (mkv, mka, mks);
|
||||
// used by callers that want to open such files in tags-only mode instead of
|
||||
// converting them.
|
||||
+ (BOOL)isMatroskaFileType:(NSString *)fileType;
|
||||
|
||||
+ (NSArray<UTType *> *)supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
+ (BOOL)canInitWithContentType:(UTType *)contentType API_AVAILABLE(macos(11.0));
|
||||
|
||||
- (nullable instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)error;
|
||||
|
||||
// tagsOnly is YES when the caller opens a Matroska file to edit it in place
|
||||
// (tags-only mode): the importer then mirrors the file's own track flags
|
||||
// (TrackFlagEnabled) instead of Subler's MP4-oriented "first track of each
|
||||
// type enabled" conversion heuristic. Non-Matroska importers ignore it.
|
||||
- (nullable instancetype)initWithURL:(NSURL *)fileURL tagsOnly:(BOOL)tagsOnly error:(NSError * __autoreleasing *)error;
|
||||
|
||||
@property (nonatomic, readonly) NSURL *fileURL;
|
||||
@property (nonatomic, readonly) MP42Metadata *metadata;
|
||||
@property (nonatomic, readonly) NSArray<MP42Track *> *tracks;
|
||||
|
||||
+20
-1
@@ -98,6 +98,11 @@ static NSArray<UTType *> *_supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
return [[self supportedFileFormats] containsObject:fileType.lowercaseString];
|
||||
}
|
||||
|
||||
+ (BOOL)isMatroskaFileType:(NSString *)fileType
|
||||
{
|
||||
return [[MP42MkvImporter supportedFileFormats] containsObject:fileType.lowercaseString];
|
||||
}
|
||||
|
||||
+ (NSArray<UTType *> *)supportedContentTypes
|
||||
{
|
||||
return _supportedContentTypes;
|
||||
@@ -116,13 +121,27 @@ static NSArray<UTType *> *_supportedContentTypes API_AVAILABLE(macos(11.0));
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
return [self initWithURL:fileURL tagsOnly:NO error:error];
|
||||
}
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)fileURL tagsOnly:(BOOL)tagsOnly error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
// Called on MP42FileImporter itself (the factory path, e.g. from the app):
|
||||
// pick and allocate the subclass for the extension. Called on a subclass
|
||||
// instance that ignores tagsOnly (it inherits this method), forward to
|
||||
// its real designated initializer instead — MP42MkvImporter overrides this
|
||||
// method outright, so it never lands here.
|
||||
if (![self isMemberOfClass:[MP42FileImporter class]]) {
|
||||
return [self initWithURL:fileURL error:error];
|
||||
}
|
||||
|
||||
self = nil;
|
||||
|
||||
// Initialize the right file importer subclass
|
||||
for (Class c in _fileImporters) {
|
||||
if ([c canInitWithFileType:fileURL.pathExtension]) {
|
||||
|
||||
self = [[c alloc] initWithURL:fileURL error:error];
|
||||
self = [[c alloc] initWithURL:fileURL tagsOnly:tagsOnly error:error];
|
||||
if (self) {
|
||||
for (MP42Track *track in _tracksArray) {
|
||||
track.importer = self;
|
||||
|
||||
@@ -32,4 +32,9 @@
|
||||
#import <MP42Foundation/MP42RelatedItem.h>
|
||||
#import <MP42Foundation/MP42SecurityAccessToken.h>
|
||||
|
||||
#import <MP42Foundation/MP42Ebml.h>
|
||||
#import <MP42Foundation/MP42MatroskaTagMapping.h>
|
||||
#import <MP42Foundation/MP42MkvRemuxer.h>
|
||||
#import <MP42Foundation/MP42MkvTagWriter.h>
|
||||
|
||||
#endif /* MP42Foundation_h */
|
||||
@@ -0,0 +1,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 <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// EBML / Matroska element identifiers.
|
||||
//
|
||||
// These are NOT the values printed on the older matroska.org documentation
|
||||
// pages, which are wrong for several elements (Tag, Targets, TargetTypeValue,
|
||||
// Attachments among them). The values below were verified empirically by
|
||||
// hex-dumping files written by ffmpeg and mkvtoolnix v104, and cross-checked
|
||||
// against the constants the bundled MatroskaParser.c demuxer parses with.
|
||||
// Treat MatroskaParser.c as the authority if you ever need to re-verify.
|
||||
enum {
|
||||
MP42MkvElementEBMLHeader = 0x1A45DFA3,
|
||||
MP42MkvElementSegment = 0x18538067,
|
||||
MP42MkvElementVoid = 0xEC,
|
||||
|
||||
MP42MkvElementSeekHead = 0x114D9B74,
|
||||
MP42MkvElementSeek = 0x4DBB,
|
||||
MP42MkvElementSeekID = 0x53AB,
|
||||
MP42MkvElementSeekPosition = 0x53AC,
|
||||
|
||||
MP42MkvElementSegmentInfo = 0x1549A966,
|
||||
MP42MkvElementTracks = 0x1654AE6B,
|
||||
MP42MkvElementTrackEntry = 0xAE,
|
||||
MP42MkvElementTrackNumber = 0xD7, // unsigned integer, referenced by block headers
|
||||
MP42MkvElementTrackUID = 0x73C5, // unsigned integer, tags/chapters/cue refs
|
||||
MP42MkvElementTrackName = 0x536E, // UTF-8 string
|
||||
// The Matroska element ids are a known trap: the practical ids (used by
|
||||
// libebml/mkvtoolnix and ffmpeg, and what every reader expects) are
|
||||
// 0x22B59C for the ISO-639-2/B language and 0x22B59D for the BCP-47
|
||||
// LanguageIETF. The EBML spec's later-introduced 0x447A carries the same
|
||||
// ISO value; it is accepted on read but never written. (Modern mkvtoolnix
|
||||
// files may contain ONLY the IETF element — mkvmerge derives the ISO code
|
||||
// from it — so the ISO element can be absent.)
|
||||
MP42MkvElementTrackLanguage = 0x22B59C, // ISO-639-2/B, 3 ASCII chars
|
||||
MP42MkvElementTrackLanguageSpec = 0x447A, // newer spec id, same ISO value
|
||||
MP42MkvElementTrackLanguageIETF = 0x22B59D, // BCP-47 string, e.g. "en-US"
|
||||
MP42MkvElementTrackFlagEnabled = 0xB9, // unsigned integer, default 1
|
||||
MP42MkvElementTrackFlagForced = 0x55AA, // unsigned integer, default 0
|
||||
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<NSString *, NSString *> *MP42MkvSimpleTagMapForTargetLevel(NSInteger level);
|
||||
|
||||
// Whether the importer models tag groups at this level at all. Groups at
|
||||
// chapter/scene/shot levels are skipped by the importer and must be carried
|
||||
// through untouched by the writer.
|
||||
BOOL MP42MkvTargetLevelIsModeled(NSInteger level);
|
||||
|
||||
// A canonical (ordered) write pair: one MP42 metadata key and the SimpleTag
|
||||
// name it is serialized as at a given level. The writer iterates these in
|
||||
// order so output is stable across saves.
|
||||
@interface MP42MkvTagPair : NSObject
|
||||
@property (nonatomic, readonly) NSString *simpleTagName;
|
||||
@property (nonatomic, readonly) NSString *metadataKey;
|
||||
- (instancetype)initWithSimpleTagName:(NSString *)name metadataKey:(NSString *)key;
|
||||
@end
|
||||
|
||||
// Write direction: ordered pairs for a target level. Derived from the read
|
||||
// map so both directions always agree.
|
||||
NSArray<MP42MkvTagPair *> *MP42MkvWritePairsForTargetLevel(NSInteger level);
|
||||
|
||||
// Whether MP42MkvTagWriter can save an MP42 metadata key to a Matroska file:
|
||||
// either it has a SimpleTag name at some modeled target level, or it is
|
||||
// regenerated (TrackNumber -> PART_NUMBER/TOTAL_PARTS), or it is stored as a
|
||||
// cover attachment (CoverArt). Keys answering NO here are silently dropped on
|
||||
// save — the UI uses this to flag such fields to the user.
|
||||
BOOL MP42MkvMetadataKeyIsPersisted(NSString *metadataKey);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,238 @@
|
||||
//
|
||||
// MP42MatroskaTagMapping.m
|
||||
// MP42Foundation
|
||||
//
|
||||
|
||||
#import "MP42MatroskaTagMapping.h"
|
||||
|
||||
#import "MP42MetadataFormat.h"
|
||||
|
||||
@implementation MP42MkvTagPair
|
||||
|
||||
- (instancetype)initWithSimpleTagName:(NSString *)name metadataKey:(NSString *)key
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_simpleTagName = [name copy];
|
||||
_metadataKey = [key copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
//
|
||||
// Read maps. These were previously inline in MP42MkvImporter's
|
||||
// readMatroskaMetadata; they live here now because the tag writer serializes
|
||||
// its inverse and any drift between the two directions silently drops tags.
|
||||
//
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvDefaultMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"TITLE": MP42MetadataKeyName,
|
||||
@"SUBTITLE": MP42MetadataKeyTrackSubTitle,
|
||||
@"ALBUM": MP42MetadataKeyAlbum,
|
||||
@"ARTIST": MP42MetadataKeyArtist,
|
||||
|
||||
@"COMMENT": MP42MetadataKeyUserComment,
|
||||
@"GENRE": MP42MetadataKeyUserGenre,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
|
||||
@"BPM": MP42MetadataKeyBeatsPerMin,
|
||||
|
||||
@"KEYWORDS": MP42MetadataKeyKeywords,
|
||||
@"THANKS_TO": MP42MetadataKeyThanks,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
|
||||
@"DESCRIPTION": MP42MetadataKeyDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeyLongDescription,
|
||||
|
||||
@"DIRECTOR_OF_PHOTOGRAPHY": MP42MetadataKeyArtDirector,
|
||||
@"COMPOSER": MP42MetadataKeyComposer,
|
||||
@"ARRANGER": MP42MetadataKeyArranger,
|
||||
@"WRITTEN_BY": MP42MetadataKeyAuthor,
|
||||
@"LYRICS": MP42MetadataKeyLyrics,
|
||||
@"CONDUCTOR": MP42MetadataKeyConductor,
|
||||
@"PUBLISHER": MP42MetadataKeyPublisher,
|
||||
@"SOUND_ENGINEER": MP42MetadataKeySoundEngineer,
|
||||
@"LEAD_PERFORMER": MP42MetadataKeySoloist,
|
||||
|
||||
@"PRODUCTION_STUDIO": MP42MetadataKeyStudio,
|
||||
@"DIRECTOR": MP42MetadataKeyDirector,
|
||||
@"PRODUCER": MP42MetadataKeyProducer,
|
||||
@"EXECUTIVE_PRODUCER": MP42MetadataKeyExecProducer,
|
||||
@"SCREENPLAY_BY": MP42MetadataKeyScreenwriters,
|
||||
@"CAST": MP42MetadataKeyCast,
|
||||
|
||||
// Movie-tab fields with no Matroska-spec equivalent; these names
|
||||
// follow the community style (uppercase words, no separators) and
|
||||
// exist mainly so values survive a Subler save/reopen round-trip.
|
||||
@"RATING": MP42MetadataKeyRating, // parental advisory string
|
||||
@"CONTENTRATING": MP42MetadataKeyContentRating, // numeric rating code
|
||||
@"MEDIAKIND": MP42MetadataKeyMediaKind,
|
||||
@"HD": MP42MetadataKeyHDVideo,
|
||||
|
||||
@"NETWORK": MP42MetadataKeyTVNetwork,
|
||||
@"EPISODEID": MP42MetadataKeyTVEpisodeID,
|
||||
|
||||
@"ENCODER": MP42MetadataKeyEncodingTool,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvCollectionMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"TITLE": MP42MetadataKeyTVShow,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
static NSDictionary<NSString *, NSString *> *MP42MkvSeasonMap(void)
|
||||
{
|
||||
static NSDictionary *map;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
map = @{
|
||||
@"PART_NUMBER": MP42MetadataKeyTVSeason,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
};
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSString *> *MP42MkvSimpleTagMapForTargetLevel(NSInteger level)
|
||||
{
|
||||
switch (level) {
|
||||
case MP42MkvTargetCollection: return MP42MkvCollectionMap();
|
||||
case MP42MkvTargetSeason: return MP42MkvSeasonMap();
|
||||
default: return MP42MkvDefaultMap();
|
||||
}
|
||||
}
|
||||
|
||||
BOOL MP42MkvTargetLevelIsModeled(NSInteger level)
|
||||
{
|
||||
// Chapter/scene/shot level tags are skipped by the importer and must be
|
||||
// preserved verbatim by the writer. Everything else (global, part, movie,
|
||||
// season, collection) feeds the metadata model.
|
||||
return level != MP42MkvTargetChapter &&
|
||||
level != MP42MkvTargetScene &&
|
||||
level != MP42MkvTargetShot;
|
||||
}
|
||||
|
||||
// Canonical SimpleTag name order per level, used to give the writer stable
|
||||
// output. Every name must exist in the read map for its level; names added
|
||||
// to a read map without being listed here are appended automatically (in
|
||||
// unspecified order) rather than silently dropped.
|
||||
static NSArray<NSString *> *MP42MkvWriteNameOrder(NSInteger level)
|
||||
{
|
||||
switch (level) {
|
||||
case MP42MkvTargetCollection:
|
||||
return @[ @"TITLE", @"SYNOPSIS", @"COPYRIGHT" ];
|
||||
case MP42MkvTargetSeason:
|
||||
return @[ @"PART_NUMBER", @"SYNOPSIS", @"DATE_RELEASED" ];
|
||||
default:
|
||||
return @[ @"TITLE", @"ALBUM", @"ARTIST", @"PART_NUMBER", @"TOTAL_PARTS",
|
||||
@"DATE_RELEASED", @"GENRE", @"DESCRIPTION", @"SYNOPSIS",
|
||||
@"COMMENT", @"COPYRIGHT", @"PRODUCTION_STUDIO",
|
||||
@"DIRECTOR", @"PRODUCER", @"EXECUTIVE_PRODUCER",
|
||||
@"SCREENPLAY_BY", @"WRITTEN_BY", @"COMPOSER", @"ARRANGER",
|
||||
@"LYRICS", @"CONDUCTOR", @"PUBLISHER", @"SOUND_ENGINEER",
|
||||
@"LEAD_PERFORMER", @"DIRECTOR_OF_PHOTOGRAPHY", @"CAST",
|
||||
@"RATING", @"CONTENTRATING", @"MEDIAKIND", @"HD",
|
||||
@"NETWORK", @"EPISODEID",
|
||||
@"KEYWORDS", @"THANKS_TO", @"BPM", @"ENCODER", @"SUBTITLE" ];
|
||||
}
|
||||
}
|
||||
|
||||
// All metadata keys MP42MkvTagWriter can round-trip, cached for the UI's
|
||||
// "can this field be saved?" hints. Kept here (next to the maps it derives
|
||||
// from) so the UI can never drift from what the writer actually writes.
|
||||
static NSSet<NSString *> *MP42MkvPersistedMetadataKeys(void)
|
||||
{
|
||||
static NSSet<NSString *> *keys;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSMutableSet<NSString *> *mutableKeys = [NSMutableSet setWithObjects:
|
||||
// Regenerated as PART_NUMBER / TOTAL_PARTS
|
||||
MP42MetadataKeyTrackNumber,
|
||||
// Fallback source for movie-level PART_NUMBER
|
||||
// when TrackNumber carries no index
|
||||
MP42MetadataKeyTVEpisodeNumber,
|
||||
// Regenerated as season-level PART_NUMBER
|
||||
// (also a season-map pair key, listed for clarity)
|
||||
MP42MetadataKeyTVSeason,
|
||||
// Stored as an AttachedFile, not a SimpleTag
|
||||
MP42MetadataKeyCoverArt,
|
||||
nil];
|
||||
for (NSNumber *level in @[ @(MP42MkvTargetMovie), @(MP42MkvTargetSeason), @(MP42MkvTargetCollection) ]) {
|
||||
for (MP42MkvTagPair *pair in MP42MkvWritePairsForTargetLevel(level.integerValue)) {
|
||||
[mutableKeys addObject:pair.metadataKey];
|
||||
}
|
||||
}
|
||||
keys = [mutableKeys copy];
|
||||
});
|
||||
return keys;
|
||||
}
|
||||
|
||||
BOOL MP42MkvMetadataKeyIsPersisted(NSString *metadataKey)
|
||||
{
|
||||
return metadataKey.length > 0 && [MP42MkvPersistedMetadataKeys() containsObject:metadataKey];
|
||||
}
|
||||
|
||||
NSArray<MP42MkvTagPair *> *MP42MkvWritePairsForTargetLevel(NSInteger level)
|
||||
{
|
||||
static NSMutableDictionary<NSNumber *, NSArray<MP42MkvTagPair *> *> *cache;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
cache = [NSMutableDictionary dictionary];
|
||||
});
|
||||
|
||||
NSNumber *levelKey = @(level);
|
||||
@synchronized (cache) {
|
||||
NSArray<MP42MkvTagPair *> *pairs = cache[levelKey];
|
||||
if (pairs) {
|
||||
return pairs;
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSString *> *readMap = MP42MkvSimpleTagMapForTargetLevel(level);
|
||||
NSMutableArray<MP42MkvTagPair *> *result = [NSMutableArray array];
|
||||
NSMutableSet<NSString *> *usedKeys = [NSMutableSet set];
|
||||
|
||||
for (NSString *name in MP42MkvWriteNameOrder(level)) {
|
||||
NSString *key = readMap[name];
|
||||
if (key && ![usedKeys containsObject:key]) {
|
||||
[usedKeys addObject:key];
|
||||
[result addObject:[[MP42MkvTagPair alloc] initWithSimpleTagName:name metadataKey:key]];
|
||||
}
|
||||
}
|
||||
|
||||
// Names present in the read map but missing from the order list still
|
||||
// need to be written; append them so both directions stay in sync.
|
||||
for (NSString *name in readMap) {
|
||||
NSString *key = readMap[name];
|
||||
if (![usedKeys containsObject:key]) {
|
||||
[usedKeys addObject:key];
|
||||
[result addObject:[[MP42MkvTagPair alloc] initWithSimpleTagName:name metadataKey:key]];
|
||||
}
|
||||
}
|
||||
|
||||
pairs = [result copy];
|
||||
cache[levelKey] = pairs;
|
||||
return pairs;
|
||||
}
|
||||
}
|
||||
+55
-80
@@ -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<NSString *, NSString *> *simpleMap = @{
|
||||
@"TITLE": MP42MetadataKeyName,
|
||||
@"SUBTITLE": MP42MetadataKeyTrackSubTitle,
|
||||
@"ALBUM": MP42MetadataKeyAlbum,
|
||||
@"ARTIST": MP42MetadataKeyArtist,
|
||||
|
||||
@"COMMENT": MP42MetadataKeyUserComment,
|
||||
@"GENRE": MP42MetadataKeyUserGenre,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate,
|
||||
|
||||
@"BPM": MP42MetadataKeyBeatsPerMin,
|
||||
|
||||
@"KEYWORDS": MP42MetadataKeyKeywords,
|
||||
@"THANKS_TO": MP42MetadataKeyThanks,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
|
||||
@"DESCRIPTION": MP42MetadataKeyDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeyLongDescription,
|
||||
|
||||
@"DIRECTOR_OF_PHOTOGRAPHY": MP42MetadataKeyArtDirector,
|
||||
@"COMPOSER": MP42MetadataKeyComposer,
|
||||
@"ARRANGER": MP42MetadataKeyArranger,
|
||||
@"WRITTEN_BY": MP42MetadataKeyAuthor,
|
||||
@"LYRICS": MP42MetadataKeyLyrics,
|
||||
@"CONDUCTOR": MP42MetadataKeyConductor,
|
||||
@"PUBLISHER": MP42MetadataKeyPublisher,
|
||||
@"SOUND_ENGINEER": MP42MetadataKeySoundEngineer,
|
||||
@"LEAD_PERFORMER": MP42MetadataKeySoloist,
|
||||
|
||||
@"PRODUCTION_STUDIO": MP42MetadataKeyStudio,
|
||||
@"DIRECTOR": MP42MetadataKeyDirector,
|
||||
@"PRODUCER": MP42MetadataKeyProducer,
|
||||
@"EXECUTIVE_PRODUCER": MP42MetadataKeyExecProducer,
|
||||
@"SCREENPLAY_BY": MP42MetadataKeyScreenwriters,
|
||||
|
||||
@"ENCODER": MP42MetadataKeyEncodingTool,
|
||||
};
|
||||
|
||||
NSDictionary<NSString *, NSString *> *collectionMap = @{
|
||||
@"TITLE": MP42MetadataKeyTVShow,
|
||||
@"COPYRIGHT": MP42MetadataKeyCopyright,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
};
|
||||
|
||||
NSDictionary<NSString *, NSString *> *seasonMap = @{
|
||||
@"PART_NUMBER": MP42MetadataKeyTVSeason,
|
||||
@"DESCRIPTION": MP42MetadataKeySeriesDescription,
|
||||
@"SYNOPSIS": MP42MetadataKeySeriesDescription,
|
||||
@"DATE_RELEASED": MP42MetadataKeyReleaseDate
|
||||
};
|
||||
// The SimpleTag maps live in MP42MatroskaTagMapping.h, shared verbatim
|
||||
// with MP42MkvTagWriter so reading and writing cannot drift apart.
|
||||
|
||||
unsigned count;
|
||||
Tag *tag_groups;
|
||||
@@ -448,8 +414,8 @@ MP42_OBJC_DIRECT_MEMBERS
|
||||
for (unsigned int xi = 0; xi < count; xi++) {
|
||||
Tag *tags = &tag_groups[xi];
|
||||
|
||||
ulonglong UID = 0;
|
||||
NSDictionary<NSString *, NSString *> *map = simpleMap;
|
||||
NSInteger level = MP42MkvTargetGlobal;
|
||||
NSDictionary<NSString *, NSString *> *map = nil;
|
||||
|
||||
if (tags->nTargetsSize) {
|
||||
struct Target *target = &tags->Targets[0];
|
||||
@@ -458,21 +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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <Foundation/Foundation.h>
|
||||
|
||||
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<MP42Track *> *)sourceTracks
|
||||
currentTracks:(NSArray<MP42Track *> *)currentTracks
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -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 <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
// 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<MP42Track *> *)sourceTracks
|
||||
currentTracks:(NSArray<MP42Track *> *)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<MP42Track *> *)sourceTracks
|
||||
currentTracks:(NSArray<MP42Track *> *)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<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
|
||||
{
|
||||
NSMutableArray<MP42Track *> *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<MP42EbmlElement *> *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<MP42Track *> *)realSource
|
||||
currentTracks:(NSArray<MP42Track *> *)currentReal
|
||||
helper:(MP42MkvTagWriter *)helper
|
||||
payload:(NSData **)outPayload
|
||||
droppedNumbers:(NSMutableSet<NSNumber *> *)droppedNumbers
|
||||
droppedBytes:(uint64_t *)outDroppedBytes
|
||||
error:(NSError **)outError
|
||||
{
|
||||
NSData *buf = file.tracks.payload;
|
||||
uint64_t regionEnd = buf.length;
|
||||
NSArray<MP42EbmlElement *> *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<MP42EbmlElement *> *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<NSNumber *> *)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<MP42EbmlElement *> *kids = [scanner scanChildrenFrom:payloadStart
|
||||
length:payloadEnd - payloadStart
|
||||
error:outError];
|
||||
if (!kids) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSMutableArray<MP42EbmlElement *> *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<NSNumber *, MP42EbmlElement *> *firstBlockByTrack = [NSMutableDictionary dictionary];
|
||||
NSMutableDictionary<NSNumber *, NSNumber *> *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<NSNumber *, NSNumber *> *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<NSNumber *> *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<MP42Track *> *)sourceTracks
|
||||
currentTracks:(NSArray<MP42Track *> *)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<MP42Track *> *realSource = RealTracksFromArray(sourceTracks);
|
||||
NSArray<MP42Track *> *currentReal = RealTracksFromArray(currentTracks);
|
||||
|
||||
NSMutableSet<NSNumber *> *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<MP42MkvKid *> *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<NSNumber *> *seekIds = [NSMutableArray array];
|
||||
NSMutableArray<NSNumber *> *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<NSNumber *, NSNumber *> *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
|
||||
@@ -0,0 +1,133 @@
|
||||
//
|
||||
// MP42MkvTagWriter+Internal.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Internal (not framework-exported) declarations shared between
|
||||
// MP42MkvTagWriter and MP42MkvRemuxer. The scanned file model and the
|
||||
// payload builders live in the tag writer's implementation; the remuxer
|
||||
// rebuilds a whole file from the same structures and builders so the two
|
||||
// writers can never drift on what a "tagged save" means. Do not import
|
||||
// this header from outside the framework, and never add it to the public
|
||||
// headers build phase.
|
||||
//
|
||||
|
||||
#import "MP42MkvTagWriter.h"
|
||||
|
||||
#import "MP42MatroskaTagMapping.h"
|
||||
|
||||
@class MP42Metadata;
|
||||
@class MP42Track;
|
||||
|
||||
typedef NS_ENUM(NSInteger, MP42MkvKidKind) {
|
||||
MP42MkvKidKeep = 0,
|
||||
MP42MkvKidTags,
|
||||
MP42MkvKidAttachments,
|
||||
MP42MkvKidTracks,
|
||||
MP42MkvKidSeekHead,
|
||||
MP42MkvKidCues,
|
||||
MP42MkvKidCluster,
|
||||
};
|
||||
|
||||
// A direct child of the Segment element plus its rewrite plan. All "rel"
|
||||
// quantities are byte offsets relative to the segment *data* start, which is
|
||||
// the same origin SeekHead/Cue positions use; that keeps position math
|
||||
// independent of any width change to the Segment header itself.
|
||||
@interface MP42MkvKid : NSObject
|
||||
@property (nonatomic, strong) MP42EbmlElement *el;
|
||||
@property (nonatomic) MP42MkvKidKind kind;
|
||||
@property (nonatomic, strong, nullable) NSData *payload; // parsed kinds only
|
||||
@property (nonatomic, strong, nullable) NSData *pendingPayload; // set when the payload is rewritten
|
||||
@property (nonatomic) BOOL removed; // element disappears
|
||||
@property (nonatomic) BOOL materializeUnknown; // cluster header: unknown size -> known
|
||||
@property (nonatomic) uint64_t relStart; // el.start - segment data start
|
||||
@property (nonatomic) uint64_t newStart; // plan-domain, relative to data start
|
||||
- (uint64_t)oldTotal;
|
||||
@end
|
||||
|
||||
// Snapshot of the file structure the rewrite operates on.
|
||||
@interface MP42MkvFile : NSObject
|
||||
@property (nonatomic, strong) MP42EbmlElement *segment;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *kids;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *tags;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *attachments;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *tracks;
|
||||
@property (nonatomic, strong, nullable) MP42MkvKid *firstCluster;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *seekHeads;
|
||||
@property (nonatomic, strong) NSArray<MP42MkvKid *> *cues;
|
||||
@property (nonatomic) BOOL segmentSizeUnknown;
|
||||
@property (nonatomic) uint64_t segDataStart; // absolute
|
||||
@property (nonatomic) uint64_t segDataLen; // old data length (to EOF when unknown)
|
||||
@end
|
||||
|
||||
// Per-field rewrite plan inside one TrackEntry (see editTrackEntry:…).
|
||||
typedef NS_ENUM(NSInteger, MP42MkvFieldAction) {
|
||||
MP42MkvFieldKeep = 0, // leave the existing element untouched
|
||||
MP42MkvFieldDrop, // remove every element with this id
|
||||
MP42MkvFieldSet, // replace the first occurrence (append if absent)
|
||||
};
|
||||
|
||||
@interface MP42MkvFieldEdit : NSObject
|
||||
@property (nonatomic) MP42MkvFieldAction action;
|
||||
@property (nonatomic, strong, nullable) NSData *payload; // Set only
|
||||
@property (nonatomic) uint32_t appendId; // id used when the file has no such element
|
||||
@end
|
||||
|
||||
// Maps an old SeekPosition (segment-data-relative) to its new value; sets
|
||||
// *drop for entries pointing into a removed element.
|
||||
typedef uint64_t (^MP42MkvPosMapper)(uint64_t relPos, BOOL *drop);
|
||||
|
||||
@interface MP42MkvTagWriter ()
|
||||
|
||||
// The members MP42MkvRemuxer drives. Semantics and nullability are as
|
||||
// documented at each implementation in MP42MkvTagWriter.m.
|
||||
|
||||
- (BOOL)checkStalenessWithError:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable MP42MkvFile *)scanFile:(MP42EbmlScanner *)scanner error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable NSData *)buildTagsPayloadForMetadata:(MP42Metadata *)metadata
|
||||
file:(MP42MkvFile *)file
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)buildAttachmentsPayloadForMetadata:(MP42Metadata *)metadata
|
||||
file:(MP42MkvFile *)file
|
||||
payload:(NSData * _Nullable *)outPayload
|
||||
changed:(BOOL *)outChanged
|
||||
shouldExist:(BOOL *)outShouldExist
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)buildTracksPayloadForTracks:(NSArray<MP42Track *> *)modelTracks
|
||||
file:(MP42MkvFile *)file
|
||||
payload:(NSData * _Nullable *)outPayload
|
||||
changed:(BOOL *)outChanged
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (nullable NSData *)editTrackEntry:(MP42EbmlElement *)entry
|
||||
buffer:(NSData *)buffer
|
||||
regionEnd:(uint64_t)regionEnd
|
||||
track:(MP42Track *)track
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Low-level output helpers (they consult -cancel and report progress on the
|
||||
// writer instance they are called on — the remuxer drives a helper writer
|
||||
// and mirrors its own state onto it).
|
||||
|
||||
- (BOOL)writeData:(NSData *)data
|
||||
fd:(int)fd
|
||||
offset:(uint64_t)offset
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)copyFromScanner:(MP42EbmlScanner *)scanner
|
||||
source:(uint64_t)sourceAbs
|
||||
length:(uint64_t)length
|
||||
toFD:(int)outFd
|
||||
outOffset:(uint64_t *)outOffset
|
||||
totalEstimate:(uint64_t)totalEstimate
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
- (BOOL)appendData:(NSData *)data
|
||||
toFD:(int)fd
|
||||
outOffset:(uint64_t *)outOffset
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// MP42MkvTagWriter.h
|
||||
// MP42Foundation
|
||||
//
|
||||
// Rewrites the Tags element (and, when the cover art changed, the
|
||||
// Attachments element) of an existing Matroska file in place, leaving all
|
||||
// track payloads and clusters untouched. Conceptually the same job as
|
||||
// `mkvpropedit --tags`.
|
||||
//
|
||||
// When model tracks are supplied, the per-track fields the model exposes —
|
||||
// Name, TrackLanguage/LanguageIETF, TrackFlagEnabled and (for subtitles)
|
||||
// TrackFlagForced — are diffed against each TrackEntry's effective values
|
||||
// and the Tracks element is rebuilt with only the changed fields
|
||||
// substituted. Conceptually `mkvpropedit --edit track:… --set …`; all other
|
||||
// TrackEntry children (CodecPrivate, timings, …) are copied byte-for-byte.
|
||||
//
|
||||
// When the new content fits into the old element's extent plus the Void
|
||||
// padding that follows it, the region is rewritten without shifting any
|
||||
// other byte (fast path, SeekHead/Cues/Segment stay valid). Otherwise the
|
||||
// file tail is rebuilt through a temporary file, SeekHead and Cues position
|
||||
// entries are recomputed, and the result atomically replaces the original.
|
||||
//
|
||||
// Tag groups Subler does not model (chapter/scene/shot targets, track/
|
||||
// edition/attachment targets, unmapped SimpleTag names such as ACTOR,
|
||||
// binary-valued tags) and non-cover attachments are preserved verbatim from
|
||||
// the file on disk, so saving never silently drops data the UI never showed.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <MP42Foundation/MP42Ebml.h>
|
||||
|
||||
@class MP42Metadata;
|
||||
@class MP42Track;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MP42MkvTagWriter : NSObject
|
||||
|
||||
@property (nonatomic, readonly) NSURL *fileURL;
|
||||
|
||||
// When set, the write refuses to touch a file whose size or modification
|
||||
// date no longer matches (callers snapshot these when the document is read).
|
||||
@property (nonatomic) uint64_t expectedFileSize;
|
||||
@property (nonatomic, copy, nullable) NSDate *expectedModificationDate;
|
||||
|
||||
// Called on the writing thread with a 0...1 estimate; may be nil.
|
||||
@property (nonatomic, copy, nullable) void (^progressHandler)(double progress);
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)URL;
|
||||
|
||||
- (BOOL)writeMetadata:(MP42Metadata *)metadata error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Also apply per-track edits (name, language, enabled, subtitle forced)
|
||||
// taken from the model tracks. The array must hold the document's tracks in
|
||||
// file order; chapter tracks are ignored (they are not Matroska tracks).
|
||||
// Pass nil to leave the Tracks element untouched.
|
||||
- (BOOL)writeMetadata:(MP42Metadata *)metadata
|
||||
tracks:(nullable NSArray<MP42Track *> *)tracks
|
||||
error:(NSError * _Nullable *)outError;
|
||||
|
||||
// Safe to call from another thread while -writeMetadata:error: is running;
|
||||
// the write aborts at the next chunk boundary leaving the original file
|
||||
// untouched.
|
||||
- (void)cancel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,7 +17,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
- (instancetype)initWithSourceURL:(NSURL *)URL trackID:(MP42TrackId)trackID fileHandle:(MP42FileHandle)fileHandle;
|
||||
- (BOOL)writeToFile:(MP42FileHandle)fileHandle error:(NSError * __autoreleasing *)outError;
|
||||
|
||||
@property(nonatomic, readwrite) MP42TrackId trackId;
|
||||
// Localized media-type label ("Video", "Sound", …) shown when the container
|
||||
// carries no explicit track name.
|
||||
- (NSString *)defaultName;
|
||||
|
||||
// trackId is readwrite in the public header
|
||||
@property(nonatomic, readwrite) MP42TrackId sourceId;
|
||||
|
||||
@property(nonatomic, readwrite, copy, nullable) NSURL *URL;
|
||||
|
||||
+5
-1
@@ -21,7 +21,11 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
*/
|
||||
@interface MP42Track : NSObject <NSSecureCoding, NSCopying, MP42SecurityScope>
|
||||
|
||||
@property(nonatomic, readonly) MP42TrackId trackId;
|
||||
// The muxer assigns the final id while writing (-[MP42File addTrack:]
|
||||
// zeroes it to mark the track as pending); hosts that build a model which
|
||||
// is never muxed (e.g. Matroska tags-only documents) can restore display
|
||||
// ids directly.
|
||||
@property(nonatomic, readwrite) MP42TrackId trackId;
|
||||
|
||||
@property(nonatomic, readonly, copy, nullable) NSURL *URL;
|
||||
|
||||
|
||||
+1
-1
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
A9B9C23E1823923100416A4E /* MP42MkvImporter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvImporter.h; sourceTree = "<group>"; };
|
||||
A9B9C23F1823923100416A4E /* MP42MkvImporter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvImporter.m; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000001 /* MP42Ebml.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Ebml.h; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000002 /* MP42Ebml.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Ebml.m; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000003 /* MP42MatroskaTagMapping.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MatroskaTagMapping.h; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000004 /* MP42MatroskaTagMapping.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MatroskaTagMapping.m; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000005 /* MP42MkvTagWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvTagWriter.h; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000006 /* MP42MkvTagWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvTagWriter.m; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000021 /* MP42MkvRemuxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42MkvRemuxer.h; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000022 /* MP42MkvRemuxer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42MkvRemuxer.m; sourceTree = "<group>"; };
|
||||
5AB1E120261124000000000023 /* MP42MkvTagWriter+Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MP42MkvTagWriter+Internal.h"; sourceTree = "<group>"; };
|
||||
A9B9C2401823923100416A4E /* MP42Mp4Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Mp4Importer.h; sourceTree = "<group>"; };
|
||||
A9B9C2411823923100416A4E /* MP42Mp4Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42Mp4Importer.m; sourceTree = "<group>"; };
|
||||
A9B9C2421823923100416A4E /* MP42Muxer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42Muxer.h; sourceTree = "<group>"; };
|
||||
@@ -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 */,
|
||||
|
||||
Reference in new issue
Block a user