Rebuild Matroska chapters on remux and recompute Info Duration

MP42MkvRemuxer gains replacementChapters: when set, the Chapters element
is rebuilt from the model track instead of copied verbatim (chapterCount
0 removes the element and its SeekHead entry). Chapter timecodes are
written as absolute nanoseconds — libmatroska/mkvtoolnix/ffmpeg all
treat them as ns regardless of TimecodeScale, confirmed by hex-dumping
a mkvmerge-written file and reading it back with mkvinfo and ffprobe.
ChapterAtom is 0xB6 (0xB0 is PixelWidth), and mandatory EditionUID/
ChapterUID are derived deterministically from the content because
ffmpeg silently skips atoms without a ChapterUID. Starts are sorted
ascending with ties clamped to previous+1ms (mkvmerge rejects
non-ascending), empty titles get the importer's "Chapter N" fallback,
and the last atom's end rides the track duration only when known.

An existing Info Duration is recomputed as the greatest written block
start+1ms: the Info payload is rewritten with a fixed 8-byte double
slot patched after the clusters stream past, converted to TimecodeScale
units. Added blocks measure start+1 like source blocks so a second
no-op remux stays byte-identical (including BlockDuration broke
idempotence). Files without a source Duration keep having none.

The importer's chapter /1e6 needed no change (Start is already ns); a
comment now records that so it doesn't get "fixed" to scale-based math.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Scott GarrettandClaude Code committed 2026-11-26 12:54:43 -05:00
1 parent 8ba3f25a2c
commit 0cf79eca1c
4 files changed
+416 -22

No files matched your search

