Skip to content

feat: Read and write MP4 chapters - #147

Merged
decriptor merged 25 commits into
mainfrom
feat/mp4-chapters
Nov 22, 2026
Merged

decriptor merged 25 commits into
mainfrom
feat/mp4-chapters

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Mp4File.Chapters reads and replaces MP4 chapters. The new Mp4Chapter type holds a start time and a title. EndTime is derived from the next start, or from the end of the chapter track or file for the last chapter.

MP4 stores chapters in two places, and both are read and written:

  • QuickTime chapter track. This is a text track that another track names in its tref/chap reference. Each sample is one title: a 16-bit length, then UTF-8 text (or UTF-16 with a BOM), then optional modifier boxes such as encd. Timing comes from stts and the mdhd timescale. Sample positions come from stsc, stsz, and stco/co64. An empty edit in elst delays the track.
  • Nero chpl in moov/udta. It has no published spec. The layout here is the one ffmpeg writes and ffprobe and MediaInfo read back: FullBox v1, 4 reserved bytes, an 8-bit count, then per entry a 64-bit start in 100 ns units, an 8-bit length, and UTF-8 text. A 300-chapter ffmpeg file gets 255 entries, which shows the count is one byte. Version 0 is accepted with or without the reserved word, whichever layout ends exactly at the box end.

Motivation and Context

