Skip to content

feat: Read and write Matroska and WebM chapters - #146

Merged
decriptor merged 20 commits into
fix/matroska-seekhead-fallbackfrom
feat/matroska-chapters
Nov 22, 2026
Merged

decriptor merged 20 commits into
fix/matroska-seekhead-fallbackfrom
feat/matroska-chapters

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Stacked on #149 (fix/matroska-seekhead-fallback), which is itself stacked on #142. Merge order: #142 → #149 → this PR. #149 provides the SeekHead/shift engine. This PR adds the chapter model and the "keep unedited bytes" rule, and writes Chapters through #149's generic TryReplace.

MatroskaFile.Chapters now reads and writes the Chapters element (0x1043A770) of Matroska and WebM files. The model has editions (MatroskaEdition) and nested chapter atoms (MatroskaChapter). Each chapter has a UID, a string UID, start and end times in nanoseconds, display strings with languages, BCP 47 languages and countries (MatroskaChapterDisplay), and the hidden and enabled flags. Editions carry UID, default, ordered and hidden. You can add, edit and remove chapters and editions. New UIDs are random nonzero 64-bit values.

Invariant: a save rewrites an element only when the model renders differently from what was read. Every offset that points past a moved element (SeekHead, CueClusterPosition, Cluster Position) still points at that element afterwards.

  • A save that does not edit chapters keeps the original Chapters bytes. This includes edit-then-revert, and files with CRC-32, Void, or non-minimal encodings that a re-render would change.
  • Chapter titles never become Tag.Title. This is tested both ways: adding chapters leaves the segment title and the TITLE tag alone, and the reverse.
  • Child elements the API does not model are written back verbatim on an edit: ChapProcess, ChapterSegmentUUID, ChapterTrack, EditionDisplay, and so on.
  • WebM saves keep to the WebM chapter subset. A WebM save leaves out EditionUID, EditionFlag*, ChapterFlagHidden, ChapterFlagEnabled and ChapLanguageBCP47.

Motivation and Context

Closes #114. Pull request #106 already copies Chapters through as original bytes. This PR exposes the element and edits it.

Spec references

  • RFC 9559 section 5.1.7 (element IDs, types, defaults, ranges): https://www.rfc-editor.org/rfc/rfc9559#section-5.1.7
  • RFC 9559 section 20: default edition (20.1.2) and that an edition needs at least one ChapterAtom (20.1).
  • RFC 9559 section 6.1: the SeekHead MUST list added top-level elements. Section 6.6: Chapters SHOULD come before the clusters.
  • RFC 9559 section 5.1.3.2: Cluster Position.
  • ChapterFlagEnabled (0x4598, default 1) and EditionFlagHidden (0x45BD, default 0) are not in RFC 9559. They are in the Matroska element schema: https://github.com/ietf-wg-cellar/matroska-specification/blob/master/ebml_matroska.xml
  • RFC 8794 section 11.1.6.4 (a mandatory element with a default value need not be stored), 11.1.17 (identically recurring elements: the first copy is read), and 6.1 (an empty element reads as its default).
  • WebM chapter subset: https://www.webmproject.org/docs/container/#chapters
  • ChapterTimeStart and ChapterTimeEnd are Matroska ticks (nanoseconds). They are not scaled by TimestampScale, which is RFC 9559 5.1.7.1.4.3 and 4 plus the WebM note "not scaled".