+24
View File
@@ -59,6 +59,30 @@ enum {
MP42MkvElementBlockDuration = 0x9B, // unsigned integer, BlockGroup child: display duration
// in TrackTimecodeScale units (default scale = 1 ms)
// Info children the remuxer recomputes; both are in TimecodeScale units
// (Duration is the only EBML *float* the remuxer touches — 8-byte double).
MP42MkvElementTimecodeScale = 0x2AD7B2, // unsigned integer, default 1000000 (1 ms in ns)
MP42MkvElementDuration = 0x4489, // float, TimecodeScale units
// Chapters children (MP42MkvElementChapters). DisplayUnitID (0x76) and
// ChapterLanguage (0x437C, default "eng") are omitted on write.
MP42MkvElementEditionEntry = 0x45B9,
MP42MkvElementEditionUID = 0x45BC, // unsigned integer, mandatory (1 edition 1 UID)
MP42MkvElementChapterUID = 0x73C4, // unsigned integer, mandatory — ffmpeg
// silently skips atoms without it
// ChapterAtom is 0xB6, NOT 0xB0 — 0xB0 is PixelWidth (TrackEntry scope;
// hex-dumping mkvmerge-written Chapters confirms 0xB6, and the vendored
// MatroskaParser.c has always parsed 0xB6 here).
MP42MkvElementChapterAtom = 0xB6,
// Chapter timecodes are absolute NANOSECONDS — unlike almost every
// other Matroska time, they do NOT follow TimecodeScale (libmatroska
// and ffmpeg both write/read them as ns; confirmed against a
// mkvmerge-written file).
MP42MkvElementChapterTimeStart = 0x91, // unsigned integer, ns
MP42MkvElementChapterTimeEnd = 0x92, // unsigned integer, ns; omit when unknown
MP42MkvElementChapterDisplay = 0x80,
MP42MkvElementChapterString = 0x85, // UTF-8 string
MP42MkvElementAttachments = 0x1941A469,
MP42MkvElementAttachedFile = 0x61A7,
MP42MkvElementFileDescription = 0x467E,
+5
View File
@@ -339,6 +339,11 @@ MP42_OBJC_DIRECT_MEMBERS
UInt64 scaledDuration = (UInt64)segInfo->Duration / SCALE_FACTOR;
[newTrack setDuration:scaledDuration];
// Chapter Start/End are absolute *nanoseconds* regardless of the
// segment's TimecodeScale — libmatroska writes and reads them that
// way (verified against mkvmerge-written files read back by both
// mkvinfo and ffprobe), so ns -> ms is a plain /1e6. The parser's
// Seg.Duration, by contrast, is already ns-scaled.
for (unsigned int xi = 0; xi < chapters->nChildren; xi++) {
uint64_t timestamp = (chapters->Children[xi].Start) / SCALE_FACTOR;
if (!xi) {
+26 -3
View File
@@ -26,11 +26,25 @@
// (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.
// Chapters: by default the source Chapters element is copied verbatim.
// Setting replacementChapters regenerates it from the model track —
// EditionEntry{ChapterAtom{ChapterTimeStart/End, ChapterDisplay{
// ChapterString}}} — with times converted from the model's milliseconds
// to absolute nanoseconds (chapter timecodes are ns in the wild, not
// TimecodeScale ticks), sorted ascending (ties clamped to previous + 1
// ms, as mkvmerge requires), each atom's end being the next atom's start
// and the last atom ending at the track duration when known.
// A replacement track with zero chapters removes the element (and its
// SeekHead entry) entirely. Chapters live before the Clusters, so any
// size change shifts every following byte — full-rebuild territory, which
// is why chapter writing lives here and not in MP42MkvTagWriter.
//
// Guarantees / edges:
// - Blocks, CodecPrivate data, Chapters and Info (including Duration)
// are copied byte-for-byte; a Duration may overstate the longest
// dropped track, which players tolerate.
// - Blocks, CodecPrivate data and Info are copied byte-for-byte, except
// that an existing Info Duration is recomputed to the end of the last
// written block (plus 1 ms) whenever the pass measured one, so a
// removal no longer leaves an overstated duration behind. Files whose
// Info never had a Duration keep having none.
// - Dangling references to removed tracks (DefaultTrackUID,
// ChapterTrackUID) are preserved; readers ignore unknown UIDs.
// - In-place writes go through a temp file in the destination directory
@@ -51,6 +65,7 @@ NS_ASSUME_NONNULL_BEGIN
@class MP42Metadata;
@class MP42Track;
@class MP42ChapterTrack;
@interface MP42MkvRemuxer : NSObject
@@ -65,6 +80,14 @@ NS_ASSUME_NONNULL_BEGIN
// Called on the remuxing thread with a 0...1 estimate; may be nil.
@property (nonatomic, copy, nullable) void (^progressHandler)(double progress);
// nil (default): the source Chapters element is copied verbatim. Non-nil:
// the Chapters element is rebuilt from this track's chapters (see the
// header notes); a track with no chapters removes the element. Timestamps
// are model milliseconds (timescale 1000); they are written as absolute
// nanoseconds (x1e6) — Matroska chapter timecodes are ns regardless of
// the segment's TimecodeScale, as mkvtoolnix and ffmpeg both read them.
@property (nonatomic, strong, nullable) MP42ChapterTrack *replacementChapters;
- (instancetype)initWithSourceURL:(NSURL *)sourceURL;
// sourceTracks must be the tracks exactly as the importer produced them
+361 -19
View File
@@ -85,6 +85,44 @@ static NSData *MkvSIntData(int64_t value)
return data;
}
// 8-byte big-endian IEEE-754 double payload. Duration is an EBML float
// (4- or 8-byte); the remuxer always writes the 8-byte form so its slot
// has a fixed width that can be pwrite-patched after the clusters stream
// past (the value is only known at the end of the pass).
static NSData *MkvFloatData(double value)
{
uint64_t bits;
memcpy(&bits, &value, sizeof(bits));
NSMutableData *data = [NSMutableData dataWithLength:8];
uint8_t *bytes = data.mutableBytes;
for (NSUInteger i = 0; i < 8; i++) {
bytes[7 - i] = (uint8_t)((bits >> (8 * i)) & 0xFF);
}
return data;
}
// Big-endian EBML float payload (4 or 8 bytes) to a double.
static double MkvFloatValue(const uint8_t *buf, NSUInteger length)
{
if (length == 4) {
uint32_t bits = 0;
for (NSUInteger i = 0; i < 4; i++) {
bits = (bits << 8) | buf[i];
}
float f;
memcpy(&f, &bits, sizeof(f));
return f;
}
uint64_t bits = 0;
for (NSUInteger i = 0; i < 8; i++) {
bits = (bits << 8) | buf[i];
}
double d;
memcpy(&d, &bits, sizeof(d));
return d;
}
static NSUInteger MkvIdWidth(uint32_t identifier)
{
if (identifier >= 0x10000000u) return 4;
@@ -201,6 +239,11 @@ static NSData *MkvSubtitleBlockGroup(uint32_t trackNumber, int64_t relTC,
@interface MP42MkvRemuxer () {
NSURL *_sourceURL;
volatile BOOL _cancelled;
// End (in segment ticks) of the last block written by the running
// remux — 1 past the greatest cluster Timecode + block relative
// timecode seen, plus subtitle block durations. Feeds the Info
// Duration patch; reset at the start of every remux.
uint64_t _writtenMaxBlockEnd;
}
// Set while a remux runs so -cancel can abort the shared I/O helpers too.
@property (nonatomic, strong, nullable) MP42MkvTagWriter *activeHelper;
@@ -783,6 +826,14 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
[MP42Ebml appendElement:MP42MkvElementClusterTimeCode payload:MkvUIntData(timecode, 1) to:payload];
NSMutableDictionary<NSNumber *, NSNumber *> *firstOffsetByTrack = [NSMutableDictionary dictionary];
for (MkvPendingBlock *block in blocks) {
// Start + 1, mirroring how these same blocks measure on a later
// pass once they are source blocks (cluster TC + relTC + 1) —
// including BlockDuration here would make the Duration depend on
// which pass wrote it, breaking remux idempotence.
uint64_t end = block.absTC + 1;
if (end > _writtenMaxBlockEnd) {
_writtenMaxBlockEnd = end;
}
if (!firstOffsetByTrack[@(block.trackNumber)]) {
firstOffsetByTrack[@(block.trackNumber)] = @(payload.length);
}
@@ -998,6 +1049,18 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
}
}
// Feed the Duration recomputation: the last original block's tick, plus
// 1, is the cluster's conservative end (frame durations inside blocks
// are not parsed; the +1 matches mkvmerge rounding past the start).
if (hasTimecode) {
for (NSNumber *rel in blockRel.allValues) {
int64_t end = (int64_t)timecode + rel.longLongValue + 1;
if (end > (int64_t)_writtenMaxBlockEnd) {
_writtenMaxBlockEnd = (uint64_t)end;
}
}
}
// Blocks of added subtitle tracks assigned to this cluster's window.
NSArray<MkvPendingBlock *> *pending = windowBlocks.blocks;
BOOL mergeable = hasTimecode && keptBlock && pending.count > 0;
@@ -1051,6 +1114,14 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
void (^flushBefore)(int64_t) = ^(int64_t limitTC) {
while (next < pending.count && (int64_t)pending[next].absTC < limitTC) {
MkvPendingBlock *block = pending[next++];
// Start + 1, never + durationMs: once these blocks are
// source blocks a later pass measures them as
// clusterTC + relTC + 1, and the Duration must not depend
// on which pass wrote it.
uint64_t end = block.absTC + 1;
if (end > _writtenMaxBlockEnd) {
_writtenMaxBlockEnd = end;
}
NSData *item = MkvSubtitleBlockGroup(block.trackNumber,
(int64_t)block.absTC - (int64_t)timecode,
block.text, block.durationMs);
@@ -1141,6 +1212,205 @@ static NSArray<MP42Track *> *RealTracksFromArray(NSArray<MP42Track *> *tracks)
return YES;
}
#pragma mark - Chapters and Duration
// Segment TimecodeScale (ns per tick) from the source Info element;
// MP42MkvElementTimecodeScale defaults to 1000000 (1 ms) when absent.
- (uint64_t)timecodeScaleForInfoKid:(nullable MP42MkvKid *)infoKid
scanner:(MP42EbmlScanner *)scanner
{
if (!infoKid || infoKid.el.sizeIsUnknown) {
return 1000000;
}
NSData *payload = [scanner readAtOffset:infoKid.el.dataStart
length:infoKid.el.dataSize
error:NULL];
if (!payload) {
return 1000000;
}
NSArray<MP42EbmlElement *> *kids = [MP42Ebml scanBuffer:payload from:0
length:payload.length error:NULL];
for (MP42EbmlElement *el in kids) {
if (el.identifier == MP42MkvElementTimecodeScale && !el.sizeIsUnknown &&
el.dataSize > 0 && el.dataSize <= 8 &&
el.dataStart + el.dataSize <= payload.length) {
NSData *value = [payload subdataWithRange:NSMakeRange((NSUInteger)el.dataStart,
(NSUInteger)el.dataSize)];
uint64_t scale = [MP42Ebml unsignedIntValueAt:value.bytes length:value.length];
if (scale > 0) {
return scale;
}
}
}
return 1000000;
}
// splitmix64 finalizer — spreads the FNV hash into a well-mixed UID.
static uint64_t MkvSplitMix64(uint64_t *state)
{
uint64_t z = (*state += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
// Rebuilt Chapters payload (the element's children): one EditionEntry with
// one ChapterAtom per chapter. Titles that came back empty from the model
// get the same "Chapter N" fallback the importer displays. Timestamps are
// sorted ascending and clamped to previous + 1 ms because mkvmerge rejects
// equal or decreasing chapter timecodes. An atom's ChapterTimeEnd is the
// next atom's start; the last atom ends at the track duration when it is
// known (a chapter track built from a .txt knows it, one built in the UI
// may not — omitting the end is legal and players extrapolate).
//
// Chapter timecodes are absolute NANOSECONDS, not TimecodeScale ticks:
// libmatroska writes and every reader (mkvtoolnix, ffmpeg) reads
// ChapterTimeStart/End as ns regardless of the segment scale — verified
// empirically by hex-dumping a mkvmerge-written file (raw 2.5e9 for 2.5 s
// in a default-scale file) and reading it back with mkvinfo and ffprobe.
- (NSData *)buildChaptersPayloadForTrack:(MP42ChapterTrack *)track
{
NSArray<MP42TextSample *> *samples =
[track.chapters sortedArrayUsingComparator:^NSComparisonResult(MP42TextSample *a, MP42TextSample *b) {
if (a.timestamp != b.timestamp) {
return a.timestamp < b.timestamp ? NSOrderedAscending : NSOrderedDescending;
}
return NSOrderedSame;
}];
NSUInteger count = samples.count;
NSMutableArray<NSNumber *> *starts = [NSMutableArray arrayWithCapacity:count];
uint64_t previous = 0;
for (NSUInteger i = 0; i < count; i++) {
uint64_t start = samples[i].timestamp;
if (i > 0 && start <= previous) {
start = previous + 1; // strictly ascending, mkvmerge rule
}
[starts addObject:@(start)];
previous = start;
}
// EditionUID and ChapterUID are mandatory per spec (exactly one each),
// and ffmpeg silently skips chapter atoms that lack a ChapterUID.
// Derived deterministically from the content (splitmixed FNV-1a, mixed
// with the index) so re-saving an unchanged model reproduces the same
// file instead of churning random UIDs.
uint64_t editionSeed = 0;
NSMutableData *edition = [NSMutableData data];
for (NSUInteger i = 0; i < count; i++) {
NSString *uidTitle = samples[i].title ?: @"";
uint64_t fnv = 1469598103934665603ull; // FNV-1a 64
for (NSUInteger b = 0; b < uidTitle.length; b++) {
fnv = (fnv ^ (uint8_t)[uidTitle characterAtIndex:b]) * 1099511628211ull;
}
uint64_t uidSeed = fnv ^ (starts[i].unsignedLongLongValue * 0x9E3779B97F4A7C15ull)
^ ((uint64_t)i << 32);
uint64_t chapterUID = MkvSplitMix64(&uidSeed);
editionSeed ^= MkvSplitMix64(&uidSeed);
NSMutableData *atom = [NSMutableData data];
[MP42Ebml appendElement:MP42MkvElementChapterUID
payload:MkvUIntData(chapterUID ? chapterUID : 1, 8)
to:atom];
[MP42Ebml appendElement:MP42MkvElementChapterTimeStart
payload:MkvUIntData(starts[i].unsignedLongLongValue * 1000000ull, 1)
to:atom];
uint64_t endMs = 0;
if (i + 1 < count) {
endMs = starts[i + 1].unsignedLongLongValue;
} else if (track.duration > starts[i].unsignedLongLongValue) {
endMs = track.duration;
}
if (endMs) {
[MP42Ebml appendElement:MP42MkvElementChapterTimeEnd
payload:MkvUIntData(endMs * 1000000ull, 1)
to:atom];
}
NSString *title = samples[i].title;
if (title.length == 0) {
title = [NSString stringWithFormat:@"Chapter %lu", (unsigned long)(i + 1)];
}
NSMutableData *display = [NSMutableData data];
[MP42Ebml appendStringElement:MP42MkvElementChapterString string:title to:display];
[MP42Ebml appendElement:MP42MkvElementChapterDisplay payload:display to:atom];
[MP42Ebml appendElement:MP42MkvElementChapterAtom payload:atom to:edition];
}
uint64_t editionUID = MkvSplitMix64(&editionSeed);
NSMutableData *editionOut = [NSMutableData data];
[MP42Ebml appendElement:MP42MkvElementEditionUID
payload:MkvUIntData(editionUID ? editionUID : 1, 8)
to:editionOut];
[editionOut appendData:edition];
NSMutableData *payload = [NSMutableData data];
[MP42Ebml appendElement:MP42MkvElementEditionEntry payload:editionOut to:payload];
return payload;
}
// Rewrites the source Info payload with the Duration element replaced by a
// fixed 8-byte slot holding the source value, and reports the slot's offset
// within the payload (pwrite-patched once the pass knows the real end) and
// the original value (written back unchanged if the pass produced nothing
// to measure). Returns nil — "copy Info verbatim instead" — when Info or a
// usable Duration element is missing: files that never had a Duration keep
// having none, players extrapolate those already.
- (nullable NSData *)infoPayloadForInfoKid:(MP42MkvKid *)infoKid
scanner:(MP42EbmlScanner *)scanner
durationOffset:(NSUInteger *)outOffset
durationOriginal:(double *)outOriginal
{
if (infoKid.el.sizeIsUnknown) {
return nil;
}
NSData *payload = [scanner readAtOffset:infoKid.el.dataStart
length:infoKid.el.dataSize
error:NULL];
if (!payload) {
return nil;
}
NSArray<MP42EbmlElement *> *kids = [MP42Ebml scanBuffer:payload from:0
length:payload.length error:NULL];
if (!kids) {
return nil;
}
NSMutableData *out = [NSMutableData data];
BOOL replaced = NO;
NSUInteger durationOffset = 0;
double original = 0;
for (MP42EbmlElement *el in kids) {
if (el.sizeIsUnknown) {
return nil;
}
BOOL isDuration = !replaced && el.identifier == MP42MkvElementDuration &&
(el.dataSize == 4 || el.dataSize == 8) &&
el.dataStart + el.dataSize <= payload.length;
if (isDuration) {
const uint8_t *bytes = (const uint8_t *)payload.bytes + el.dataStart;
original = MkvFloatValue(bytes, el.dataSize);
durationOffset = out.length + MkvIdWidth(MP42MkvElementDuration) +
[MP42Ebml encodedLengthForSizeValue:8];
[MP42Ebml appendElement:MP42MkvElementDuration payload:MkvFloatData(original) to:out];
replaced = YES;
} else {
[out appendData:RemuxBufferSlice(payload, el, payload.length)];
}
}
if (!replaced) {
return nil;
}
if (outOffset) {
*outOffset = durationOffset;
}
if (outOriginal) {
*outOriginal = original;
}
return out;
}
#pragma mark - SeekHead
// A Seek entry whose SeekPosition payload is a fixed-width placeholder;
@@ -1260,6 +1530,28 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
}
}
_writtenMaxBlockEnd = 0;
// Segment tick size in ns — needed to turn the millisecond Duration
// patch value into TimecodeScale units (Duration *is* scale-based,
// unlike chapter timecodes which are absolute ns).
uint64_t timecodeScaleNs = [self timecodeScaleForInfoKid:infoKid scanner:scanner];
// Chapters: decide up front whether the element exists at all,
// because the SeekHead plan below depends on it. With a replacement
// track: rebuild its payload (or remove the element when the model
// deleted every chapter row); without one: the old verbatim copy.
BOOL chaptersShouldExist = chaptersKid != nil;
NSData *chaptersPayload = nil;
if (self.replacementChapters) {
if (self.replacementChapters.chapterCount > 0) {
chaptersPayload = [self buildChaptersPayloadForTrack:self.replacementChapters];
chaptersShouldExist = YES;
} else {
chaptersShouldExist = NO;
}
}
// Progress: the output is roughly the input minus the dropped payload.
uint64_t totalEstimate = scanner.fileSize > droppedBytes ? scanner.fileSize - droppedBytes
: scanner.fileSize;
@@ -1404,7 +1696,7 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementTracks, &patchRel);
[seekIds addObject:@(MP42MkvElementTracks)];
[seekPatchRels addObject:@(patchRel)];
if (chaptersKid) {
if (chaptersShouldExist) {
MkvAppendSeekEntry(seekHeadPayload, MP42MkvElementChapters, &patchRel);
[seekIds addObject:@(MP42MkvElementChapters)];
[seekPatchRels addObject:@(patchRel)];
@@ -1461,15 +1753,36 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
}
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;
// Info: verbatim unless it carries a usable Duration element, which
// is rewritten as a fixed 8-byte slot patched after the clusters
// have streamed past (their end is only known at the very end).
uint64_t durationPatchAbs = 0;
double durationOriginal = 0;
if (infoKid) {
NSUInteger durationOffset = 0;
NSData *infoPayload = [self infoPayloadForInfoKid:infoKid
scanner:scanner
durationOffset:&durationOffset
durationOriginal:&durationOriginal];
if (infoPayload) {
NSMutableData *infoElement = [NSMutableData data];
[MP42Ebml appendElement:MP42MkvElementSegmentInfo payload:infoPayload to:infoElement];
if (![helper appendData:infoElement toFD:outFd outOffset:&cursor error:outError]) {
break;
}
durationPatchAbs = cursor - infoElement.length
+ MkvIdWidth(MP42MkvElementSegmentInfo)
+ [MP42Ebml encodedLengthForSizeValue:infoPayload.length]
+ durationOffset;
} else if (![helper copyFromScanner:scanner
source:infoKid.el.start
length:infoKid.el.totalSize
toFD:outFd
outOffset:&cursor
totalEstimate:totalEstimate
error:outError]) {
break;
}
}
BOOL extrasFailed = NO;
for (MP42MkvKid *kid in extras) {
@@ -1498,16 +1811,23 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
break;
}
// Chapters verbatim.
if (chaptersKid) {
// Chapters: rebuilt payload when the model edited them, source
// bytes otherwise, nothing at all when the model emptied them.
if (chaptersShouldExist) {
finalRels[@(MP42MkvElementChapters)] = @(cursor - segDataStartAbs);
if (![helper copyFromScanner:scanner
source:chaptersKid.el.start
length:chaptersKid.el.totalSize
toFD:outFd
outOffset:&cursor
totalEstimate:totalEstimate
error:outError]) {
if (chaptersPayload) {
NSMutableData *chaptersElement = [NSMutableData data];
[MP42Ebml appendElement:MP42MkvElementChapters payload:chaptersPayload to:chaptersElement];
if (![helper appendData:chaptersElement toFD:outFd outOffset:&cursor error:outError]) {
break;
}
} else if (![helper copyFromScanner:scanner
source:chaptersKid.el.start
length:chaptersKid.el.totalSize
toFD:outFd
outOffset:&cursor
totalEstimate:totalEstimate
error:outError]) {
break;
}
}
@@ -1559,6 +1879,28 @@ static void MkvAppendSeekEntry(NSMutableData *seekHeadPayload,
break;
}
// Patch Info's Duration slot with the end of the last block written
// (already +1 past the greatest start). A pass that wrote no
// measurable block — every cluster blockless, say — keeps the source
// value instead of zeroing it.
if (durationPatchAbs) {
// _writtenMaxBlockEnd is in ms; Duration is in TimecodeScale
// units. At the default scale (1e6 ns/tick) ms == ticks; at a
// non-default scale the end estimate already inherits this
// pass's cluster-timecode convention (cluster TCs are copied
// verbatim and the phase-3b cue math treats ticks as ms), so
// the conversion here is exact exactly where that is too.
double patchValue = _writtenMaxBlockEnd > 0
? (double)_writtenMaxBlockEnd * 1000000.0 / (double)timecodeScaleNs
: durationOriginal;
if (![helper writeData:MkvFloatData(patchValue)
fd:outFd
offset:durationPatchAbs
error:outError]) {
break;
}
}
// Attachments.
if (attShouldExist) {
finalRels[@(MP42MkvElementAttachments)] = @(cursor - segDataStartAbs);