MP4/M4B chapters are the navigation in audiobooks and podcasts, and players (Apple Books, QuickTime, ffmpeg-based players) show them. TagLibSharp2 kept existing udta children through a save (#88), but it had no API to list or replace chapters. docs/MP4_ACCEPTANCE_CRITERIA.md had deferred chpl.

Closes #113

Design decisions

  • Read precedence. The chapter track is read first, which is how ffprobe reads these files. chpl is the fallback when there is no chapter track, or when a chapter sample lies outside the file or is not valid UTF-8/UTF-16 text. Validity is a scan (Utf8.IsValid on net8+, a Unicode Table 3-7 scan on netstandard, a surrogate-pair check for UTF-16), not a caught exception (for example, ffmpeg +global_sidx output, whose tfhd base offsets go stale). The track still bounds the last chapter's end. When both forms hold the same titles in the same order, the start times come from chpl. That keeps 100 ns precision and a first chapter that starts after zero. The chapter track's first sample always starts at 0, as ffmpeg writes it too. If the titles differ (a stale chpl), the track wins. When no chpl exists, an unreadable sample keeps its timing and gets an empty title.
  • Save writes both forms:
    • chpl gets the first 255 chapters, with titles cut to 255 UTF-8 bytes on a character boundary. The first chpl is replaced in place and any extra ones are dropped.
    • An existing chapter track is rebuilt under the same track_ID, and its chap references are left alone. It keeps its media timescale (falling back to 1000 Hz if a delta would overflow 32 bits), its tkhd flags, its mdhd language, and its hdlr box. Apple's locale-keyed chapter lookup returns nothing once the language turns into und.
    • Without a chapter track, a new disabled text track is added after the last trak (tkhd flags 2, text handler, self-contained dref). Its layout follows the brand. MP4 brands get nmhd and a tx3g 3GPP TextSampleEntry, as Apple TN2174 specifies for a Chapter Marker Track. QuickTime (major brand qt , or no ftyp, which ISO files must have) gets gmhd (gmin + text) and the QTFF text sample description with every field zero and an empty font name. AVFoundation and MediaInfo stopped listing chapters when the foreground colour was white. It takes track_ID max+1 (never below mvhd.next_track_ID), and next_track_ID is bumped. Every sound and video track gets a chap reference to it, except a track that a chap already names. Apple files keep chapter images in such a video track, and adding a reference to it made ffmpeg drop its attached-picture disposition. Existing chap entries keep their order.
    • Samples are the length, the UTF-8 text, and encd 0x100, the same layout ffmpeg and Apple use.
    • A set replaces every chapter title track with the one list. A file can hold one title track per language: AVFoundation picks one by locale, and ffprobe can take a later one. Chapters has no locale. So the first chapter text track is rebuilt, and every other one goes the way a clear removes it (trak, chap entries, unused trex). Every reader then shows the new list.
      • What stays: a chapter URL track, whose samples carry an href hypertext modifier (3GPP TS 26.245 §5.17.1.5), and chapter image tracks. A track whose chap named a removed title track then names the rebuilt one, so every track that had a chapter list keeps one.
      • A text track whose samples cannot all be read (outside the file, unparsable tables, or none in moov) cannot be told apart, so it stays too.
      • If such a track, or a title track, has samples in movie fragments, the set is refused, as the clear is.
      • The sample walk shares one step budget, the file's length, across every extra track.
      • Setting the list the file already reads is a no-op only when no other title track would remain.
      • The href rule is from the spec. AVFoundation, run as a black box, decodes a 3GPP href box as an HREF attribute on the chapter item (present with the box, absent without), which confirms the semantics. No real Apple enhanced-podcast file was available. apple_tags.m4a is truncated before its URL sample, which is why that track stays.
  • Reused track_IDs. track_IDs must be unique (§8.3.2.3), but files that reuse one exist. A chap entry is a track_ID (§8.3.3), and it resolves once, to the first trak with that ID. Every other decision is made on trak objects: chapter track, chapter media, presentation track, the replaced or removed trak, and where the new chunk offset is written (by trak position). IDs are compared only where the spec ties a structure to one: tref targets, tfhd (§8.8.7), trex (§8.8.3). The add path and the read path share one chapter-media rule: what a chap resolves to, unless that trak holds a chap of its own or is a sound trak.
  • Sample data placement. The new samples go in a new mdat right after moov, so the existing AdjustChunkOffsets pass moves every later offset by moov delta + mdat size. The chapter track is built with chunk offset 0, which no shift moves, and that offset is set once the position is known. ISO 14496-12 allows any number of mdat boxes.
  • Repeated edits do not grow the file. Sometimes the box right after moov is an mdat that holds only the old samples of the chapter tracks being rebuilt or removed. One rule decides this: the old samples must cover its payload exactly, and every byte range anything else in the file references must be computed and avoid it. Anything that cannot be computed keeps the mdat.
    • Traks: every trak other than the replaced trak objects (compared by object, so a trak that shares the chapter track's ID is still checked). Chunk extents come from stco/co64 + stsc + stsz or stz2, with checked arithmetic; an overflow keeps the mdat.
    • Items: every iloc in a meta at file, movie or track level (§8.11.3, construction method 0 extents). A meta without an iloc references nothing. An iloc that does not parse keeps the mdat, and so does an unread box tail that holds the bytes iloc. An iloc there could not be read, while unread bytes without that type code cannot hold one. This lets iTunes metas with stray trailing bytes, like bgo_676934.m4a, stay constant in size.
    • Aux info: every saio offset (§8.7.9; absolute in an stbl, from the traf base in a fragment) with the saiz total after it. A saio without a saiz keeps the mdat.
    • Fragments: every traf run.
    • Cost: each range is tested as it is found and none is stored. Zero-width iloc extents (§8.11.3 allows field sizes of 0) count once per item, and any other extent count must fit the box's bytes. A crafted 559 KB iloc file now saves in 0.13 s at 52 MB peak; it ran out of memory before.
      That is always true of an mdat a previous chapter save wrote. In that case the mdat is dropped, and moov plus that mdat count as one region for the offset update, so every later offset moves by the change in the region's size. Clearing the list drops it the same way. Old chapter samples that share an mdat with audio, as in ffmpeg-written files, stay there as dead bytes. Only the first edit of such a file adds an mdat; later edits replace it.
  • Clearing. An empty list removes chpl, every track a chap reference names, and those references. That covers the titles and Apple's chapter URL and chapter image tracks, because Apple players list chapters from any of them. A named track that holds a chap reference of its own is a presentation track and stays. That is decided per trak object: a trak that only shares the named track's track_ID (invalid per §8.3.2.3, but seen) does not make it a presentation track. Every remaining trak then loses its chap entries for the removed IDs, including a trak that shares one. An emptied chap, tref, udta, or trex is dropped.
  • Fragmented movies (moov/mvex, ISO 14496-12 §8.8):
    • Reading: a track's samples are its moov samples followed by its fragment samples. Reading is lenient, as ffprobe, AVFoundation and MediaInfo are: a moof or traf with stray trailing bytes, or a traf that cannot be read, does not hide the samples around it. Chapter samples are read from every traf of the chapter track, using the tfhd base (explicit, moof, or the end of the previous traf's data), tfhd and trex defaults, tfdt, and trun offsets, durations, and sizes. The last chapter's end comes from the fragments, so an empty_moov file no longer gets a zero-length last chapter.
    • Writing: changing (or clearing) the chapters of a track that has, or may have, fragment samples fails. A moof with an unread tail, or a traf whose track cannot be told, counts as "may have". SaveToFile and SaveToFileAsync return an error that says why, Render returns empty, and no file is written. Rebuilding that track in moov would leave the fragment samples as a second chapter list. This is what made ffprobe and AVFoundation show 6 chapters, and the file grow on every edit.
    • A fragmented movie whose chapter samples are all in moov is rewritten as usual. Its old chapter mdat is replaced only when no traf run reaches into it, so repeated edits keep a constant size. That guard fails closed: if any traf, trun, or moof or traf tail cannot be read, or the file has an unread tail, the mdat is kept.
    • A fragmented movie with no chapter track gets chpl only, as before.
  • No-op saves. A save that does not touch the list, or sets the list the file already holds, keeps the chapter bytes. Render compares the requested list with the list in the data being saved, so saving the same Mp4File again over its own output is byte-identical.
  • Untrusted input. Each sample read is capped at 2 + 65,535 bytes. Total reads are capped at the file length, so overlapping samples cannot multiply the work. A constant-size stsz is capped at 65,535 samples. Every table walk is bounded by its box bytes, and chapter tracks are found through a track_ID map. Byte-flip and truncate-at-every-byte matrices run over span and stream reads.
  • Stream read (MediaFile.Read(stream)) keeps skipping mdat and reads chapter samples from the stream at their offsets.
  • Twin found and fixed (separate commit). The byte-flip matrix found that a version 1 mvhd/mdhd with a 64-bit duration past TimeSpan.MaxValue threw out of Mp4File.Read. It also threw from Mp4AudioPropertiesParser.Parse, which has four sibling conversions. All five now saturate.

Out of scope

  • On a replace, chapter image and URL tracks are kept but not edited, so their timing still follows the old chapters. Clearing removes them.
  • No chapter track is added to a fragmented movie (mvex needs a trex per track) or to a moov with no trak. chpl carries the list alone there. Chapters in movie fragments are read but cannot be changed (see above).
  • Chapters and the tag are separate. ClearAllMetadata() and Tag = null clear every tag field, mapped and unmapped. Chapters are file structure, not tag fields: the chapter track and chpl stay, and Chapters = [] removes them. Chapters = [] in turn keeps the tag. Both are documented (the ClearAllMetadata summary, the Chapters remarks, the CHANGELOG) and pinned. Matroska on main does the same.
  • Changes stay in the chapter/save area of Mp4File and in new files, to keep the conflict with fix: Read MP4 gnre and keep unedited ilst atoms #133 (Mp4Tag/ilst) small.

Spec references

ISO 14496-12 §8.2.2 (mvhd), §8.3.2 (tkhd), §8.3.3 (tref), §8.4.2 (mdhd), §8.4.3 (hdlr), §8.5.2 (sample entry), §8.6.1.2 (stts), §8.6.6 (elst), §8.7.2 (dref), §8.7.3 to §8.7.5 (stsz/stsc/stco/co64), §8.4.5.2 (nmhd), §8.8.1 (mvex), §8.8.3 (trex), §8.8.7 (tfhd), §8.8.8 (trun), §8.8.12 (tfdt). Apple TN2174 "Chapter Marker Track" (nmhd, TextSampleEntry, disabled track, chap from an enabled track). QuickTime File Format: "Chapter lists", track reference type chap, "Text sample description", "Base media information header atom" / "Base media info atom" (gmhd/gmin), "Text media information atom". 3GPP TS 26.245 §5.16 to §5.17 (TextSampleEntry, sample modifiers). The chpl layout comes from black-box output of ffmpeg 9.0.2, read back with ffprobe and MediaInfo. No GPL source was consulted.

Type of Change

  • Bug fix (non-breaking change that fixes an issue): duration overflow
  • New feature (non-breaking change that adds functionality)
  • Breaking change
  • Documentation update

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed (CHANGELOG Unreleased, README matrix, docs/MP4_ACCEPTANCE_CRITERIA.md)
  • My changes generate no new warnings

Testing

Gates:

  • dotnet build -c Release: 0 warnings, 0 errors (netstandard2.0, netstandard2.1, net8.0, net10.0)
  • dotnet test -c Release: net8.0 6014 passed, 39 skipped, 0 failed; net10.0 6014 passed, 39 skipped, 0 failed (on main f1ecb88; merges cleanly with 2ca56f8)
  • dotnet format --verify-no-changes: clean. dotnet list package --vulnerable --include-transitive: none
  • Public API snapshot updated: Mp4Chapter, Mp4File.Chapters

Unit tests (Mp4ChapterTests and Mp4ChapterTextTests, 187 cases; the integration class below adds 5 more): built in code with real sample tables (audio samples in mdat), moov first and moov last. They cover reading chpl (v1, v0, 100 ns, out of order), the text track (UTF-8, UTF-16 BOM, sbtl, co64, empty edit), precedence, fallback, and span vs stream reads. Saves cover new, replace, clear, 300 chapters, 400-byte titles, mvex, no trak, Apple image/URL tracks, dangling chap ids, and next_track_ID. In every save the audio sample bytes are compared at their new offsets. No-op saves are checked for byte identity: untouched list, same list, title edit, and a second save. Repeated edits: five chapter edits in a row (moov first and last, starting with and without chapters). Every edit is the size of edit 1, the audio bytes are unchanged, and exactly one chapter mdat follows moov. A growing list replaces its own mdat, and clearing after an edit drops it. The mdat is kept when it has extra bytes, when another track's offset points into it, or when it is shared with audio. Malformed input: truncation at every byte, byte flips across moov, a huge stsz count, and overlapping 4 GiB samples. Guard reverts were checked red: chapter-media skip, read budget, Render list comparison, duplicate-id guard, chpl start rule, mvex guard, first-sample-at-zero, the duration clamp, and the chapter-mdat checks (exact coverage, other-track reference, drop).

Integration tests (Mp4ChapterIntegrationTests, TAGLIBSHARP2_TEST_MP4_CHAPTERS=<file>): 5/5 passed locally for each of a.m4a, a_fast.m4a, a.m4b, book.m4b, v.mp4, v.mov, and apple_tags.m4a. In round 6 they also passed on regenerated a.m4a, a_fast.m4a, a.m4b, v.mp4, v.mov, frag.m4a, frag_moov.m4a and many.m4a, on stz2.m4a and topmeta.m4a, and on the shared-ID dup_tref.m4a. The first version of the suite (4 tests) also passed on a_nochpl.m4a, late.m4a, and many.m4a. They check read, replace with a per-track sample SHA-256 match, five edits in a row at a constant size, clear, and a title edit that keeps the chapters.

Real-file verification

Inputs: ffmpeg 9.0.2 -f ffmetadata chapters with -map_chapters (m4a moov-last and +faststart, m4b, +disable_chpl, first chapter at 2 s, 300 chapters, H.264+AAC mp4 and mov, and a 30-minute/60-chapter m4b), the same files without chapters, and the TagLib# samples sample.m4a, sample.m4v (truncated), apple_tags.m4a (iTunes, chap → titles, images, URLs; truncated), and bgo_658920.m4a.

Commands for each file: set 3 chapters (One@0, Two ü 日本@1.25 s, Three@2.5 s), then:

  • ffprobe -show_chapters
  • mediainfo (both Menu sections: track and chpl)
  • ffmpeg -v error -i out -map 0:a? -map 0:V? -f null -
  • ffmpeg -map 0:a? -map 0:V? -c copy -f streamhash -hash sha256, before vs after
  • a save with nothing changed (cmp), re-setting the same list on the output (cmp), and clearing (ffprobe chapter count, stream hash)
File ffprobe titles MediaInfo (track + chpl) Decode A/V stream hashes No-op save Re-save same list Clear
a.m4a, a_fast.m4a, a.m4b, a_nochpl.m4a, late.m4a, many.m4a One / Two ü 日本 / Three 6/6 clean equal identical identical 0 chapters, hash equal
v.mp4, v.mov same 6/6 clean equal (2 streams) identical identical 0, equal
book.m4b (30 min, 60 ch) same 6/6 clean equal identical identical 0, equal
plain.m4a, plain_fast.m4a, plain_v.mp4 (new track created) same 6/6 clean equal identical identical 0, equal
sample.m4a, bgo_658920.m4a same 6/6 clean equal differs* identical 0, equal
sample.m4v (truncated) same 6/6 same as input** equal (2) differs* identical 0, equal
apple_tags.m4a (truncated, image + URL tracks) first title empty*** 6/6 clean equal differs* identical 0, equal

* These inputs already re-save non-identically on main because the ilst is re-rendered. I checked by building origin/main: its no-op output is byte-identical to this branch's. A title edit is byte-identical to main for every file in the table, so a save that leaves chapters alone keeps the chapter bytes.
** Same "no decoder for stream 1" as the untouched input.
*** ffprobe drops the first title of this Apple file before and after the save (it reads 7 untitled chapters from the original). MediaInfo shows the new list. The attached_pic disposition of the chapter image track is kept.

Five edits in a row

Each round sets 3 chapters with new titles of the same length. For every round I checked ffprobe titles and starts, MediaInfo (6/6 lines), a clean decode, and an unchanged A/V streamhash against the original.

File Original size Size after edits 1..5 All checks Top level after edit 5
a.m4a (moov last) 45967 46008 ×5 pass ftyp free mdat moov mdat
a_fast.m4a (faststart) 45967 46008 ×5 pass ftyp moov mdat free mdat
a.m4b 45967 46008 ×5 pass ftyp free mdat moov mdat
book.m4b (30 min, 60 ch) 7640981 7639734 ×5 pass ftyp free mdat moov mdat
plain.m4a / plain_fast.m4a (no chapters before) 45222 45902 ×5 pass as above
v.mp4 / v.mov 60989 / 61064 61010 ×5 / 61061 ×5 pass ftyp free/wide mdat moov mdat

Clearing after edit 5 drops the chapter mdat. a.m4a ends up ftyp free mdat moov and a_fast.m4a ftyp moov free mdat. ffprobe then reports 0 chapters, and the streamhash is unchanged.

Review round 1

Each finding has a pinning test that fails at 71aa72d and passes now:

  • Fragments: Read_FragmentedChapterTrack_ReadsSamplesFromMovieFragments (moof base, explicit base, previous-traf base), Read_FragmentedChapterTrack_TfdtSetsTheDecodeTime, Save_FragmentedMovieWithChapterTrack_RefusesAChapterChange, SaveToFileAsync_FragmentedMovieWithChapterTrack_RefusesClearing, Save_FragmentedMovieWithChapterSamplesInMoov_ReplacesWithoutGrowing.
  • Language: Save_ReplaceChapters_KeepsLanguageHandlerAndTrackFlags.
  • Per-brand layout: Save_NewChapters_Mp4BrandWritesNmhdAndTx3g and Save_NewChapters_QuickTimeBrandWritesGmhdAndQtffTextDescription.
  • Clearing: Save_ClearChapters_RemovesChapterImageAndUrlTracks.

Before vs after (71aa72d vs now):

  • The 585-file MediaFile.Read corpus changes in one answer, frag.m4a's last chapter end (2.5 s → 4.0 s, as ffprobe reports).
  • Reading frag_nochpl.m4a now gives the three fragment chapters (it was empty).
  • No-op and title-edit saves of 52 MP4 files: 0 byte differences.
  • The 29-file chapter matrix changes only for the cases above:
    • frag.m4a and frag_nochpl.m4a: the edit is refused, where ffprobe and AVFoundation used to show 6 chapters.
    • frag_moov.m4a: 5 edits now keep a constant size, where it used to grow.
    • v.mov: AVFoundation's locale is en, where it was und.
    • Apple samples: clearing leaves AVFoundation with 0 chapters, where it had 7.
    • The new and replaced tracks are smaller (nmhd instead of gmhd).
  • ffprobe, MediaInfo (6 lines), AVFoundation and mutagen read every saved non-refused file.

Review round 2

Each finding has a pinning test that fails at dce5295 and passes now:

  • Read_ChapterSampleThatIsNotText_FallsBackToChpl (moov and fragment rows).
  • Save_ChapterMdatNextToFragmentData_IsKeptWhenATrafPointsIntoIt rows 1 to 3: a malformed traf, a track_ID 0 traf, a traf without tfhd.
  • Save_NewChapters_NoFtypWritesTheQuickTimeLayout.

The guards that were untested now go red when reverted:

  • The soun exclusion: Save_ClearChapters_KeepsASoundTrackThatChapNames.
  • The tfhd 0x2 skip: Read_FragmentedChapterTrack_TfhdDefaultsAfterSampleDescriptionIndex.
  • The unread moof tail, traf tail and file tail: rows 4 to 6 of the mdat-guard test.

Before vs after (dce5295 vs now):

  • Read corpus (613 files, adding the reviewer's g2 and noftyp files): one change, fa_sidx.m4a. It now has Intro / Middle ü / End 日本, as ffprobe and chpl give; it had U+FFFD junk.
  • noop, title, set3 and clear saves of 84 MP4 files (296 outputs): only the two ftyp-less MOVs differ (gmhd + QTFF text). ffprobe, MediaInfo, AVFoundation (locale kept) and mutagen read both, decode is clean and A/V hashes are equal.
  • The 42-file chapter matrix changes only for v_free.mov's layout.

Review round 3

This round also rebases onto main 85ce8d2. The CHANGELOG is merged: one [Unreleased], with the MP4 duration fix under Fixed next to the Ogg entries.

Each finding has a pinning test that fails at 649f8bd and passes now:

  • Read_ManyInvalidChapterSamples_DecodeWithoutExceptions: 65,535 invalid samples, no first-chance DecoderFallbackException. On the reviewer's perf/bad.m4a, a read costs 27.6 ms and 24.6 MB, against 256–262 ms and 101 MB before; the valid control is 25 ms and 17.9 MB.
  • Save_ChapterMdatReferencedByAnotherTrack_IsKept, rows 1 to 9: bad box in stbl, in trak, a trak in moov's tail, a chunk running into the mdat, iloc in moov, a co64 hidden behind a bad box, no stsz, and a chunk or size table past its box.
  • Read_FragmentWithTrailingBytes_StillReadsItsChapters (moof, traf) and Read_FragmentWithAnUnreadableTrafForAnotherTrack_StillReadsTheChapterTraf.
  • Save_ChapterTrafInAnUnreadMoofTail_IsRefused.

The guard's fail-closed result is also pinned directly by HoldsOnlyReplacedSamples_UnreadableFragment_FailsClosed.

Before vs after (98b8b61, the rebased 649f8bd, vs now):

  • Read corpus (640 files): only rt/moof_tail.m4a and rt/traf_tail.m4a change, from no chapters to 3, as ffprobe, AVFoundation and MediaInfo read them.
  • Saves (noop, title, set3 and clear over 105 MP4 files): only the reviewer's crafted files change.
    • The tw/ stblbad, trakbad and moovtail files keep the chapter mdat (they dropped it).
    • fo/ files with malformed trafs refuse the chapter change, and so do the rt/ fragment files whose chapter traf may sit in a fragment.
    • Every other output is byte-identical.

Review round 4

The mdat drop guard is now the single rule above. It replaces the moov-only checks and the top-level-meta rule, both of which blocked legal files. Rows of Save_ChapterMdatReferencedByAnotherTrack_IsKept that fail at 383a4a2:

  • 11 and 16-19 (keep or drop, per the rule);
  • 12 (drop: an hdlr-only file-level meta);
  • 15 (drop: stz2 with the chunk elsewhere);
  • 21 (drop: 4-bit stz2 ending at the mdat).

Rows 10, 13, 14, 20, 22 and 23 pass at both heads; they pin the rule's other branches. Read_ImplicitBaseAfterAnUnreadableTraf_IsUnknown rows 1 and 2 also fail at 383a4a2.

Real files, 4 chained edits each:

  • tw4/topmeta.m4a stays at 34668 bytes and tw4/stz2.m4a at 34275 (both used to grow by 56 bytes per edit).
  • meta_bad_iloc, dup, big_ctrl and big_ovf keep the mdat.
  • The integration suite passes 5/5 on topmeta and stz2; its sample hash now reads stz2.
  • ib/ff_badtfhd, ff_traftail, ib_badtfhd and ib_badtrun read the chpl titles, not junk.
  • Clearing dup.m4a keeps the sound trak that shares the chapter track's ID; it used to be deleted.

Review round 5

These pins fail at 4863573:

  • Save_ZeroWidthIlocExtents_CostOnlyTheirBytes (allocation bound: under 8 MB where 4863573 allocated hundreds of MB);
  • Save_ChapterMdatReferencedByAnotherTrack_IsKept row 27 (saio in the mdat, keep);
  • Save_ClearChapters_SharedTrackId_DropsTheChapReferenceAndKeepsTheTrex.

The guards the review found unpinned now go red when reverted:

  • row 24 (an unread file tail holding an iloc);
  • row 25 (an iloc extent_length of 0 runs to the end);
  • row 26 (stz2 4-bit nibble order);
  • the shared-ID test (a trex stays while a remaining trak uses its ID).

Row 28 (saio elsewhere, drop) passes at both heads.

Clearing tw4/dup.m4a now leaves no chap reference: ffprobe lists 0 chapters and both streams as audio. adv/saio_in.m4a keeps its aux-info bytes.

Review round 6

A sound trak that shares the chapter track's track_ID and keeps its own chap reference made the text track look like a presentation track, so a clear removed only chpl. Holders are now trak objects, and the remove pass of ReplaceReferences no longer skips a trak by ID. On the reviewer's dup_tref.m4a a clear now leaves 0 chapters in ffprobe, two audio streams with unchanged stream hashes, and no tref, chap or text trak.

These pins fail at c3c5be1:

  • Save_ClearChapters_SharedTrackId_DropsTheChapReferenceAndKeepsTheTrex (True). The copied sound trak keeps its tref.

Guards from round 5 that had no test now go red when reverted:

  • TryIlocRanges_ZeroWidthExtents_WalkOneExtentPerItem. A step counter, not wall clock: at most 64 steps for 64 items of 65,535 zero-width extents. Without the cap all 64 × 65,535 = 4,194,240 extents are walked.
  • PatchIloc_ZeroWidthExtents_WalkNone. PatchIloc returns the extents it walked: 0 here.
  • Save_TrafAuxInfo_IsAReference (True). A traf saio, from an explicit base, into the chapter mdat.
  • Save_ChapterMdatReferencedByAnotherTrack_IsKept row 29. A version 1 saio; read as 32-bit, its offset would miss.
  • Row 30. A saio without a saiz.

Save_EditChapters_SharedTrackId_RewritesOnlyTheChapterTrack covers the edit path on the same file shape. The chunk offset and the replacement land on the chapter trak, and the sound trak still reads its audio. It goes red when WriteChunkOffset writes every trak with the ID.

The clear and the reference walk scanned the list of removed traks for every moov child, so their work grew with traks × chapter tracks, both counts set by the file. They now make one set lookup per trak. ClearChapters_ManyChapterTracks_LooksEachTrakUpOnce counts the lookups on a moov with 2,000 chapter tracks, and it goes red with either list scan restored.

Checks run on the new code:

  • 1,043,528 truncation and bit-flip cases over 20 shared-ID, saio, iloc and fragment files: span and stream reads, set, clear. None threw.
  • Crafted inputs with hostile counts, up to 32,000 chapter tracks and 65,535 × 65,535 zero-width iloc extents. Allocation stays linear in the file size.

Review round 7

Adding a chapter track skipped every sound or video trak whose track_ID some chap named. A sound trak sharing its ID with a chapter image trak (the reviewer's cm_only.m4a) therefore never referenced the new track, and each edit added another one: 34653 -> 35136 -> 35634 -> 36132 bytes. The add path now uses the read path's chapter-media rule, by trak object. On cm_only, three edits stay at 35134 bytes, ffprobe, MediaInfo and mutagen read the new titles, and a clear leaves 0 chapters.

These pins fail at a40cd76:

  • Save_NewTrack_EverySoundTrakThatIsNotChapterMedia_GetsTheReference, rows cm_only, cm_img, cm_sfirst and cm_audref.
  • Save_RepeatedEdits_SharedTrackIdShapes_KeepOneChapterTrackAndTheSize (cm_only).

The repeated-edit property runs over the seven shared-ID shapes (dup, dup_tref, sonly, cm_img, cm_sfirst, cm_audref, cm_only). For each, four edits are the same size, the same edit again is byte-identical, one chapter track reads back, and a clear leaves none.

The self-reference test (ReferenceEquals (target, trak)) is now pinned by a sonly row in the shared-ID clear and edit tests: only the trak that shares the ID holds the reference. Restoring the by-ID test turns those rows red.

The integration tests now key their per-track sample hashes by trak position, so a trak sharing an ID with the chapter track has its samples checked too.

Rebased onto main 88f91b7. Only CHANGELOG.md and docs/Cookbook.md conflicted, and both now add only the MP4 entries.

Per-language chapter title tracks (F4): a set now leaves one title track. On a valid eng + deu file (two_lang.m4a), every reader shows the new list after a set: ours, ffprobe, MediaInfo (one list), mutagen, and AVFoundation (one locale; best match for ["de","en"] gives the new titles). Before, ffprobe and AVFoundation de kept the old ones. The next edit keeps the size (34688 bytes), and a clear leaves nothing.

These pins fail at 7703c2f:

  • Save_SetChapters_SecondTitleTrack_IsReplacedByTheOneList;
  • Save_SetChapters_TheListAlreadyRead_StillLeavesOneTitleTrack;
  • Save_SetChapters_ExtraTextTrackWithFragmentSamples_IsRefused, both rows.

These pass at both heads and go red with their guard reverted:

  • Save_SetChapters_UrlTrackWithHref_IsKept;
  • Save_SetChapters_ExtraTextTrackThatCannotBeTold_IsKept, rows unreadable and empty;
  • Plan_ManyExtraTitleTracks_ExamineAtMostTheFileLength, a step count.

Rebased again onto main 577eaaf. Only README.md conflicted: main added an AAC column and footnote ¹⁰, so the Chapters row has an AAC cell and its footnote is ¹¹.

Rebase onto #133 (main f1ecb88)

#133 rewrote the MP4 tag save path: moov/meta placement, udta kept in its place, QuickTime keys, and Clear removing all metadata. The conflict in Mp4File.cs is resolved by keeping #133's path and threading the chapter plan through it:

  • the moov children come from the chapter plan;
  • chpl passes through BuildUdtaBox/RebuildUdta.
  • When the tag lives in moov/meta, fix: Read MP4 gnre and keep unedited ilst atoms #133 copies udta as it was. A chapter save there now rebuilds udta with no tag in it, so its meta keeps its bytes (RebuildMeta keeps every child of a meta with no ilst) and only chpl changes.

New pins:

  • Save_TagClear_KeepsTheChapters (ClearAllMetadata and Tag = null);
  • Save_ChapterClear_KeepsTheTag;
  • Save_Chapters_TagInMovieMeta_RewritesOnlyTheChapters (set and clear);
  • Save_Chapters_TagInMovieMeta_CopiesUdtaMetaAsItWas;
  • Save_TitleAndChapters_TagInMovieMeta_WritesBoth.

Copying udta unchanged whenever the tag is in moov/meta (the pre-merge rule) turns three of them red.

Checks after the merge:

  • ffprobe, mutagen, MediaInfo and AVFoundation show the chapters kept after a tag Clear and the title kept after a chapter clear.
  • Chapter read-back after set and clear is identical to f328c89 on all 224 grid files.
  • No-op and title-edit outputs are byte-identical to main's.
  • The shared-ID shapes and the edit-idempotence property pass.

Review round 8

  • Retargeting: a set no longer leaves a track without a chapter list when its only chap named a removed title track. That entry now names the rebuilt title track, once and in place; a clear still drops it.
    • On the reviewer's split_en and split_dis, both audio traks end with chap [2], and every reader shows the new list.
    • Pins: Save_SetChapters_TrackNamingARemovedTitleTrack_NamesTheRebuiltOne, and RebuildTref_Retarget_NamesTheRebuiltTrackOnceInPlace (order and dedupe).
  • A crash found while pinning that: when the first title track held a chap of its own naming a removed title track, the set threw ArgumentOutOfRangeException. The removal had rewritten the trak object the set was about to replace.
    • The removal now runs after the rebuilt trak is in place.
    • Pin: Save_SetChapters_TitleTrackHoldingAChapToTheRemovedOne_IsRebuilt. Revert either change and it goes red.
  • Docs: the ClearAllMetadata summary states the chapter exception, and the href citation is §5.17.1.5.

Additional Notes

Mp4File.Read now decodes chapter samples, bounded as above. Reading a file without chapters does no extra I/O.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.50790% with 332 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.16%. Comparing base (f1ecb88) to head (210f1c7).
⚠️ Report is 39 commits behind head on main.

Files with missing lines Patch % Lines
src/TagLibSharp2/Mp4/Mp4ChapterCodec.cs 84.31% 89 Missing and 111 partials ⚠️
...gLibSharp2.Tests/Mp4/Mp4ChapterIntegrationTests.cs 5.17% 110 Missing ⚠️
src/TagLibSharp2/Mp4/Mp4File.cs 89.51% 11 Missing and 2 partials ⚠️
...ts/TagLibSharp2.Tests/Mp4/Mp4ChapterTestBuilder.cs 97.78% 3 Missing and 4 partials ⚠️
src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs 80.00% 1 Missing ⚠️
src/TagLibSharp2/Mp4/Mp4Chapter.cs 94.11% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #147      +/-   ##
==========================================
- Coverage   93.25%   93.16%   -0.10%     
==========================================
  Files         364      382      +18     
  Lines       76942    80902    +3960     
  Branches     8305     9096     +791     
==========================================
+ Hits        71754    75369    +3615     
- Misses       3057     3260     +203     
- Partials     2131     2273     +142     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@decriptor
decriptor force-pushed the feat/mp4-chapters branch 6 times, most recently from 7703c2f to f328c89 Compare November 22, 2026 17:46
A version 1 mvhd or mdhd stores a 64-bit duration (ISO 14496-12 §8.2.2,
§8.4.2). With a small timescale the seconds overflow TimeSpan, and
TimeSpan.FromSeconds threw out of Mp4File.Read and
Mp4AudioPropertiesParser.Parse. All five conversions now saturate at
TimeSpan.MaxValue.
Mp4File.Chapters lists and replaces the chapter list. Mp4Chapter holds
a start time and title; the end time is the next start, or the track or
file end.

Reading takes the QuickTime chapter track: the text track a tref/chap
reference names (ISO 14496-12 §8.3.3). Samples are a 16-bit length and
UTF-8 or BOM-led UTF-16 text (3GPP TS 26.245 §5.17), timed by stts and
the mdhd timescale and placed by stsc, stsz, and stco/co64. Without a
readable track, the Nero chpl box in moov/udta is read: version 1, four
reserved bytes, an 8-bit count, then 64-bit 100 ns starts and
length-prefixed UTF-8 titles, the layout ffmpeg writes. When both forms
hold the same titles, chpl supplies the start times.

Saving writes both forms. chpl gets the first 255 chapters. An existing
chapter track is rebuilt under its track_ID; otherwise a disabled text
track is added and every sound and video track that is not chapter
media gets a chap reference. The new samples go in an mdat right after
moov, so the existing chunk-offset update moves every later offset.
A fragmented movie or a moov with no trak gets chpl only. An empty list
removes chpl, the track, and its references. A save that leaves the
list as the file holds it keeps the chapter bytes.

Sample reads stop at 65,537 bytes each and at the file length in total.
The acceptance criteria deferred the chpl atom; it now describes both
chapter forms and the save rules. The README matrix gains a chapters
row, and the changelog an Unreleased entry.
Chapters documents its list as ordered by start. A chapter track is
ordered by its sample times, but chpl entries need not be. Reading now
applies the same stable sort the setter uses, so a save compares like
with like.
Apple files name a second text track (chapter URLs) in chap next to the
titles. After the titles track was removed, that track read back as the
chapter list, so an empty list did not stay empty. Clearing now removes
every text track a chap reference names, and those references; chapter
image tracks stay.

Chapter tracks are now found through a track_ID map, so a moov with many
traks and long chap lists is not scanned once per reference.
A truncated sample file ends mid-track. The tests now hash the samples
that lie inside the file, which are the same before and after a save.
Each chapter save added an mdat after moov and left the previous
chapter samples unreferenced, so N edits left N-1 dead copies. When the
box right after moov is an mdat whose payload is tiled exactly by the
old samples of the chapter tracks being rebuilt or removed, and no
other track has a chunk offset inside it, that mdat is dropped and the
new one takes its place. moov and that mdat are treated as one region,
so the existing offset update moves every later offset by the change in
the region's size. Clearing the list drops it the same way.

Old chapter samples that share an mdat with other media, as in files
ffmpeg writes, still stay in place unreferenced; only the first edit of
such a file adds an mdat.
…identity

Fragments: a track's samples are those in its moov sample table
followed by those in movie fragments (ISO 14496-12 §8.8.1). Chapter
samples are now read from every traf of the chapter track: tfhd base
offsets (explicit, moof, or the end of the previous traf's data) and
defaults, trex defaults, tfdt decode time, and trun offsets, durations,
and sizes (§8.8.3, §8.8.7, §8.8.8, §8.8.12). A chapter change on a track
that has fragment samples is refused with an error from SaveToFile,
because rebuilding it in moov would leave the fragment samples as a
second list. A fragmented movie whose chapter samples are all in moov
is rewritten as before, and its old chapter mdat is replaced only when
no traf run reaches into it. Clearing drops the removed tracks' trex.

A replaced chapter track keeps its tkhd flags, mdhd language, and hdlr:
Apple's locale-keyed chapter lookup found nothing once the language
became und.

A new track follows its brand. MP4 gets nmhd and a tx3g TextSampleEntry
(Apple TN2174, Chapter Marker Track); QuickTime gets gmhd and the QTFF
text sample description, all fields zero. AVFoundation and MediaInfo
stopped listing the chapters with a white foreground colour.

Clearing now removes every track a chap reference names, including
Apple chapter image tracks, so Apple players list no chapters either. A
track that holds a chap reference of its own is a presentation track
and stays.
The Cookbook's audiobook chapters section shows Mp4File.Chapters next to
the ID3 CHAP example. The changelog and acceptance criteria cover
fragment reads, the refused edit, the kept language, the per-brand track
layout, and clearing chapter image tracks.
A chapter sample whose bytes are not valid UTF-8, or not valid UTF-16
after its byte order mark (Apple TN2174), is not a title. ffmpeg's
+global_sidx output keeps a tfhd base_data_offset that predates the
sidx it inserts, so the fragment offsets land on audio data. Such a
sample now yields to chpl like a sample outside the file; without chpl
it keeps its lossy decoding. The track's end still bounds the last
chapter when chpl supplies the titles.

The guard that keeps an earlier chapter mdat fails closed: a traf or
trun it cannot read, an unread moof or traf tail, or an unread tail
after the last top-level box in a fragmented movie means the mdat is
kept. A traf for track_ID 0 no longer stops the scan.

A file with no ftyp is QuickTime and gets the QuickTime chapter track
layout. The QuickTime text description comment names white, the only
foreground colour seen to hide the chapters. New tests pin the sound
track kept by a clear and the tfhd sample_description_index skip.
…unread tracks

Chapter text validity is a scan, not a caught DecoderFallbackException:
Utf8.IsValid on net8+, a Unicode Table 3-7 scan on netstandard, and a
surrogate-pair check for UTF-16. A file of 65,535 invalid samples reads
in the time and memory of a valid one again.

The guard that drops an earlier chapter mdat now fails closed on moov as
well as on fragments. A track whose sample table cannot be fully read
(an unread trak, mdia, minf or stbl tail, a missing stsz or stsc, or a
count past its box), a trak in moov's unread tail, an iloc in moov, or a
top-level meta keeps the mdat. A chunk spans its samples, so a chunk
that starts before the mdat and runs into it counts.

Reading fragments is lenient again: an unread moof or traf tail, or a
traf it cannot read, no longer hides the chapter samples around it. The
refusal of a chapter change also fails closed: a moof tail or a traf
whose track it cannot tell may hold chapter samples.
…mputed

One rule decides whether the chapter mdat after moov goes: the replaced
samples must tile it, and every byte range anything else in the file
references must be computed and avoid it. Anything that cannot be
computed keeps it.

- Traks: every trak other than the replaced trak objects, compared by
  object rather than track_ID, so a trak that shares the chapter
  track's ID is checked. Chunk extents come from stco/co64 and stsc with
  stsz or stz2 (§8.7.3.3, 4-, 8-, or 16-bit entries), with checked
  arithmetic: an overflow keeps the mdat.
- Items: every iloc in a meta at file, movie, or track level, parsed per
  §8.11.3; construction method 0 extents are file ranges. A meta without
  an iloc references nothing and no longer blocks the drop. A meta that
  stops parsing, an unread tail that names a meta or an iloc, or an iloc
  that does not parse keeps the mdat.
- Fragments: unchanged.

Clearing removes the chapter trak objects, not every trak with their
IDs, so a trak that shares an ID survives.

Reading fragments: after a traf whose data length is unknown, a later
traf of that moof with an implicit base (§8.8.7) is skipped instead of
read from a guessed position, so chpl wins over misplaced bytes.

The integration test's sample hash reads stz2.
An iloc in unread bytes would carry its type code, so an unread tail
without the bytes "iloc" cannot hide one. A meta with stray trailing
bytes, as in the TagLib# sample bgo_676934.m4a, no longer keeps the
earlier chapter mdat, so its chapter edits stay a constant size.
The drop check stored one range per iloc extent before testing any.
iloc field sizes may be 0 (§8.11.3), so an extent can take no bytes:
a 43 KB file declared millions and a save allocated 1.9 GB. Each range
is now tested as it is found and none is stored. Extents with no index,
offset, or length fields are one extent per item; any other extent
count must fit the bytes left in the box. The offset patcher skips such
zero-width extents too, since they hold nothing to move.

Auxiliary information is counted: saio offsets (§8.7.9), absolute in an
stbl and from the traf's base in a fragment, each with the saiz total
after it. A saio without a saiz, or either one cut short, keeps the
mdat.

Clearing removes every chap entry for a removed chapter track, even
when another trak shares its track_ID, and keeps a trex while a
remaining trak uses its ID.
A sound trak that shares the chapter track's track_ID and holds its own
chap reference made the chapter text track look like a presentation
track, so clearing chapters removed only chpl. Holders are now trak
objects, and a clear drops every remaining chap entry for a removed ID.

Pin the guards that had no test: the zero-width iloc cap and its
PatchIloc twin (by step count), traf aux info, version 1 saio, and saio
without saiz. Cover the edit path on a shared-ID file too.
A clear removed every chapter-media trak by scanning the removed list
for each moov child, and the reference walk did the same for each trak,
so the work grew with traks times chapter tracks, both set by the file.
Both passes now make one set lookup per trak, pinned by a lookup count
on a moov with 2,000 chapter tracks.
Adding a chapter track skipped any sound or video trak whose track_ID a
chap entry named, so a sound trak sharing its ID with a chapter image
trak never referenced the new track and each edit added another one.
The add path now uses the read path's rule: a chap entry resolves to
the first trak with its ID, and chapter media is that trak object.

The rest of the chapter code follows the same invariant. The new chunk
offset is written by trak position, the replaced traks travel as
objects, and IDs are compared only where the spec ties a structure to
one (tref targets, tfhd, trex).

Pin the self-reference test with a file in which only the trak sharing
the ID holds the reference, and check that repeated edits keep one
chapter track and a constant size across every shared-ID shape.
Keyed by track_ID, a later trak that shares an ID overwrote the hash of
the first, and skipping the chapter track by its ID skipped the sound
trak sharing it too, so its samples went unchecked on shared-ID files.
A set rebuilt only the first chapter text track. Files can hold one
title track per language (AVFoundation picks one by locale), and ffprobe
and AVFoundation's other locales kept showing the old titles there.

A set now removes every other chap-named text track the way a clear
does, so each reader shows the new list. A chapter URL track, whose
samples carry an href modifier (3GPP TS 26.245), stays, and so does a
text track whose samples cannot all be read, since it cannot be told
apart. A title track with samples in fragments refuses the set, as the
clear does. The sample walk shares one step budget, the file's length,
across every extra track.
…fragment samples

Only a track whose samples carry an href is known to be a URL track. An
extra chapter text track with no samples in moov may hold its titles in
movie fragments, where a set could not reach them, so the set is refused
as it is for a title track.
…her title tracks remain

A set leaves one chapter title track. Setting the list the first track
already holds returned early, in the setter and in the save, so the
other title tracks kept their old titles. That set is now a no-op only
when no other title track would remain.
…r text tracks

A set may now remove extra title tracks, which shifts trak positions.
The hashes of every other trak are compared in moov order instead.
With the tag in moov/meta, a save copies udta as it was. chpl lives in
udta, so a chapter save now rebuilds udta with no tag in it, which keeps
its meta byte for byte and replaces only chpl.

Pin that a tag Clear or Tag = null keeps the chapter track and chpl,
that a chapter clear keeps the tag's bytes, and that chapter saves on a
moov/meta file leave moov/meta and udta/meta untouched.
…t one

A set removed extra title tracks the way a clear does, so a track whose
only chap named one of them was left with no chapter list. Those entries
now name the rebuilt title track, once and in place. A clear still drops
them.

The removal now runs after the rebuilt trak replaces the old one. When
the first title track held a chap of its own naming a removed track,
removing first rewrote that trak object, and the set threw when it came
to replace it.

Cite 3GPP TS 26.245 §5.17.1.5 for the href box, and say in the
ClearAllMetadata summary that chapters are not tag fields and stay.
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 210f1c7.

What was checked:

  • Round 8 (f2e1889) approved, with 2 minors and 1 trivial. All three are fixed at 210f1c7, and I verified each one directly:
    • Retargeting. A set now points each chap entry for a removed extra title track at the rebuilt track, once, in place. A clear still drops those entries.
      • Removing the retarget turns Save_SetChapters_TrackNamingARemovedTitleTrack_NamesTheRebuiltOne red.
      • Fixing this turned up a crash, which is also fixed. A first title track holding a chap to a removed title track made the set throw ArgumentOutOfRangeException. Removal now runs after the replacement, and restoring the old order turns Save_SetChapters_TitleTrackHoldingAChapToTheRemovedOne_IsRebuilt red.
      • Extras exist only when there is an existing title track, so the new placement covers every case.
    • Docs. The ClearAllMetadata docs say chapters are file structure and stay, and that Chapters = [] removes them.
    • Citation. The href rule now cites 3GPP TS 26.245 §5.17.1.5.
  • Earlier rounds. All findings from rounds 1–7 are fixed and pinned:
    • Tracks are identified by object, not by ID, wherever IDs can collide.
    • Repeated edits keep a constant size on every shared-ID shape.
    • The chapter mdat is dropped only when every referenced range can be computed and none overlaps; iloc and saio are included.
    • Memory and work are bounded: a zero-width iloc bomb went from 1.9 GB to 46 MB.
    • A set replaces all chapter title tracks with one list, and URL tracks and tracks it cannot classify are kept.
    • After a set on an English+German file, every reader shows the new list: ffprobe, MediaInfo, mutagen and AVFoundation in both locales.
    • The merge with fix: Read MP4 gnre and keep unedited ilst atoms #133: no-op, title and tag-clear saves match main byte for byte on 618/618 rows.
  • Gates.
    • Release build: 0 warnings.
    • net8.0 and net10.0: 6014 passed / 39 skipped.
    • Format clean.
    • Integration 5/5 on the real files.
    • CI 8/8 green. GitHub reports the PR clean and mergeable.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit 7f7bcb7 into main Nov 22, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved AI has reviewed and signed off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Read and write MP4 chapters

1 participant