Files
MP42Foundation/MP42/MP42MkvRemuxer.m
T
Scott GarrettandClaude Code 8ba3f25a2c Write added subtitle tracks during Matroska remux
MP42MkvRemuxer previously refused any track present in currentTracks
but not in sourceTracks; it now accepts added MP42SubtitleTracks whose
URL extension is srt/ssa/ass and muxes them into the rebuilt file as
S_TEXT/UTF8. The extension gate mirrors the app-side
DocumentWindowController.matroskaSubtitleExtensions list — the two
must stay in sync.

- Each added track gets an appended TrackEntry: TrackNumber = max of
  all entries + 1 (refuse past 0x3FFF, the 2-byte unmarked-vint
  limit), TrackType 17, FlagEnabled 1, FlagLacing 0, CodecID
  S_TEXT/UTF8, ISO 0x22B59C + IETF 0x22B59D language, Name only when
  it differs from the codec default.
- The model never holds subtitle text, so lines are re-parsed from
  track.URL at save time: SRT via LoadSRTFromURL + serializer drain,
  SSA/ASS via MP42SSAParser/MP42SSAConverter (styling stripped, same
  lossy path the tx3g muxer takes). Zero parsed lines refuses.
- Blocks are written as BlockGroup{Block(unmarked-vint track number,
  int16 BE relative timecode, UTF-8 text), BlockDuration(>=1 ms)}.
  The BlockGroup wrapper is mandatory: a bare Block as a direct
  Cluster child is silently ignored by libebml readers even though
  ffmpeg tolerates it.
- Lines are assigned to the last existing Cluster whose Timecode is
  <= the line's start time (inheriting missing cluster timecodes,
  negative relative timecodes are legal); lines whose relative
  timecode would exceed +32767 flush as synthesized Clusters right
  after that cluster. Original clusters are copied verbatim and
  never split.
- Added tracks join the existing per-track CueTrackPositions
  bookkeeping, and the drop-all-remaining guard still fires before
  additions, so drop-all-plus-add stays refused.

Adds TrackType/FlagLacing/CodecID/BlockDuration element ids to
MP42MatroskaTagMapping.h.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-26 11:53:17 -05:00

1638 lines
69 KiB
Objective-C

//
// 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 <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.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;
}
// 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<MP42SubLine *> *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<MkvPendingBlock *> *blocks;
// Groups of overflow blocks; each group becomes one synthesized Cluster
// whose Timecode is the first block's.
@property (nonatomic, strong) NSMutableArray<NSMutableArray<MkvPendingBlock *> *> *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;
}
// 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;
}
// 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<MP42SubLine *> *)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<MP42SubLine *> *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<MP42EbmlElement *> *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<MP42Track *> *)realSource
currentTracks:(NSArray<MP42Track *> *)currentReal
helper:(MP42MkvTagWriter *)helper
payload:(NSData **)outPayload
droppedNumbers:(NSMutableSet<NSNumber *> *)droppedNumbers
droppedBytes:(uint64_t *)outDroppedBytes
addedTracks:(NSMutableArray<MkvAddedSubtitleTrack *> *)addedTracks
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;
}
NSMutableArray<MP42Track *> *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<MP42SubLine *> *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<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
// 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<MP42EbmlElement *> *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<MP42EbmlElement *> *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<MkvPendingBlock *> *)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<NSNumber *, NSNumber *> *firstOffsetByTrack = [NSMutableDictionary dictionary];
for (MkvPendingBlock *block in blocks) {
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<NSNumber *> *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<MkvPendingBlock *> *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<NSNumber *> *)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<MP42EbmlElement *> *kids = [scanner scanChildrenFrom:payloadStart
length:payloadEnd - payloadStart
error:outError];
if (!kids) {
return NO;
}
NSMutableArray<MP42EbmlElement *> *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<NSNumber *, id> *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<NSNumber *, NSNumber *> *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;
}
}
// Blocks of added subtitle tracks assigned to this cluster's window.
NSArray<MkvPendingBlock *> *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++];
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<NSNumber *, NSNumber *> *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<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];
}
// 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 - 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;
NSMutableArray<MkvAddedSubtitleTrack *> *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<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;
// ---- Added subtitle tracks: timecode windows and block placement ----
uint64_t segmentDataEnd = file.segmentSizeUnknown ? scanner.fileSize
: file.segDataStart + file.segDataLen;
NSArray<MP42MkvKid *> *clusterKids = nil; // cluster kids in file order
NSArray<NSNumber *> *windowTimecodes = nil; // parallel to clusterKids
// Per cluster (indexed in clusterKids): blocks to merge into / follow it.
NSMutableDictionary<NSNumber *, MkvWindowBlocks *> *windowBlocks = [NSMutableDictionary dictionary];
// Blocks starting before any cluster can reference them: head clusters.
NSMutableArray<NSMutableArray<MkvPendingBlock *> *> *headGroups = [NSMutableArray array];
if (addedTracks.count) {
NSMutableArray<MP42MkvKid *> *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<NSNumber *> *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<MkvPendingBlock *> *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<MkvPendingBlock *> *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<MkvPendingBlock *> *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<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.
NSMutableData *cuesPayload = [NSMutableData data];
BOOL clustersFailed = NO;
// Subtitle blocks starting ahead of the first cluster's range.
for (NSArray<MkvPendingBlock *> *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;
}
// 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