- 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>
516 lines
16 KiB
Objective-C
516 lines
16 KiB
Objective-C
//
|
|
// 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
|