Design decisions

  • "Edited" means "holds a value other than the one read". On read, each edition and chapter keeps a snapshot of its own values and child list, and Tags keeps its rendered bytes. A save compares against that, so there is no per-setter dirty flag, and setting a value back is not an edit. Adding, removing (by RemoveEdition, Clear or the Editions list), or reordering counts. In a Matroska file, every edition and chapter that was not changed is written back byte for byte from one copy of the element; a WebM file is rewritten to its subset, and values WebM does not store are not an edit there. I applied the same rule to Tags (MatroskaTag.IsAsRead). Without it, a chapter-only save re-rendered Tags. On feat: Write Matroska pictures as image attachments #142, a no-op save of TaglibSharpSamples/matroska/test1.mkv lost its tags in ffprobe: the re-rendered Tags was 4 bytes larger, so it moved past the clusters, and its 2-byte SeekPosition could not reach the new offset. fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149 already keeps those tags listed; this PR also makes a no-op save byte-identical on every real file below. The container is still parsed, so a bad container still fails the save. Clear() on a file whose Chapters held no chapter atoms (or only a Void) still removes the element.
  • Ordered chapters go after Info. RFC 9559 6.6 also says ordered chapters SHOULD come after the first Info and before the first Tracks. When a moved or new Chapters element has an ordered edition (Matroska only), it goes right after the first Info, when that Info follows the SeekHead and precedes the first Tracks and Cluster; otherwise it keeps the after-SeekHead place. A Chapters element that fits in place or in a Void is still written there.
  • Chapters go before the Clusters. RFC 9559 6.6: Chapters SHOULD come before the Clusters, and a reader that goes front to back (a piped ffprobe, exiftool) stops at the first one. An edited Chapters element that the plan would place after the first Cluster (outgrown, or muxed at the end) moves right after the first SeekHead, or before the first Cluster when there is none, through fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149's move. Everything after it moves once and every offset follows. A tag-only save leaves chapters where they are. Before this, every ffmpeg-made file showed 0 chapters to a piped ffprobe and exiftool after an add or retitle.
  • Same splice engine. Edited Attachments, then edited Chapters, then edited Tags each go through fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149's generic TryReplace (TryStage). Each pass re-parses the layout the previous one produced. When the SeekHead has no room, fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149 moves the element after the SeekHead, so added chapters are listed (RFC 9559 6.1). On test1/2/3/6/8 the SeekHead is full, and before fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149 added chapters were unlisted and invisible to ffprobe.
  • Untrusted input. ChapterAtom recursion is capped at 32 levels. At most 65,536 child elements are parsed across the whole Chapters element; once they are spent, the rest of each parent is kept as one copy of its bytes and written back, after the last chapter read from the file and before any added one. Rendering measures first and writes once into an exact buffer, so no level is copied into its parent. A read-only open of the reviewer's 16 MB file of empty atoms peaks at 116 MB RSS, including one copy of the element kept so untouched parts go back byte for byte (was 638 MB; the base, which does not parse chapters, 58 MB). Void and CRC-32 children are never kept: an edited parent gets neither (RFC 8794 11.3.1). Truncation at every byte is tested. Malformed children end their parent and never throw.
  • RFC 9559 timing rules. A save fails, writing nothing, when a chapter it adds or changes ends before it starts (20.2.2), starts outside its parent (20.2.3), or is a lowest-level chapter of an ordered edition with no end (20.2.4, Table 29). A chapter whose context changed is checked with everything nested in it: one that is new, moved to another edition or parent, or in an edition that is new or whose own values changed (for example, made ordered). An added edition without chapters is never written and is not an edit. An untouched chapter is not checked, so a bad chapter from another tool does not block other edits, and it goes back byte for byte. The error names the chapter, for example Matroska chapter (edition 1, chapter 2, UID 77) ends before it starts. Start/End throw ArgumentOutOfRangeException past 2^64 - 1 ns instead of wrapping.
  • WebM. When a WebM file's chapters are written, only the chapter elements the WebM guidelines list as supported are written, on every chapter, edited or not, whether modelled or kept: EditionUID, the edition flags, ChapterFlagHidden, ChapterFlagEnabled, ChapLanguageBCP47, EditionDisplay, ChapterSegmentUUID, ChapterTrack, ChapterPhysicalEquiv and ChapProcess are left out. A hidden or disabled chapter in a WebM file is therefore written as a plain one. Bytes kept past the depth or entry limit are filtered only at their top level.
  • A chapter read without a valid ChapterUID gets a random one. That UID is written only if the chapters are edited.
  • Multiple Chapters copies (identically recurring) are read from the first. An edit voids every copy and writes one.
  • Flags are written only when they differ from the default (RFC 8794 11.1.6.4). ChapLanguage is always written. A display without ChapLanguage reads as eng.

