// // MP42MkvRemuxer.m // MP42Foundation // #import "MP42MkvRemuxer.h" #import "MP42MkvTagWriter+Internal.h" #import "MP42MatroskaTagMapping.h" #import "MP42Metadata.h" #import "MP42Track.h" #import "MP42Track+Private.h" #import "MP42ChapterTrack.h" #import "MP42SubtitleTrack.h" #import "MP42Languages.h" #import "MP42SubUtilities.h" #import "MP42SSAParser.h" #import "MP42SSAConverter.h" #include #include #include #include #include // BlockGroups put their Block first; a small peek is enough to find the // track number that decides keep/drop for the whole group. static const uint64_t kBlockGroupPeekSize = 64 * 1024; static NSError *RemuxError(MP42MkvError code, NSString *format, ...) { va_list args; va_start(args, format); NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; va_end(args); return [MP42Ebml errorWithCode:code message:@"%@", message]; } // Subdata of a whole element (header + payload) within a scanned buffer. static NSData *RemuxBufferSlice(NSData *buffer, MP42EbmlElement *el, uint64_t regionEnd) { uint64_t end = [MP42Ebml payloadEndForElement:el regionEnd:regionEnd]; return [buffer subdataWithRange:NSMakeRange((NSUInteger)el.start, (NSUInteger)(end - el.start))]; } // Big-endian payload for an unsigned-integer element, minimal width unless // a wider one is requested (SeekHead positions stay 8 bytes so the element // size never changes when they are patched). static NSData *MkvUIntData(uint64_t value, NSUInteger minWidth) { NSUInteger width = 1; while (width < 8 && value >= ((uint64_t)1 << (8 * width))) { width++; } width = MAX(width, minWidth); NSMutableData *data = [NSMutableData dataWithLength:width]; uint8_t *bytes = data.mutableBytes; for (NSUInteger i = 0; i < width; i++) { bytes[width - 1 - i] = (uint8_t)(value & 0xFF); value >>= 8; } return data; } // Signed integer payload in minimal two's-complement big-endian width // (CueRelativePosition). Zero encodes as the single byte 0x00. static NSData *MkvSIntData(int64_t value) { NSUInteger width = 1; while (width < 8) { int64_t lo = -(INT64_C(1) << (8 * width - 1)); int64_t hi = (INT64_C(1) << (8 * width - 1)) - 1; if (value >= lo && value <= hi) { break; } width++; } NSMutableData *data = [NSMutableData dataWithLength:width]; uint8_t *bytes = data.mutableBytes; for (NSUInteger i = 0; i < width; i++) { bytes[width - 1 - i] = (uint8_t)((value >> (8 * (width - 1 - i))) & 0xFF); } return data; } // 8-byte big-endian IEEE-754 double payload. Duration is an EBML float // (4- or 8-byte); the remuxer always writes the 8-byte form so its slot // has a fixed width that can be pwrite-patched after the clusters stream // past (the value is only known at the end of the pass). static NSData *MkvFloatData(double value) { uint64_t bits; memcpy(&bits, &value, sizeof(bits)); NSMutableData *data = [NSMutableData dataWithLength:8]; uint8_t *bytes = data.mutableBytes; for (NSUInteger i = 0; i < 8; i++) { bytes[7 - i] = (uint8_t)((bits >> (8 * i)) & 0xFF); } return data; } // Big-endian EBML float payload (4 or 8 bytes) to a double. static double MkvFloatValue(const uint8_t *buf, NSUInteger length) { if (length == 4) { uint32_t bits = 0; for (NSUInteger i = 0; i < 4; i++) { bits = (bits << 8) | buf[i]; } float f; memcpy(&f, &bits, sizeof(f)); return f; } uint64_t bits = 0; for (NSUInteger i = 0; i < 8; i++) { bits = (bits << 8) | buf[i]; } double d; memcpy(&d, &bits, sizeof(d)); return d; } static NSUInteger MkvIdWidth(uint32_t identifier) { if (identifier >= 0x10000000u) return 4; if (identifier >= 0x200000u) return 3; if (identifier >= 0x4000u) return 2; return 1; } // A block's timecode is stored as int16 milliseconds relative to its // cluster's Timecode. static const int64_t kMkvBlockRelTCMax = 32767; #pragma mark - Added subtitle tracks // A subtitle track the document added on top of the source file: assigned a // fresh TrackNumber, with its timed-text lines re-parsed from track.URL // (the model never holds the text itself). The lines become BlockGroups // interleaved with the stream-copied blocks. @interface MkvAddedSubtitleTrack : NSObject @property (nonatomic, strong) MP42SubtitleTrack *track; @property (nonatomic) uint32_t trackNumber; @property (nonatomic, copy) NSArray *lines; // begin/end in ms, ascending @end @implementation MkvAddedSubtitleTrack @end // One not-yet-placed subtitle block. Its BlockGroup payload is only built // once the target cluster's timecode is known (the header needs the signed // relative timecode). @interface MkvPendingBlock : NSObject @property (nonatomic) uint32_t trackNumber; @property (nonatomic) uint64_t absTC; // block start, ms @property (nonatomic, copy) NSString *text; @property (nonatomic) uint64_t durationMs; @end @implementation MkvPendingBlock @end // New blocks landing around one original cluster: merged into that cluster // when it is rewritten with a Timecode and surviving blocks, otherwise // emitted as standalone Cluster elements directly after it. @interface MkvWindowBlocks : NSObject @property (nonatomic, strong) NSMutableArray *blocks; // Groups of overflow blocks; each group becomes one synthesized Cluster // whose Timecode is the first block's. @property (nonatomic, strong) NSMutableArray *> *overflowGroups; @end @implementation MkvWindowBlocks - (instancetype)init { if ((self = [super init])) { _blocks = [NSMutableArray array]; _overflowGroups = [NSMutableArray array]; } return self; } @end // Unmarked-vint track number as stored at the start of a block payload — // the inverse of +[MP42Ebml blockTrackNumberAt:available:value:]. static void MkvAppendBlockTrackNumber(NSMutableData *data, uint32_t value) { if (value <= 0x7F) { uint8_t byte = (uint8_t)(0x80 | value); [data appendBytes:&byte length:1]; } else { uint16_t encoded = (uint16_t)(0x4000 | value); uint8_t bytes[2] = { (uint8_t)(encoded >> 8), (uint8_t)(encoded & 0xFF) }; [data appendBytes:bytes length:2]; } } static NSData *MkvSubtitleBlockGroupPayload(uint32_t trackNumber, int64_t relTC, NSString *text, uint64_t durationMs) { // The caller checked the fit; clamping keeps malformed input from // silently writing a wrong header. relTC = MAX(-32768, MIN(kMkvBlockRelTCMax, relTC)); NSMutableData *block = [NSMutableData data]; MkvAppendBlockTrackNumber(block, trackNumber); uint8_t tcBytes[2] = { (uint8_t)(((uint16_t)(int16_t)relTC >> 8) & 0xFF), (uint8_t)((uint16_t)(int16_t)relTC & 0xFF) }; [block appendBytes:tcBytes length:2]; uint8_t flags = 0; // no keyframe/lacing flags on text blocks [block appendBytes:&flags length:1]; NSData *utf8 = [text dataUsingEncoding:NSUTF8StringEncoding]; if (utf8.length) { [block appendData:utf8]; } // SimpleBlock cannot carry a display duration, so text blocks live in a // BlockGroup with BlockDuration (TrackTimecodeScale units, default 1 ms). NSMutableData *payload = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementBlock payload:block to:payload]; [MP42Ebml appendElement:MP42MkvElementBlockDuration payload:MkvUIntData(MAX(durationMs, 1), 1) to:payload]; return payload; } static NSData *MkvSubtitleBlockGroup(uint32_t trackNumber, int64_t relTC, NSString *text, uint64_t durationMs) { NSMutableData *group = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementBlockGroup payload:MkvSubtitleBlockGroupPayload(trackNumber, relTC, text, durationMs) to:group]; return group; } @interface MP42MkvRemuxer () { NSURL *_sourceURL; volatile BOOL _cancelled; // End (in segment ticks) of the last block written by the running // remux — 1 past the greatest cluster Timecode + block relative // timecode seen, plus subtitle block durations. Feeds the Info // Duration patch; reset at the start of every remux. uint64_t _writtenMaxBlockEnd; } // Set while a remux runs so -cancel can abort the shared I/O helpers too. @property (nonatomic, strong, nullable) MP42MkvTagWriter *activeHelper; @end @implementation MP42MkvRemuxer - (instancetype)initWithSourceURL:(NSURL *)sourceURL { self = [super init]; if (self) { _sourceURL = [sourceURL copy]; } return self; } - (NSURL *)sourceURL { return _sourceURL; } - (void)cancel { _cancelled = YES; [self.activeHelper cancel]; } - (BOOL)checkCancelledWithError:(NSError **)outError { if (_cancelled) { if (outError) { *outError = RemuxError(MP42MkvErrorCancelled, @"cancelled"); } return NO; } return YES; } #pragma mark - Entry point - (BOOL)remuxToURL:(NSURL *)destURL metadata:(MP42Metadata *)metadata sourceTracks:(NSArray *)sourceTracks currentTracks:(NSArray *)currentTracks error:(NSError **)outError { _cancelled = NO; NSString *tempPath = nil; NSError *innerError = nil; BOOL ok = [self remuxToTempPath:&tempPath dest:destURL metadata:metadata sourceTracks:sourceTracks currentTracks:currentTracks error:&innerError]; if (ok) { // Temp lives in the destination directory, so the rename is atomic. if (rename([tempPath fileSystemRepresentation], [destURL.path fileSystemRepresentation]) != 0) { ok = NO; innerError = RemuxError(MP42MkvErrorWriteFailed, @"Could not install %@ (%d)", destURL.lastPathComponent, errno); } } if (!ok && tempPath) { unlink([tempPath fileSystemRepresentation]); } if (!ok && outError) { *outError = innerError; } return ok; } - (BOOL)remuxToTempPath:(NSString **)outTempPath dest:(NSURL *)destURL metadata:(MP42Metadata *)metadata sourceTracks:(NSArray *)sourceTracks currentTracks:(NSArray *)currentTracks error:(NSError **)outError { NSURL *destDir = destURL.URLByDeletingLastPathComponent; NSString *tempPath = [destDir.path stringByAppendingPathComponent: [NSString stringWithFormat:@".subler-remux-%@.tmp", [[NSUUID UUID] UUIDString]]]; int outFd = open([tempPath fileSystemRepresentation], O_WRONLY | O_CREAT | O_TRUNC, 0644); if (outFd < 0) { if (outError) { *outError = RemuxError(MP42MkvErrorWriteFailed, @"Could not create %@ (%d)", tempPath.lastPathComponent, errno); } return NO; } *outTempPath = tempPath; BOOL ok = [self remuxToFD:outFd dest:destURL metadata:metadata sourceTracks:sourceTracks currentTracks:currentTracks error:outError]; // Match the source file's permission bits for the replaced file. if (ok) { struct stat st; if (stat(_sourceURL.fileSystemRepresentation, &st) == 0) { fchmod(outFd, st.st_mode & 07777); } if (fsync(outFd) != 0) { ok = NO; if (outError) { *outError = RemuxError(MP42MkvErrorWriteFailed, @"Sync error (%d)", errno); } } } close(outFd); return ok; } #pragma mark - Track pairing / payload building // Filtered copy without the chapter pseudo-track (not a Matroska track). static NSArray *RealTracksFromArray(NSArray *tracks) { NSMutableArray *out = [NSMutableArray array]; for (MP42Track *track in tracks) { if (![track isMemberOfClass:MP42ChapterTrack.class]) { [out addObject:track]; } } return out; } // TrackNumber of a TrackEntry's payload; entries without one cannot be // dropped (their blocks would be unidentifiable). - (BOOL)trackNumberForEntry:(MP42EbmlElement *)entry buffer:(NSData *)buffer regionEnd:(uint64_t)regionEnd value:(uint32_t *)outValue error:(NSError **)outError { NSArray *kids = [MP42Ebml scanBuffer:buffer from:entry.dataStart length:entry.dataSize error:outError]; if (!kids) { *outError = RemuxError(MP42MkvErrorUnsupported, @"A track in %@ could not be parsed", _sourceURL.lastPathComponent); return NO; } for (MP42EbmlElement *kid in kids) { if (kid.identifier == MP42MkvElementTrackNumber && !kid.sizeIsUnknown && kid.dataSize > 0) { NSData *data = [buffer subdataWithRange:NSMakeRange((NSUInteger)kid.dataStart, (NSUInteger)kid.dataSize)]; uint64_t value = [MP42Ebml unsignedIntValueAt:data.bytes length:data.length]; if (value > 0 && value <= 255) { *outValue = (uint32_t)value; return YES; } } } *outError = RemuxError(MP42MkvErrorUnsupported, @"A removed track in %@ has no usable TrackNumber, so its data could not be located", _sourceURL.lastPathComponent); return NO; } // Timed-text lines for an added subtitle file, milliseconds, in the order // the shared serializer emits them (overlaps merged — the same semantics // the tx3g mux path gets). SSA styling is stripped by the converter; per // line SRT "!!!" forced markers and top-position markers are not carried // into Matroska blocks. - (nullable NSArray *)loadLinesForSubtitleURL:(NSURL *)url error:(NSError **)outError { MP42SubSerializer *serializer = [[MP42SubSerializer alloc] init]; BOOL isSRT = [url.pathExtension caseInsensitiveCompare:@"srt"] == NSOrderedSame; if (isSRT) { MP4Duration duration = 0; if (!LoadSRTFromURL(url, serializer, &duration)) { if (outError) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ does not contain any subtitles", url.lastPathComponent); } return nil; } } else { NSString *text = STLoadFileWithUnknownEncoding(url); if (!text.length) { if (outError) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ could not be read as a subtitle file", url.lastPathComponent); } return nil; } serializer.ssa = YES; // mirrors MP42SSAImporter's convert path MP42SSAParser *parser = [[MP42SSAParser alloc] initWithString:text]; MP42SSAConverter *converter = [[MP42SSAConverter alloc] initWithParser:parser]; for (MP42SSALine *line in parser.lines) { NSString *converted = [converter convertLine:line]; if (converted.length) { [serializer addLine:[[MP42SubLine alloc] initWithLine:converted start:line.start end:line.end]]; } } } [serializer setFinished:YES]; NSMutableArray *lines = [NSMutableArray array]; MP42SubLine *packet = nil; while ((packet = [serializer getSerializedPacket])) { if ([packet->line isEqualToString:@"\n"]) { continue; // gap filler; the next real line starts a new block } [lines addObject:packet]; } return lines; } // A fresh TrackEntry for an added subtitle track. Name follows the tag // writer's rule — an absent Name element *is* the localized default label — // so a later tags-only save diffs this entry against the model unchanged. - (NSData *)buildAddedTrackEntryForTrack:(MP42SubtitleTrack *)track trackNumber:(uint32_t)number { NSMutableData *payload = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementTrackNumber payload:MkvUIntData(number, 1) to:payload]; uint32_t uid = arc4random(); if (uid == 0) { uid = 1; // TrackUID 0 is reserved for the chapter pseudo-track } [MP42Ebml appendElement:MP42MkvElementTrackUID payload:MkvUIntData(uid, 4) to:payload]; [MP42Ebml appendElement:MP42MkvElementTrackType payload:MkvUIntData(17, 1) to:payload]; // subtitle [MP42Ebml appendElement:MP42MkvElementTrackFlagEnabled payload:MkvUIntData(1, 1) to:payload]; [MP42Ebml appendElement:MP42MkvElementFlagLacing payload:MkvUIntData(0, 1) to:payload]; // mkvmerge writes 0 MP42Languages *langs = MP42Languages.defaultManager; NSString *language = track.language ?: @"und"; NSString *iso = [langs ISO_639_2CodeForExtendedTag:language] ?: @"und"; [MP42Ebml appendStringElement:MP42MkvElementTrackLanguage string:iso to:payload]; if ([language rangeOfString:@"-"].location != NSNotFound) { NSString *ietfTag = [language stringByReplacingOccurrencesOfString:@"_" withString:@"-"]; [MP42Ebml appendStringElement:MP42MkvElementTrackLanguageIETF string:ietfTag to:payload]; } NSString *name = track.name; if (name.length && ![name isEqualToString:[track defaultName]]) { [MP42Ebml appendStringElement:MP42MkvElementTrackName string:name to:payload]; } [MP42Ebml appendStringElement:MP42MkvElementCodecID string:@"S_TEXT/UTF8" to:payload]; NSMutableData *entry = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementTrackEntry payload:payload to:entry]; return entry; } // Largest TrackNumber in a TrackEntry, 0 when absent or out of range — // unlike -trackNumberForEntry: this never errors: only dropped entries // strictly need a number (to find their blocks), the max is bookkeeping // for numbering the appended ones past every number in the file. - (uint32_t)maxTrackNumberInEntry:(MP42EbmlElement *)entry buffer:(NSData *)buffer regionEnd:(uint64_t)regionEnd { NSArray *kids = [MP42Ebml scanBuffer:buffer from:entry.dataStart length:entry.dataSize error:NULL]; uint32_t max = 0; 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 > max && value <= 0x3FFF) { max = (uint32_t)value; } } } return max; } // 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, and validated subtitle additions get a fresh // TrackEntry appended past every TrackNumber in the file. Collects the // dropped TrackNumbers, an approximate dropped-payload size for the // progress estimate, and the added tracks (with parsed lines) for the // cluster pass. - (BOOL)buildRemuxedTracksPayloadForFile:(MP42MkvFile *)file sourceTracks:(NSArray *)realSource currentTracks:(NSArray *)currentReal helper:(MP42MkvTagWriter *)helper payload:(NSData **)outPayload droppedNumbers:(NSMutableSet *)droppedNumbers droppedBytes:(uint64_t *)outDroppedBytes addedTracks:(NSMutableArray *)addedTracks error:(NSError **)outError { NSData *buf = file.tracks.payload; uint64_t regionEnd = buf.length; NSArray *kids = [MP42Ebml scanBuffer:buf from:0 length:regionEnd error:outError]; if (!kids) { *outError = RemuxError(MP42MkvErrorUnsupported, @"The tracks in %@ could not be parsed", _sourceURL.lastPathComponent); return NO; } NSUInteger entryCount = 0; for (MP42EbmlElement *kid in kids) { if (kid.identifier == MP42MkvElementTrackEntry) { entryCount++; } } if (entryCount != realSource.count) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ contains %lu tracks but the document started with %lu; revert the document before saving", _sourceURL.lastPathComponent, (unsigned long)entryCount, (unsigned long)realSource.count); return NO; } NSMutableArray *addedReal = [NSMutableArray array]; for (MP42Track *track in currentReal) { if ([realSource indexOfObjectIdenticalTo:track] == NSNotFound) { [addedReal addObject:track]; } } NSMutableData *out = [NSMutableData data]; NSUInteger modelIndex = 0; NSUInteger droppedCount = 0; uint64_t droppedBytes = 0; uint32_t maxNumber = 0; for (MP42EbmlElement *kid in kids) { BOOL isEntry = (kid.identifier == MP42MkvElementTrackEntry); if (!isEntry) { [out appendData:RemuxBufferSlice(buf, kid, regionEnd)]; continue; } if (!kid.sizeIsUnknown) { maxNumber = MAX(maxNumber, [self maxTrackNumberInEntry:kid buffer:buf regionEnd:regionEnd]); } 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; } // Additions: only subtitle text files become new tracks; everything else // (video/audio, other codecs, other containers) stays refused. for (MP42Track *track in addedReal) { NSString *ext = track.URL.pathExtension; BOOL subtitleText = [track isKindOfClass:MP42SubtitleTrack.class] && track.URL && ([ext caseInsensitiveCompare:@"srt"] == NSOrderedSame || [ext caseInsensitiveCompare:@"ssa"] == NSOrderedSame || [ext caseInsensitiveCompare:@"ass"] == NSOrderedSame); if (!subtitleText) { *outError = RemuxError(MP42MkvErrorUnsupported, @"Only .srt, .ssa or .ass subtitle tracks can be added to %@; the document contains a track that is not stored in the file", _sourceURL.lastPathComponent); return NO; } NSArray *lines = [self loadLinesForSubtitleURL:track.URL error:outError]; if (!lines) { return NO; } if (lines.count == 0) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ does not contain any subtitles", track.URL.lastPathComponent); return NO; } if (maxNumber >= 0x3FFF) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ has no free track number left for another track", _sourceURL.lastPathComponent); return NO; } maxNumber++; MkvAddedSubtitleTrack *added = [[MkvAddedSubtitleTrack alloc] init]; added.track = (MP42SubtitleTrack *)track; added.trackNumber = maxNumber; added.lines = lines; [addedTracks addObject:added]; [out appendData:[self buildAddedTrackEntryForTrack:(MP42SubtitleTrack *)track trackNumber:maxNumber]]; } *outPayload = out; *outDroppedBytes = droppedBytes; return YES; } #pragma mark - Block helpers // Track number carried by a SimpleBlock/Block payload, plus the block's // signed 16-bit timecode relative to its cluster (outRelTC may be NULL). - (BOOL)trackNumberAtBlockPayload:(uint64_t)payloadStart limit:(uint64_t)limitEnd scanner:(MP42EbmlScanner *)scanner value:(uint32_t *)outValue timecode:(int16_t *)outRelTC error:(NSError **)outError { NSUInteger avail = (NSUInteger)MIN((uint64_t)16, limitEnd - payloadStart); if (avail == 0) { *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ is truncated", _sourceURL.lastPathComponent); return NO; } NSData *head = [scanner readAtOffset:payloadStart length:avail error:outError]; if (!head) { return NO; } uint32_t value = 0; NSUInteger consumed = [MP42Ebml blockTrackNumberAt:head.bytes available:head.length value:&value]; if (consumed == 0 || value == 0 || value > 255) { *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ has an invalid track number", _sourceURL.lastPathComponent); return NO; } int16_t relTC = 0; if (outRelTC) { if (consumed + 2 > head.length) { *outError = RemuxError(MP42MkvErrorParse, @"A block in %@ is truncated", _sourceURL.lastPathComponent); return NO; } const uint8_t *tc = (const uint8_t *)head.bytes + consumed; relTC = (int16_t)((tc[0] << 8) | tc[1]); } *outValue = value; if (outRelTC) { *outRelTC = relTC; } return YES; } // Track number of a BlockGroup, taken from its Block child (BlockAdditions // belong to that block's track, so deciding on the group is enough). - (BOOL)trackNumberForBlockGroup:(MP42EbmlElement *)group scanner:(MP42EbmlScanner *)scanner value:(uint32_t *)outValue timecode:(int16_t *)outRelTC error:(NSError **)outError { uint64_t peek = MIN(group.dataSize, kBlockGroupPeekSize); NSData *buf = [scanner readAtOffset:group.dataStart length:peek error:outError]; if (!buf) { return NO; } NSArray *kids = [MP42Ebml scanBuffer:buf from:0 length:buf.length error:outError]; if (!kids) { *outError = RemuxError(MP42MkvErrorParse, @"A block group in %@ could not be parsed", _sourceURL.lastPathComponent); return NO; } for (MP42EbmlElement *kid in kids) { if (kid.identifier == MP42MkvElementBlock) { return [self trackNumberAtBlockPayload:group.dataStart + kid.dataStart limit:group.dataStart + group.dataSize scanner:scanner value:outValue timecode:outRelTC error:outError]; } } *outError = RemuxError(MP42MkvErrorUnsupported, @"A block group in %@ has no Block element", _sourceURL.lastPathComponent); return NO; } #pragma mark - Cluster rewriting // Timecode of a cluster for the added-blocks windowing pre-pass. Every // muxer writes Timecode as the cluster's first child, so a small peek // suffices; anything unusual falls back to a full header-only scan. // *outFound stays NO for a cluster that carries no Timecode at all — the // window then inherits the previous cluster's timecode (the caller also // enforces ascending windows, which a Timecode-less file cannot break). - (BOOL)clusterTimecodeForKid:(MP42MkvKid *)kid scanner:(MP42EbmlScanner *)scanner dataEnd:(uint64_t)dataEnd timecode:(uint64_t *)outTC found:(BOOL *)outFound error:(NSError **)outError { uint64_t payloadStart = kid.el.dataStart; uint64_t payloadEnd = kid.el.sizeIsUnknown ? dataEnd : kid.el.end; NSUInteger peek = (NSUInteger)MIN((uint64_t)64, payloadEnd - payloadStart); NSData *head = [scanner readAtOffset:payloadStart length:peek error:outError]; if (head) { NSArray *kids = [MP42Ebml scanBuffer:head from:0 length:head.length error:NULL]; MP42EbmlElement *first = kids.firstObject; if (first && first.identifier == MP42MkvElementClusterTimeCode && !first.sizeIsUnknown && first.dataSize > 0 && first.dataStart + first.dataSize <= head.length) { NSData *data = [head subdataWithRange:NSMakeRange((NSUInteger)first.dataStart, (NSUInteger)first.dataSize)]; *outTC = [MP42Ebml unsignedIntValueAt:data.bytes length:data.length]; *outFound = YES; return YES; } } // Unusual layout (or a short read): the full scan decides. Errors are // swallowed here — remuxClusterKid will surface any real corruption. NSArray *kids = [scanner scanChildrenFrom:payloadStart length:payloadEnd - payloadStart error:NULL]; for (MP42EbmlElement *child in kids) { if (child.identifier == MP42MkvElementClusterTimeCode && !child.sizeIsUnknown && child.dataSize > 0) { NSData *data = [scanner readAtOffset:child.dataStart length:child.dataSize error:outError]; if (!data) { return NO; } *outTC = [MP42Ebml unsignedIntValueAt:data.bytes length:data.length]; *outFound = YES; return YES; } } *outFound = NO; return YES; } // A whole synthesized Cluster (Timecode + BlockGroups) for subtitle blocks // that cannot ride inside an original cluster, plus its cue point. The // blocks' relative timecodes are computed against `timecode`. - (BOOL)writeSynthClusterWithTimecode:(uint64_t)timecode blocks:(NSArray *)blocks helper:(MP42MkvTagWriter *)helper fd:(int)fd cursor:(uint64_t *)cursor segDataStart:(uint64_t)segDataStartAbs wantCues:(BOOL)wantCues cuesPayload:(NSMutableData *)cuesPayload totalEstimate:(uint64_t)totalEstimate error:(NSError **)outError { if (blocks.count == 0) { return YES; } NSMutableData *payload = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementClusterTimeCode payload:MkvUIntData(timecode, 1) to:payload]; NSMutableDictionary *firstOffsetByTrack = [NSMutableDictionary dictionary]; for (MkvPendingBlock *block in blocks) { // Start + 1, mirroring how these same blocks measure on a later // pass once they are source blocks (cluster TC + relTC + 1) — // including BlockDuration here would make the Duration depend on // which pass wrote it, breaking remux idempotence. uint64_t end = block.absTC + 1; if (end > _writtenMaxBlockEnd) { _writtenMaxBlockEnd = end; } if (!firstOffsetByTrack[@(block.trackNumber)]) { firstOffsetByTrack[@(block.trackNumber)] = @(payload.length); } [payload appendData:MkvSubtitleBlockGroup(block.trackNumber, (int64_t)block.absTC - (int64_t)timecode, block.text, block.durationMs)]; } NSMutableData *cluster = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementCluster payload:payload to:cluster]; uint64_t clusterRel = *cursor - segDataStartAbs; // Where the cluster payload starts, relative to the cluster element — // block offsets are payload-relative, so cue-relative positions are // this plus the block's offset (both measured from the cluster start). uint64_t payloadRel = MkvIdWidth(MP42MkvElementCluster) + [MP42Ebml encodedLengthForSizeValue:payload.length]; if (![helper appendData:cluster toFD:fd outOffset:cursor error:outError]) { return NO; } if (wantCues) { NSMutableData *point = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementCueTime payload:MkvUIntData(timecode, 1) to:point]; NSArray *numbers = [firstOffsetByTrack.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)payloadRel + firstOffsetByTrack[num].longLongValue; 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; } // Standalone clusters for a window's new blocks when they cannot be merged // into the original cluster (raw copy, emptied cluster, no Timecode): the // window's blocks first (Timecoded at the window timecode, unless they were // already merged in), then each overflow group (Timecoded at its own first // block). - (BOOL)writeWindowExtras:(nullable MkvWindowBlocks *)windowBlocks timecode:(uint64_t)windowTimecode includeBlocks:(BOOL)includeBlocks helper:(MP42MkvTagWriter *)helper fd:(int)fd cursor:(uint64_t *)cursor segDataStart:(uint64_t)segDataStartAbs wantCues:(BOOL)wantCues cuesPayload:(NSMutableData *)cuesPayload totalEstimate:(uint64_t)totalEstimate error:(NSError **)outError { if (!windowBlocks) { return YES; } if (includeBlocks && ![self writeSynthClusterWithTimecode:windowTimecode blocks:windowBlocks.blocks helper:helper fd:fd cursor:cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]) { return NO; } for (NSArray *group in windowBlocks.overflowGroups) { if (![self writeSynthClusterWithTimecode:group.firstObject.absTC blocks:group helper:helper fd:fd cursor:cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]) { return NO; } } return YES; } // 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. `windowBlocks` carries the added-tracks' blocks // assigned to this cluster's timecode window: merged into the cluster by // timestamp when it is rewritten with a Timecode, standalone (and skipped // along with the window's overflow groups) otherwise. - (BOOL)remuxClusterKid:(MP42MkvKid *)kid scanner:(MP42EbmlScanner *)scanner helper:(MP42MkvTagWriter *)helper fd:(int)fd cursor:(uint64_t *)cursor segDataStart:(uint64_t)segDataStartAbs dataEnd:(uint64_t)dataEnd droppedNumbers:(NSSet *)droppedNumbers wantCues:(BOOL)wantCues cuesPayload:(NSMutableData *)cuesPayload totalEstimate:(uint64_t)totalEstimate windowBlocks:(nullable MkvWindowBlocks *)windowBlocks windowTimecode:(uint64_t)windowTimecode error:(NSError **)outError { if (![self checkCancelledWithError:outError]) { return NO; } uint64_t payloadStart = kid.el.dataStart; // An unknown-size cluster (only ever the last child) runs to the end of // the segment data — EOF for unknown-size segments, else the old segment // end (trailing padding is dropped with the rebuild). uint64_t payloadEnd = kid.el.sizeIsUnknown ? dataEnd : kid.el.end; NSArray *kids = [scanner scanChildrenFrom:payloadStart length:payloadEnd - payloadStart error:outError]; if (!kids) { return NO; } NSMutableArray *kept = [NSMutableArray array]; __block uint64_t keptTotal = 0; // __block: the merge closure below grows it BOOL hadBlock = NO, keptBlock = NO; uint64_t timecode = 0; BOOL hasTimecode = NO; // First surviving block element per track (+ its block timecode): the // cue point references land on these once their output position is known. NSMutableDictionary *firstBlockByTrack = [NSMutableDictionary dictionary]; // Block children keyed by file offset (unique within the cluster — // MP42EbmlElement is not NSCopying, so the elements themselves cannot // be dictionary keys) → their signed relative timecode. The cluster's // own Timecode may be scanned after the blocks, so absolute timestamps // are resolved against `timecode` once the loop finishes. NSMutableDictionary *blockRel = [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; } blockRel[@(child.start)] = @(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; } blockRel[@(child.start)] = @(relTC); [kept addObject:child]; keptTotal += child.totalSize; break; } default: // Position, PrevSize, PrevDuration, unknown children: verbatim. [kept addObject:child]; keptTotal += child.totalSize; break; } } // Feed the Duration recomputation: the last original block's tick, plus // 1, is the cluster's conservative end (frame durations inside blocks // are not parsed; the +1 matches mkvmerge rounding past the start). if (hasTimecode) { for (NSNumber *rel in blockRel.allValues) { int64_t end = (int64_t)timecode + rel.longLongValue + 1; if (end > (int64_t)_writtenMaxBlockEnd) { _writtenMaxBlockEnd = (uint64_t)end; } } } // Blocks of added subtitle tracks assigned to this cluster's window. NSArray *pending = windowBlocks.blocks; BOOL mergeable = hasTimecode && keptBlock && pending.count > 0; if (!hadBlock) { // Nothing block-like: copy the raw region (keeps the unknown-size // trailing form intact for a final blockless cluster). New subtitle // blocks cannot be merged in, so they follow as standalone clusters. if (![helper copyFromScanner:scanner source:kid.el.start length:payloadEnd - kid.el.start toFD:fd outOffset:cursor totalEstimate:totalEstimate error:outError]) { return NO; } return [self writeWindowExtras:windowBlocks timecode:windowTimecode includeBlocks:YES helper:helper fd:fd cursor:cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]; } if (!keptBlock) { // Cluster emptied by the removal: skip it whole, but the window's // new blocks still have to appear (their own Timecode keeps them // in timeline order where the original cluster used to be). return [self writeWindowExtras:windowBlocks timecode:windowTimecode includeBlocks:YES helper:helper fd:fd cursor:cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]; } // Output items: original children interleaved with synthesized // BlockGroups in ascending timestamp order (NSData = synthesized). NSMutableArray *outItems = kept; if (mergeable) { outItems = [NSMutableArray array]; __block NSUInteger next = 0; // int64 throughout: original blocks may carry negative relative // timecodes, which must order before every (unsigned) added block. void (^flushBefore)(int64_t) = ^(int64_t limitTC) { while (next < pending.count && (int64_t)pending[next].absTC < limitTC) { MkvPendingBlock *block = pending[next++]; // Start + 1, never + durationMs: once these blocks are // source blocks a later pass measures them as // clusterTC + relTC + 1, and the Duration must not depend // on which pass wrote it. uint64_t end = block.absTC + 1; if (end > _writtenMaxBlockEnd) { _writtenMaxBlockEnd = end; } NSData *item = MkvSubtitleBlockGroup(block.trackNumber, (int64_t)block.absTC - (int64_t)timecode, block.text, block.durationMs); if (!firstBlockByTrack[@(block.trackNumber)]) { firstBlockByTrack[@(block.trackNumber)] = item; } [outItems addObject:item]; keptTotal += item.length; } }; for (MP42EbmlElement *child in kept) { NSNumber *rel = blockRel[@(child.start)]; if (rel) { flushBefore((int64_t)timecode + rel.longLongValue); } [outItems addObject:child]; } flushBefore(INT64_MAX); } uint64_t clusterRel = *cursor - segDataStartAbs; NSMutableData *header = [NSMutableData data]; [MP42Ebml appendId:MP42MkvElementCluster to:header]; [MP42Ebml appendSize:keptTotal to:header]; // materializes an unknown-size header if (![helper appendData:header toFD:fd outOffset:cursor error:outError]) { return NO; } NSMutableDictionary *firstOutRelByTrack = [NSMutableDictionary dictionary]; for (id item in outItems) { uint64_t outPos = *cursor; for (NSNumber *num in firstBlockByTrack) { if (firstBlockByTrack[num] == item) { firstOutRelByTrack[num] = @(outPos - segDataStartAbs); } } if ([item isKindOfClass:NSData.class]) { if (![helper appendData:item toFD:fd outOffset:cursor error:outError]) { return NO; } } else if (![helper copyFromScanner:scanner source:((MP42EbmlElement *)item).start length:((MP42EbmlElement *)item).totalSize toFD:fd outOffset:cursor totalEstimate:totalEstimate error:outError]) { return NO; } } // One CuePoint per written cluster, with a CueTrackPositions for every // surviving track present in it — same shape libebml/mkvmerge emit, so // readers see the same index entries they saw before the removal. if (wantCues && hasTimecode) { NSMutableData *point = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementCueTime payload:MkvUIntData(timecode, 1) to:point]; NSArray *numbers = [firstOutRelByTrack.allKeys sortedArrayUsingSelector:@selector(compare:)]; for (NSNumber *num in numbers) { NSMutableData *trackPositions = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementCueTrack payload:MkvUIntData(num.unsignedLongLongValue, 1) to:trackPositions]; [MP42Ebml appendElement:MP42MkvElementCueClusterPosition payload:MkvUIntData(clusterRel, 1) to:trackPositions]; int64_t relative = (int64_t)firstOutRelByTrack[num].longLongValue - (int64_t)clusterRel; if (relative != 0) { [MP42Ebml appendElement:MP42MkvElementCueRelativePosition payload:MkvSIntData(relative) to:trackPositions]; } [MP42Ebml appendElement:MP42MkvElementCueTrackPositions payload:trackPositions to:point]; } [MP42Ebml appendElement:MP42MkvElementCuePoint payload:point to:cuesPayload]; } // Overflow groups always follow the cluster; the window's own blocks // only when they could not be merged into it (no Timecode). if (windowBlocks) { if (![self writeWindowExtras:windowBlocks timecode:windowTimecode includeBlocks:!mergeable helper:helper fd:fd cursor:cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]) { return NO; } } return YES; } #pragma mark - Chapters and Duration // Segment TimecodeScale (ns per tick) from the source Info element; // MP42MkvElementTimecodeScale defaults to 1000000 (1 ms) when absent. - (uint64_t)timecodeScaleForInfoKid:(nullable MP42MkvKid *)infoKid scanner:(MP42EbmlScanner *)scanner { if (!infoKid || infoKid.el.sizeIsUnknown) { return 1000000; } NSData *payload = [scanner readAtOffset:infoKid.el.dataStart length:infoKid.el.dataSize error:NULL]; if (!payload) { return 1000000; } NSArray *kids = [MP42Ebml scanBuffer:payload from:0 length:payload.length error:NULL]; for (MP42EbmlElement *el in kids) { if (el.identifier == MP42MkvElementTimecodeScale && !el.sizeIsUnknown && el.dataSize > 0 && el.dataSize <= 8 && el.dataStart + el.dataSize <= payload.length) { NSData *value = [payload subdataWithRange:NSMakeRange((NSUInteger)el.dataStart, (NSUInteger)el.dataSize)]; uint64_t scale = [MP42Ebml unsignedIntValueAt:value.bytes length:value.length]; if (scale > 0) { return scale; } } } return 1000000; } // splitmix64 finalizer — spreads the FNV hash into a well-mixed UID. static uint64_t MkvSplitMix64(uint64_t *state) { uint64_t z = (*state += 0x9E3779B97F4A7C15ull); z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; return z ^ (z >> 31); } // Rebuilt Chapters payload (the element's children): one EditionEntry with // one ChapterAtom per chapter. Titles that came back empty from the model // get the same "Chapter N" fallback the importer displays. Timestamps are // sorted ascending and clamped to previous + 1 ms because mkvmerge rejects // equal or decreasing chapter timecodes. An atom's ChapterTimeEnd is the // next atom's start; the last atom ends at the track duration when it is // known (a chapter track built from a .txt knows it, one built in the UI // may not — omitting the end is legal and players extrapolate). // // Chapter timecodes are absolute NANOSECONDS, not TimecodeScale ticks: // libmatroska writes and every reader (mkvtoolnix, ffmpeg) reads // ChapterTimeStart/End as ns regardless of the segment scale — verified // empirically by hex-dumping a mkvmerge-written file (raw 2.5e9 for 2.5 s // in a default-scale file) and reading it back with mkvinfo and ffprobe. - (NSData *)buildChaptersPayloadForTrack:(MP42ChapterTrack *)track { NSArray *samples = [track.chapters sortedArrayUsingComparator:^NSComparisonResult(MP42TextSample *a, MP42TextSample *b) { if (a.timestamp != b.timestamp) { return a.timestamp < b.timestamp ? NSOrderedAscending : NSOrderedDescending; } return NSOrderedSame; }]; // ChapterDisplay/ChapterLanguage: the model carries one language for the // whole track (Matroska allows one per display, but every common tool // stamps the same value on all atoms). Omit it when nil or when the ISO // tag is eng — eng is the spec default, and omitting keeps the bytes // identical to writers that predate language support. NSString *chapterLanguage = nil; if (track.language.length) { NSString *iso = [MP42Languages.defaultManager ISO_639_2CodeForExtendedTag:track.language]; if (iso.length == 3 && ![iso isEqualToString:@"eng"]) { chapterLanguage = iso; } } NSUInteger count = samples.count; NSMutableArray *starts = [NSMutableArray arrayWithCapacity:count]; uint64_t previous = 0; for (NSUInteger i = 0; i < count; i++) { uint64_t start = samples[i].timestamp; if (i > 0 && start <= previous) { start = previous + 1; // strictly ascending, mkvmerge rule } [starts addObject:@(start)]; previous = start; } // EditionUID and ChapterUID are mandatory per spec (exactly one each), // and ffmpeg silently skips chapter atoms that lack a ChapterUID. // Derived deterministically from the content (splitmixed FNV-1a, mixed // with the index) so re-saving an unchanged model reproduces the same // file instead of churning random UIDs. uint64_t editionSeed = 0; NSMutableData *edition = [NSMutableData data]; for (NSUInteger i = 0; i < count; i++) { NSString *uidTitle = samples[i].title ?: @""; uint64_t fnv = 1469598103934665603ull; // FNV-1a 64 for (NSUInteger b = 0; b < uidTitle.length; b++) { fnv = (fnv ^ (uint8_t)[uidTitle characterAtIndex:b]) * 1099511628211ull; } uint64_t uidSeed = fnv ^ (starts[i].unsignedLongLongValue * 0x9E3779B97F4A7C15ull) ^ ((uint64_t)i << 32); uint64_t chapterUID = MkvSplitMix64(&uidSeed); editionSeed ^= MkvSplitMix64(&uidSeed); NSMutableData *atom = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementChapterUID payload:MkvUIntData(chapterUID ? chapterUID : 1, 8) to:atom]; [MP42Ebml appendElement:MP42MkvElementChapterTimeStart payload:MkvUIntData(starts[i].unsignedLongLongValue * 1000000ull, 1) to:atom]; uint64_t endMs = 0; if (i + 1 < count) { endMs = starts[i + 1].unsignedLongLongValue; } else if (track.duration > starts[i].unsignedLongLongValue) { endMs = track.duration; } if (endMs) { [MP42Ebml appendElement:MP42MkvElementChapterTimeEnd payload:MkvUIntData(endMs * 1000000ull, 1) to:atom]; } NSString *title = samples[i].title; if (title.length == 0) { title = [NSString stringWithFormat:@"Chapter %lu", (unsigned long)(i + 1)]; } NSMutableData *display = [NSMutableData data]; [MP42Ebml appendStringElement:MP42MkvElementChapterString string:title to:display]; if (chapterLanguage) { [MP42Ebml appendStringElement:MP42MkvElementChapterLanguage string:chapterLanguage to:display]; } [MP42Ebml appendElement:MP42MkvElementChapterDisplay payload:display to:atom]; [MP42Ebml appendElement:MP42MkvElementChapterAtom payload:atom to:edition]; } uint64_t editionUID = MkvSplitMix64(&editionSeed); NSMutableData *editionOut = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementEditionUID payload:MkvUIntData(editionUID ? editionUID : 1, 8) to:editionOut]; [editionOut appendData:edition]; NSMutableData *payload = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementEditionEntry payload:editionOut to:payload]; return payload; } // Rewrites the source Info payload with the Duration element replaced by a // fixed 8-byte slot holding the source value, and reports the slot's offset // within the payload (pwrite-patched once the pass knows the real end) and // the original value (written back unchanged if the pass produced nothing // to measure). Returns nil — "copy Info verbatim instead" — when Info or a // usable Duration element is missing: files that never had a Duration keep // having none, players extrapolate those already. - (nullable NSData *)infoPayloadForInfoKid:(MP42MkvKid *)infoKid scanner:(MP42EbmlScanner *)scanner durationOffset:(NSUInteger *)outOffset durationOriginal:(double *)outOriginal { if (infoKid.el.sizeIsUnknown) { return nil; } NSData *payload = [scanner readAtOffset:infoKid.el.dataStart length:infoKid.el.dataSize error:NULL]; if (!payload) { return nil; } NSArray *kids = [MP42Ebml scanBuffer:payload from:0 length:payload.length error:NULL]; if (!kids) { return nil; } NSMutableData *out = [NSMutableData data]; BOOL replaced = NO; NSUInteger durationOffset = 0; double original = 0; for (MP42EbmlElement *el in kids) { if (el.sizeIsUnknown) { return nil; } BOOL isDuration = !replaced && el.identifier == MP42MkvElementDuration && (el.dataSize == 4 || el.dataSize == 8) && el.dataStart + el.dataSize <= payload.length; if (isDuration) { const uint8_t *bytes = (const uint8_t *)payload.bytes + el.dataStart; original = MkvFloatValue(bytes, el.dataSize); durationOffset = out.length + MkvIdWidth(MP42MkvElementDuration) + [MP42Ebml encodedLengthForSizeValue:8]; [MP42Ebml appendElement:MP42MkvElementDuration payload:MkvFloatData(original) to:out]; replaced = YES; } else { [out appendData:RemuxBufferSlice(payload, el, payload.length)]; } } if (!replaced) { return nil; } if (outOffset) { *outOffset = durationOffset; } if (outOriginal) { *outOriginal = original; } return out; } #pragma mark - SeekHead // A Seek entry whose SeekPosition payload is a fixed-width placeholder; // records where that payload sits relative to the SeekHead payload start // so it can be pwrite-patched once final positions are known. static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload, uint32_t targetID, NSUInteger *outPatchRel) { NSMutableData *idBytes = [NSMutableData data]; [MP42Ebml appendId:targetID to:idBytes]; NSMutableData *seekPayload = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementSeekID payload:idBytes to:seekPayload]; NSUInteger positionPayloadOffset = seekPayload.length + MkvIdWidth(MP42MkvElementSeekPosition) + [MP42Ebml encodedLengthForSizeValue:8]; [MP42Ebml appendElement:MP42MkvElementSeekPosition payload:MkvUIntData(0, 8) to:seekPayload]; NSUInteger seekElementOffset = seekHeadPayload.length; [MP42Ebml appendElement:MP42MkvElementSeek payload:seekPayload to:seekHeadPayload]; if (outPatchRel) { NSUInteger seekHeaderSize = MkvIdWidth(MP42MkvElementSeek) + [MP42Ebml encodedLengthForSizeValue:seekPayload.length]; *outPatchRel = seekElementOffset + seekHeaderSize + positionPayloadOffset; } } #pragma mark - Main remux - (BOOL)remuxToFD:(int)outFd dest:(NSURL *)destURL metadata:(MP42Metadata *)metadata sourceTracks:(NSArray *)sourceTracks currentTracks:(NSArray *)currentTracks error:(NSError **)outError { MP42MkvTagWriter *helper = [[MP42MkvTagWriter alloc] initWithURL:_sourceURL]; helper.expectedFileSize = self.expectedFileSize; helper.expectedModificationDate = self.expectedModificationDate; helper.progressHandler = self.progressHandler; self.activeHelper = helper; MP42EbmlScanner *scanner = [MP42EbmlScanner scannerWithURL:_sourceURL error:outError]; if (!scanner) { self.activeHelper = nil; return NO; } BOOL ok = NO; do { if (![helper checkStalenessWithError:outError]) { break; } MP42MkvFile *file = [helper scanFile:scanner error:outError]; if (!file || !file.tracks) { if (file && outError) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ has no Tracks element", _sourceURL.lastPathComponent); } break; } NSArray *realSource = RealTracksFromArray(sourceTracks); NSArray *currentReal = RealTracksFromArray(currentTracks); NSMutableSet *droppedNumbers = [NSMutableSet set]; uint64_t droppedBytes = 0; NSMutableArray *addedTracks = [NSMutableArray array]; NSData *newTracks = nil; if (![self buildRemuxedTracksPayloadForFile:file sourceTracks:realSource currentTracks:currentReal helper:helper payload:&newTracks droppedNumbers:droppedNumbers droppedBytes:&droppedBytes addedTracks:addedTracks error:outError]) { break; } NSData *newTags = [helper buildTagsPayloadForMetadata:metadata file:file error:outError]; if (!newTags) { break; } BOOL tagsShouldExist = newTags.length > 0; NSData *newAtt = nil; BOOL attChanged = NO, attShouldExist = NO; if (![helper buildAttachmentsPayloadForMetadata:metadata file:file payload:&newAtt changed:&attChanged shouldExist:&attShouldExist error:outError]) { break; } BOOL writeAttPayload = attShouldExist && attChanged && newAtt != nil; BOOL wantCues = file.cues.count > 0; // Locate the verbatim-carry top-level elements. MP42MkvKid *infoKid = nil, *chaptersKid = nil; NSMutableArray *extras = [NSMutableArray array]; for (MP42MkvKid *kid in file.kids) { if (kid.kind != MP42MkvKidKeep) { continue; } uint32_t identifier = kid.el.identifier; if (identifier == MP42MkvElementSegmentInfo && !infoKid) { infoKid = kid; } else if (identifier == MP42MkvElementChapters && !chaptersKid) { chaptersKid = kid; } else if (identifier != MP42MkvElementVoid) { [extras addObject:kid]; } } _writtenMaxBlockEnd = 0; // Segment tick size in ns — needed to turn the millisecond Duration // patch value into TimecodeScale units (Duration *is* scale-based, // unlike chapter timecodes which are absolute ns). uint64_t timecodeScaleNs = [self timecodeScaleForInfoKid:infoKid scanner:scanner]; // Chapters: decide up front whether the element exists at all, // because the SeekHead plan below depends on it. With a replacement // track: rebuild its payload (or remove the element when the model // deleted every chapter row); without one: the old verbatim copy. BOOL chaptersShouldExist = chaptersKid != nil; NSData *chaptersPayload = nil; if (self.replacementChapters) { if (self.replacementChapters.chapterCount > 0) { chaptersPayload = [self buildChaptersPayloadForTrack:self.replacementChapters]; chaptersShouldExist = YES; } else { chaptersShouldExist = NO; } } // Progress: the output is roughly the input minus the dropped payload. uint64_t totalEstimate = scanner.fileSize > droppedBytes ? scanner.fileSize - droppedBytes : scanner.fileSize; // ---- Added subtitle tracks: timecode windows and block placement ---- uint64_t segmentDataEnd = file.segmentSizeUnknown ? scanner.fileSize : file.segDataStart + file.segDataLen; NSArray *clusterKids = nil; // cluster kids in file order NSArray *windowTimecodes = nil; // parallel to clusterKids // Per cluster (indexed in clusterKids): blocks to merge into / follow it. NSMutableDictionary *windowBlocks = [NSMutableDictionary dictionary]; // Blocks starting before any cluster can reference them: head clusters. NSMutableArray *> *headGroups = [NSMutableArray array]; if (addedTracks.count) { NSMutableArray *kids = [NSMutableArray array]; for (MP42MkvKid *kid in file.kids) { if (kid.kind == MP42MkvKidCluster) { [kids addObject:kid]; } } if (kids.count == 0) { *outError = RemuxError(MP42MkvErrorUnsupported, @"%@ has no clusters to add subtitle blocks to", _sourceURL.lastPathComponent); break; } clusterKids = kids; NSMutableArray *timecodes = [NSMutableArray array]; uint64_t lastTC = 0; BOOL windowsFailed = NO; for (MP42MkvKid *kid in kids) { uint64_t tc = 0; BOOL found = NO; if (![self clusterTimecodeForKid:kid scanner:scanner dataEnd:segmentDataEnd timecode:&tc found:&found error:outError]) { windowsFailed = YES; break; } if (!found) { tc = lastTC; // no Timecode child: the window inherits the previous one } if (tc < lastTC) { *outError = RemuxError(MP42MkvErrorUnsupported, @"The clusters in %@ are not in ascending timecode order", _sourceURL.lastPathComponent); windowsFailed = YES; break; } lastTC = tc; [timecodes addObject:@(tc)]; } if (windowsFailed) { break; } windowTimecodes = timecodes; NSMutableArray *pending = [NSMutableArray array]; for (MkvAddedSubtitleTrack *added in addedTracks) { for (MP42SubLine *line in added.lines) { MkvPendingBlock *block = [[MkvPendingBlock alloc] init]; block.trackNumber = added.trackNumber; block.absTC = line->begin_time; block.text = line->line; block.durationMs = line->end_time > line->begin_time ? line->end_time - line->begin_time : 1; [pending addObject:block]; } } [pending sortUsingComparator:^NSComparisonResult(MkvPendingBlock *a, MkvPendingBlock *b) { if (a.absTC != b.absTC) { return a.absTC < b.absTC ? NSOrderedAscending : NSOrderedDescending; } if (a.trackNumber != b.trackNumber) { return a.trackNumber < b.trackNumber ? NSOrderedAscending : NSOrderedDescending; } return NSOrderedSame; }]; MkvWindowBlocks *(^windowFor)(NSUInteger) = ^MkvWindowBlocks *(NSUInteger idx) { MkvWindowBlocks *w = windowBlocks[@(idx)]; if (!w) { w = [[MkvWindowBlocks alloc] init]; windowBlocks[@(idx)] = w; } return w; }; uint64_t addedBytes = 0; for (MkvPendingBlock *block in pending) { addedBytes += block.text.length * 3 + 32; // rough estimate for progress // Last window whose timecode is at or before the block start // (clamped to the first window; timecodes are ascending). NSUInteger lo = 0, hi = windowTimecodes.count; while (lo < hi) { NSUInteger mid = (lo + hi) / 2; if (windowTimecodes[mid].unsignedLongLongValue <= block.absTC) { lo = mid + 1; } else { hi = mid; } } NSUInteger window = lo > 0 ? lo - 1 : 0; int64_t rel = (int64_t)block.absTC - (int64_t)windowTimecodes[window].unsignedLongLongValue; if (rel > kMkvBlockRelTCMax) { // Cluster longer than the int16 block header can reach: // synthesized clusters of at most one reachable span each // follow the assigned cluster. MkvWindowBlocks *w = windowFor(window); NSMutableArray *group = w.overflowGroups.lastObject; if (!group || block.absTC - group.firstObject.absTC > kMkvBlockRelTCMax) { group = [NSMutableArray array]; [w.overflowGroups addObject:group]; } [group addObject:block]; } else if (rel < -32768) { // Only the first window can be ahead of a block; such a // block gets its own head cluster. NSMutableArray *group = headGroups.lastObject; if (!group || block.absTC - group.firstObject.absTC > kMkvBlockRelTCMax) { group = [NSMutableArray array]; [headGroups addObject:group]; } [group addObject:block]; } else { [windowFor(window).blocks addObject:block]; } } totalEstimate += addedBytes; } // ---- SeekHead plan (fixed size, placeholder positions) ---- NSMutableArray *seekIds = [NSMutableArray array]; NSMutableArray *seekPatchRels = [NSMutableArray array]; NSMutableData *seekHeadPayload = [NSMutableData data]; NSUInteger patchRel = 0; MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementTracks, &patchRel); [seekIds addObject:@(MP42MkvElementTracks)]; [seekPatchRels addObject:@(patchRel)]; if (chaptersShouldExist) { 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; // Info: verbatim unless it carries a usable Duration element, which // is rewritten as a fixed 8-byte slot patched after the clusters // have streamed past (their end is only known at the very end). uint64_t durationPatchAbs = 0; double durationOriginal = 0; if (infoKid) { NSUInteger durationOffset = 0; NSData *infoPayload = [self infoPayloadForInfoKid:infoKid scanner:scanner durationOffset:&durationOffset durationOriginal:&durationOriginal]; if (infoPayload) { NSMutableData *infoElement = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementSegmentInfo payload:infoPayload to:infoElement]; if (![helper appendData:infoElement toFD:outFd outOffset:&cursor error:outError]) { break; } durationPatchAbs = cursor - infoElement.length + MkvIdWidth(MP42MkvElementSegmentInfo) + [MP42Ebml encodedLengthForSizeValue:infoPayload.length] + durationOffset; } else if (![helper copyFromScanner:scanner source:infoKid.el.start length:infoKid.el.totalSize toFD:outFd outOffset:&cursor totalEstimate:totalEstimate error:outError]) { break; } } BOOL extrasFailed = NO; for (MP42MkvKid *kid in extras) { if (![helper copyFromScanner:scanner source:kid.el.start length:kid.el.totalSize toFD:outFd outOffset:&cursor totalEstimate:totalEstimate error:outError]) { extrasFailed = YES; break; } } if (extrasFailed) { break; } NSMutableDictionary *finalRels = [NSMutableDictionary dictionary]; // Tracks (new payload). NSMutableData *tracksElement = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementTracks payload:newTracks to:tracksElement]; finalRels[@(MP42MkvElementTracks)] = @(cursor - segDataStartAbs); if (![helper appendData:tracksElement toFD:outFd outOffset:&cursor error:outError]) { break; } // Chapters: rebuilt payload when the model edited them, source // bytes otherwise, nothing at all when the model emptied them. if (chaptersShouldExist) { finalRels[@(MP42MkvElementChapters)] = @(cursor - segDataStartAbs); if (chaptersPayload) { NSMutableData *chaptersElement = [NSMutableData data]; [MP42Ebml appendElement:MP42MkvElementChapters payload:chaptersPayload to:chaptersElement]; if (![helper appendData:chaptersElement toFD:outFd outOffset:&cursor error:outError]) { break; } } else if (![helper copyFromScanner:scanner source:chaptersKid.el.start length:chaptersKid.el.totalSize toFD:outFd outOffset:&cursor totalEstimate:totalEstimate error:outError]) { break; } } // Clusters, filtered. NSMutableData *cuesPayload = [NSMutableData data]; BOOL clustersFailed = NO; // Subtitle blocks starting ahead of the first cluster's range. for (NSArray *group in headGroups) { if (![self writeSynthClusterWithTimecode:group.firstObject.absTC blocks:group helper:helper fd:outFd cursor:&cursor segDataStart:segDataStartAbs wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate error:outError]) { clustersFailed = YES; break; } } NSUInteger clusterIndex = 0; for (MP42MkvKid *kid in file.kids) { if (kid.kind != MP42MkvKidCluster) { continue; } MkvWindowBlocks *window = clusterKids ? windowBlocks[@(clusterIndex)] : nil; uint64_t windowTimecode = clusterKids ? windowTimecodes[clusterIndex].unsignedLongLongValue : 0; clusterIndex++; if (![self remuxClusterKid:kid scanner:scanner helper:helper fd:outFd cursor:&cursor segDataStart:segDataStartAbs dataEnd:segmentDataEnd droppedNumbers:droppedNumbers wantCues:wantCues cuesPayload:cuesPayload totalEstimate:totalEstimate windowBlocks:window windowTimecode:windowTimecode error:outError]) { clustersFailed = YES; break; } } if (clustersFailed) { break; } // Patch Info's Duration slot with the end of the last block written // (already +1 past the greatest start). A pass that wrote no // measurable block — every cluster blockless, say — keeps the source // value instead of zeroing it. if (durationPatchAbs) { // _writtenMaxBlockEnd is in ms; Duration is in TimecodeScale // units. At the default scale (1e6 ns/tick) ms == ticks; at a // non-default scale the end estimate already inherits this // pass's cluster-timecode convention (cluster TCs are copied // verbatim and the phase-3b cue math treats ticks as ms), so // the conversion here is exact exactly where that is too. double patchValue = _writtenMaxBlockEnd > 0 ? (double)_writtenMaxBlockEnd * 1000000.0 / (double)timecodeScaleNs : durationOriginal; if (![helper writeData:MkvFloatData(patchValue) fd:outFd offset:durationPatchAbs error:outError]) { 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