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>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-26 11:53:17 -05:00
1 parent e42855867d
commit 8ba3f25a2c
3 files changed
+732 -35

No files matched your search

+5
View File
@@ -47,12 +47,17 @@ enum {
MP42MkvElementTrackLanguageIETF = 0x22B59D, // BCP-47 string, e.g. "en-US"
MP42MkvElementTrackFlagEnabled = 0xB9, // unsigned integer, default 1
MP42MkvElementTrackFlagForced = 0x55AA, // unsigned integer, default 0
MP42MkvElementTrackType = 0x83, // unsigned integer: 1 video, 2 audio, 17 subtitle
MP42MkvElementFlagLacing = 0x9C, // unsigned integer, default 1 (mkvmerge writes 0 for subtitles)
MP42MkvElementCodecID = 0x86, // ASCII string, e.g. "S_TEXT/UTF8"
MP42MkvElementChapters = 0x1043A770,
MP42MkvElementCluster = 0x1F43B675,
MP42MkvElementClusterTimeCode = 0xE7, // unsigned integer, cluster child
MP42MkvElementSimpleBlock = 0xA3, // cluster child; payload starts with the track-number vint
MP42MkvElementBlockGroup = 0xA0, // cluster child; the track comes from its Block child
MP42MkvElementBlock = 0xA1, // BlockGroup child (inside SimpleBlock it is 0xA3)
MP42MkvElementBlockDuration = 0x9B, // unsigned integer, BlockGroup child: display duration
// in TrackTimecodeScale units (default scale = 1 ms)
MP42MkvElementAttachments = 0x1941A469,
MP42MkvElementAttachedFile = 0x61A7,
+21 -4
View File
@@ -6,7 +6,8 @@
// (no decode/re-encode) except the blocks of tracks the model dropped —
// the job mkvpropedit cannot do (it corresponds to mkvmerge's copy mode
// with tracks deselected). Used when the user deletes tracks in a
// tags-only document, and for MKV Save-As to another URL.
// tags-only document, when the user adds a subtitle file to one, and for
// MKV Save-As to another URL.
//
// The Tracks, Tags and Attachments payloads are built with the exact
// model-diff builders MP42MkvTagWriter uses, so a remux save applies
@@ -16,6 +17,16 @@
// modified, so the remaining tracks' TrackNumber values may be gapped
// after a removal (valid Matroska, and what avoids any block rewrite).
//
// Added tracks: a model track absent from sourceTracks (by identity) must
// be an MP42SubtitleTrack whose URL ends in .srt/.ssa/.ass; its text is
// re-parsed from the URL at save time (the model never holds it) and
// written as S_TEXT/UTF8 BlockGroup{Block, BlockDuration} elements, past
// a fresh appended TrackEntry numbered past every number in the file.
// Blocks land in the original cluster whose Timecode window contains them
// (merged by timestamp); pathologically long clusters, emptied clusters
// and blocks outside every cluster's int16 range get their own
// synthesized Cluster elements instead — no original cluster is split.
//
// Guarantees / edges:
// - Blocks, CodecPrivate data, Chapters and Info (including Duration)
// are copied byte-for-byte; a Duration may overstate the longest
@@ -27,7 +38,11 @@
// and mtime as usual.
// - Refuses: multiple Segments, unknown-size elements other than the
// trailing cluster, unknown-size elements inside Tracks or clusters,
// and remuxes that would leave zero tracks.
// remuxes that would leave zero tracks, and added tracks that are not
// parseable .srt/.ssa/.ass subtitle files.
// - SSA styling is stripped to plain text (same conversion the MP4 mux
// path applies); per-line SRT "!!!" forced markers and top-position
// markers are not carried into the Matroska blocks.
//
#import <Foundation/Foundation.h>
@@ -55,8 +70,10 @@ NS_ASSUME_NONNULL_BEGIN
// sourceTracks must be the tracks exactly as the importer produced them
// (file order, chapter pseudo-track filtered out) — TrackEntry elements
// are paired with them by position. currentTracks is the document model's
// track list after user deletions; entries whose paired sourceTracks
// object is no longer present (compared by object identity) are removed.
// track list after user edits; entries whose paired sourceTracks object
// is no longer present (compared by object identity) are removed, and
// model tracks with no sourceTracks counterpart are appended as new
// S_TEXT/UTF8 subtitle tracks (see the header notes).
//
// Safe to call from another thread while -cancel may fire; the write
// aborts at the next chunk boundary and the partial temp file is
+706 -31
View File
@@ -9,11 +9,18 @@
#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
@@ -86,6 +93,111 @@ static NSUInteger MkvIdWidth(uint32_t identifier)
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;
@@ -255,10 +367,131 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
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. Collects the dropped TrackNumbers and an
// approximate dropped-payload size for the progress estimate.
// 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
@@ -266,6 +499,7 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
payload:(NSData **)outPayload
droppedNumbers:(NSMutableSet<NSNumber *> *)droppedNumbers
droppedBytes:(uint64_t *)outDroppedBytes
addedTracks:(NSMutableArray<MkvAddedSubtitleTrack *> *)addedTracks
error:(NSError **)outError
{
NSData *buf = file.tracks.payload;
@@ -289,12 +523,10 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
_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) {
*outError = RemuxError(MP42MkvErrorUnsupported,
@"The document contains a track that is not stored in %@; only removal is supported",
_sourceURL.lastPathComponent);
return NO;
[addedReal addObject:track];
}
}
@@ -302,6 +534,7 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
NSUInteger modelIndex = 0;
NSUInteger droppedCount = 0;
uint64_t droppedBytes = 0;
uint32_t maxNumber = 0;
for (MP42EbmlElement *kid in kids) {
BOOL isEntry = (kid.identifier == MP42MkvElementTrackEntry);
@@ -310,6 +543,10 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
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;
@@ -347,6 +584,44 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
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;
@@ -433,9 +708,172 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
#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.
// 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
@@ -447,6 +885,8 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
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]) {
@@ -467,14 +907,19 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
}
NSMutableArray<MP42EbmlElement *> *kept = [NSMutableArray array];
uint64_t keptTotal = 0;
__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 *, MP42EbmlElement *> *firstBlockByTrack = [NSMutableDictionary dictionary];
NSMutableDictionary<NSNumber *, NSNumber *> *blockRelTCByTrack = [NSMutableDictionary dictionary];
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) {
@@ -518,8 +963,8 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
keptBlock = YES;
if (!firstBlockByTrack[@(number)]) {
firstBlockByTrack[@(number)] = child;
blockRelTCByTrack[@(number)] = @(relTC);
}
blockRel[@(child.start)] = @(relTC);
[kept addObject:child];
keptTotal += child.totalSize;
break;
@@ -538,8 +983,8 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
keptBlock = YES;
if (!firstBlockByTrack[@(number)]) {
firstBlockByTrack[@(number)] = child;
blockRelTCByTrack[@(number)] = @(relTC);
}
blockRel[@(child.start)] = @(relTC);
[kept addObject:child];
keptTotal += child.totalSize;
break;
@@ -553,19 +998,77 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
}
}
// 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).
return [helper copyFromScanner:scanner
source:kid.el.start
length:payloadEnd - kid.el.start
toFD:fd
outOffset:cursor
// 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) {
return YES; // cluster emptied by the removal: skip it whole
// 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;
@@ -578,20 +1081,24 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
}
NSMutableDictionary<NSNumber *, NSNumber *> *firstOutRelByTrack = [NSMutableDictionary dictionary];
for (MP42EbmlElement *child in kept) {
for (id item in outItems) {
uint64_t outPos = *cursor;
for (NSNumber *num in firstBlockByTrack) {
if (firstBlockByTrack[num] == child) {
if (firstBlockByTrack[num] == item) {
firstOutRelByTrack[num] = @(outPos - segDataStartAbs);
}
}
if (![helper copyFromScanner:scanner
source:child.start
length:child.totalSize
toFD:fd
outOffset:cursor
totalEstimate:totalEstimate
error:outError]) {
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;
}
}
@@ -615,6 +1122,22 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
}
[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;
}
@@ -686,6 +1209,7 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
NSMutableSet<NSNumber *> *droppedNumbers = [NSMutableSet set];
uint64_t droppedBytes = 0;
NSMutableArray<MkvAddedSubtitleTrack *> *addedTracks = [NSMutableArray array];
NSData *newTracks = nil;
if (![self buildRemuxedTracksPayloadForFile:file
sourceTracks:realSource
@@ -694,7 +1218,8 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
payload:&newTracks
droppedNumbers:droppedNumbers
droppedBytes:&droppedBytes
error:outError]) {
addedTracks:addedTracks
error:outError]) {
break;
}
@@ -739,6 +1264,138 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
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];
@@ -856,14 +1513,30 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
}
// Clusters, filtered.
uint64_t segmentDataEnd = file.segmentSizeUnknown ? scanner.fileSize
: file.segDataStart + file.segDataLen;
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
@@ -875,6 +1548,8 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
wantCues:wantCues
cuesPayload:cuesPayload
totalEstimate:totalEstimate
windowBlocks:window
windowTimecode:windowTimecode
error:outError]) {
clustersFailed = YES;
break;