Out of scope

  • A tag block that targets a removed chapter's UID (TagChapterUID) stays in Tags. Nothing prunes it.
  • EditionDisplay (minver 5) and ChapProcess are preserved as bytes but not modelled.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • 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, Cookbook, ROADMAP, MIGRATION-FROM-TAGLIB)
  • My changes generate no new warnings

Testing

Gates:

  • dotnet build -c Release: 0 warnings, 0 errors (all target frameworks)
  • dotnet test -c Release: net8.0 5018 passed / 26 skipped / 0 failed; net10.0 5018 passed / 26 skipped / 0 failed
  • dotnet format --verify-no-changes: clean
  • PublicApi snapshot updated (new MatroskaChapters, MatroskaEdition, MatroskaChapter, MatroskaChapterDisplay, MatroskaFile.Chapters)

Unit tests are in tests/TagLibSharp2.Tests/Matroska/MatroskaChapterTests.cs. Each guard was reverted to confirm a test goes red:

  • the chapters "unchanged" check
  • the tags "as read" check
  • the WebM filter
  • the entry-limit keep

Removing the depth cap crashes the test host with a stack overflow.

Three chapter tests changed meaning after stacking on #149:

  • a full SeekHead now widens the other Seeks instead of refusing the move
  • a too-narrow Seek stays listed
  • with no SeekHead, chapters go before the first Cluster

Env-gated integration tests: TAGLIBSHARP2_TEST_MATROSKA=<file> dotnet test --filter "FullyQualifiedName~MatroskaChapterIntegrationTests" (MatroskaChapterIntegrationTests.cs). Locally, with these and #142's MatroskaIntegrationTests, they passed on every file below and on a test2 output that now has chapters. The tag-edit-keeps-Chapters test is inconclusive on files without chapters.

Real-file verification

Files:

  • TaglibSharpSamples/matroska/test1..8.mkv: none have chapters.
  • taglib-sharp Turning Lime.mkv
  • ffmpeg 9.0.2 output from lavfi sources with three chapters from an ffmetadata file (-map_chapters): gen.mkv (H.264/AAC), gen.webm (VP9/Opus), gen.mka (FLAC)
  • nochap.mka (Opus, no chapters)

Operations:

  • noop: save without edits
  • tagonly: change the artist
  • retitle: rename chapter 1 with a longer title, nest a chapter in it, add a chapter in French
  • shrink: shorten a title
  • remove: remove the last chapter
  • clear: remove all chapters
  • add: add three chapters to a file without any

After every save I checked:

  • ffprobe -show_chapters
  • the mediainfo Menu entry count
  • ffmpeg -v error -i out -f null -
  • the cluster payload compared to the input (every cluster child except Position and CRC-32)
  • whether the Chapters element bytes were kept
  • every SeekHead entry and every CueClusterPosition points at an element of its ID
  • top-level CRC-32 values
  • every Cluster Position equals its offset
File Ops ffprobe after save mediainfo Decode Cluster payload Offsets
gen.mkv / gen.webm / gen.mka noop, tagonly the original 3 chapters; Chapters bytes kept; noop byte-identical 3 clean identical ok
gen.mkv / gen.webm / gen.mka retitle, shrink, remove, clear 4, 3, 2, 0 chapters 5 (includes the nested one), 3, 2, 0 clean identical ok
nochap.mka add 3 chapters 3 clean identical ok
test1, test6 (SeekHead full) noop, add, retitle, clear byte-identical, 3, 4, 0 chapters; TITLE kept 0, 3, 5, 0 clean identical Chapters listed after the SeekHead
test2, test3, test8 (Position present) noop, add, retitle, clear byte-identical, 3, 4, 0; TITLE kept 0, 3, 5, 0 clean identical; only Position values change when moved all 47 Position values correct
test5 noop, add, retitle, clear byte-identical, 3, 4, 0; TITLE kept 0, 3, 5, 0 clean identical ok
test7 (junk in clusters) noop, add, retitle, clear byte-identical, 3, 4, 0 0, 3, 5, 0 "Invalid track number 87", same as the input only Position bytes differ 37 Position values correct
test4 (live, no SeekHead) noop, add, retitle, clear ffprobe cannot open the input either; this reader reads the chapters back n/a same error as the input n/a no SeekHead
Turning Lime.mkv noop, add, retitle, clear byte-identical, 3, 4, 0; TITLE kept 0, 3, 5, 0 clean identical ok (the input's one wrong CueClusterPosition is unchanged)
test1–8, Turning Lime both: two chapters, an artist, and a JPEG cover in one save 2 chapters, TITLE + new ARTIST, 1 attached picture 2 menu entries, Cover = Yes clean (test4/7 as their inputs) identical all Seeks, Cues and Position values correct

A no-op save is byte-identical on all 12 of the files I checked; on #142 and #149 it rewrote them.

Two notes on the table:

  • ffprobe does not list nested chapters. It also lists a chapter only when it starts after the previous one, which is why the retitle check adds its chapter after the last start.
  • Saved WebM Chapters contain only the chapter elements WebM supports (pinned by SaveChapters_WebM_WritesOnlyWhatWebMSupports, which includes unmodelled children).

Review round 1

Rebased onto #149 @ fb58a98 (SeekHead fallback, position engine and track-flag shift, on #142 f3a6078, which is on main ebd6138 with #132, #135 and #140). A save that sets a track flag and edits chapters writes both: SaveChapters_WithATrackFlag_WritesBothAndMovesEveryPosition, and on test1–8, Turning Lime and gen.* the flag and the added chapter read back, while ffprobe (file and piped) sees the chapter, every Seek, CueClusterPosition and Cluster Position lands, clusters are unchanged apart from Position, and decoding is clean (test4/test7 as their inputs).

Round 2: F1 (validate only chapters the save adds or changes, keep untouched ones byte for byte, name the chapter), F2 (pins for the kept-leaf check and kept-edition order) and F3 (RemoveEdition and list removal of an edition without atoms) are in MatroskaChapterEditTests.cs.

Round 3: a chapter moved into an ordered edition is checked (RFC 9559 20.2.4), an empty added edition is not an edit, and MatroskaChapterPropertyTests.cs covers every settable value and list operation, top level and nested, in Matroska and WebM: an edit saves and reads back, setting a value to itself is byte-identical, and a value WebM does not store is byte-identical there. A self-nested chapter saves without overflowing the stack. The fixes for findings #1–#7 are in fix:/perf:/test:/docs: commits on top of the original commit. New tests are in MatroskaChapterLimitTests.cs and MatroskaChapterTests.cs (SaveChapters_Grown_GoBeforeTheClustersAndStayListed, SaveChapters_EditedAfterTheClusters_MoveBeforeThem). The env-gated RealFile_AddEditAndClearChapters_KeepsClustersAndTags now also checks that Chapters precede the first Cluster.

After the fix, a piped cat out | ffprobe -show_chapters -i - and exiftool find the chapters on every add/retitle output (gen.mkv/mka/webm, nochap.mka/webm, test2, Turning Lime), where they found 0 before.

Additional Notes

Rebased (force-pushed) from the original main-based version onto #149. The SeekHead fallback and Cluster Position patch that this PR used to carry are now in #149.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.30469% with 130 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (fix/matroska-seekhead-fallback@8769001). Learn more about missing BASE report.

Files with missing lines Patch % Lines
....Tests/Matroska/MatroskaChapterIntegrationTests.cs 2.91% 100 Missing ⚠️
src/TagLibSharp2/Matroska/MatroskaChapters.cs 94.73% 7 Missing and 7 partials ⚠️
src/TagLibSharp2/Matroska/MatroskaRewrite.cs 53.84% 9 Missing and 3 partials ⚠️
...agLibSharp2.Tests/Matroska/MatroskaChapterTests.cs 99.51% 1 Missing and 2 partials ⚠️
src/TagLibSharp2/Matroska/MatroskaFile.cs 90.90% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@                        Coverage Diff                        @@
##             fix/matroska-seekhead-fallback     #146   +/-   ##
=================================================================
  Coverage                                  ?   92.71%           
=================================================================
  Files                                     ?      295           
  Lines                                     ?    59670           
  Branches                                  ?     5869           
=================================================================
  Hits                                      ?    55322           
  Misses                                    ?     2633           
  Partials                                  ?     1715           

☔ 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/matroska-chapters branch from 8e4ec2c to 256bf8d Compare November 21, 2026 09:13
@decriptor
decriptor changed the base branch from main to fix/matroska-seekhead-fallback November 21, 2026 09:14
@decriptor
decriptor force-pushed the feat/matroska-chapters branch from f318aa4 to f9829f2 Compare November 21, 2026 19:08
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch 2 times, most recently from 0311603 to 22f84e7 Compare November 21, 2026 19:40
@decriptor
decriptor force-pushed the feat/matroska-chapters branch 2 times, most recently from 3415e09 to 045869d Compare November 21, 2026 19:49
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch from 39c4b3f to 04d5de3 Compare November 21, 2026 20:17
@decriptor
decriptor force-pushed the feat/matroska-chapters branch 2 times, most recently from a05ae4c to 6e9d465 Compare November 21, 2026 22:34
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch from 336ed70 to fbce9f2 Compare November 22, 2026 03:18
@decriptor
decriptor force-pushed the feat/matroska-chapters branch 2 times, most recently from 3caf329 to 39871a4 Compare November 22, 2026 04:15
@decriptor
decriptor force-pushed the feat/matroska-chapters branch from 39871a4 to 68b7cf1 Compare November 22, 2026 04:41
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 8766d27.

This PR is stacked on #149, which is stacked on #142. Merge order: #151, then #142, then #149, then this PR. Because it is stacked, CI does not run on this branch; the gates below were run locally.

What was checked:

  • Round 4 (approve at 68b7cf1). Its 2 minors and 1 trivial are fixed at 8766d27, verified directly:
    • A moved or new Chapters element with an ordered edition now goes right after the first Info and before the first Tracks, with or without a SeekHead (RFC 9559 §6.6). Files whose Tracks or Cluster comes before Info keep the old placement. A Chapters element that fits in place or in a Void stays there, and the docs say so.
    • Removing the Info anchor makes 2 tests fail, and ignoring the ordered flag makes 1 test fail.
    • A chapter edit together with a track flag set to its stored value now has a pinning test.
    • The TryRender summary covers chapters.
  • Earlier rounds, all fixed and pinned:
    • A single save that changes chapters, tags, a cover and a track flag on test1..8.mkv, Turning Lime.mkv and generated files puts every Seek, CueClusterPosition, CueCodecState and Cluster Position in the right place.
    • Cluster payloads are unchanged.
    • ffprobe (file and piped), mediainfo, TagLib# and ffmpeg -f null agree.
    • ChapterAtom nesting is capped at 32 levels. Files nested 100,000 and 1,000,000 deep read and save without overflowing, and the whole chain is kept.
  • Gates at 8766d27:
    • Release build: 0 warnings.
    • net8.0 and net10.0: 5018 passed / 26 skipped.
    • Format clean.
    • Env-gated Matroska integration tests pass on test1..8.mkv and Turning Lime.mkv.
    • The branch merges cleanly into main.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit 686041d into fix/matroska-seekhead-fallback Nov 22, 2026
@decriptor
decriptor deleted the feat/matroska-chapters branch November 22, 2026 05:16
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 Matroska and WebM chapters

1 participant