Repository navigation
feat: Read and write Matroska and WebM chapters - #146
Merged
decriptor merged 20 commits intoNov 22, 2026
Merged
Conversation
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
decriptor
force-pushed
the
feat/matroska-chapters
branch
from
November 21, 2026 09:13
8e4ec2c to
256bf8d
Compare
decriptor
changed the base branch from
main
to
fix/matroska-seekhead-fallback
November 21, 2026 09:14
8 of 10 tasks
decriptor
force-pushed
the
feat/matroska-chapters
branch
from
November 21, 2026 19:08
f318aa4 to
f9829f2
Compare
decriptor
force-pushed
the
fix/matroska-seekhead-fallback
branch
2 times, most recently
from
November 21, 2026 19:40
0311603 to
22f84e7
Compare
decriptor
force-pushed
the
feat/matroska-chapters
branch
2 times, most recently
from
November 21, 2026 19:49
3415e09 to
045869d
Compare
decriptor
force-pushed
the
fix/matroska-seekhead-fallback
branch
from
November 21, 2026 20:17
39c4b3f to
04d5de3
Compare
decriptor
force-pushed
the
feat/matroska-chapters
branch
2 times, most recently
from
November 21, 2026 22:34
a05ae4c to
6e9d465
Compare
7 tasks done
decriptor
force-pushed
the
fix/matroska-seekhead-fallback
branch
from
November 22, 2026 03:18
336ed70 to
fbce9f2
Compare
decriptor
force-pushed
the
feat/matroska-chapters
branch
2 times, most recently
from
November 22, 2026 04:15
3caf329 to
39871a4
Compare
… empty added edition
decriptor
force-pushed
the
feat/matroska-chapters
branch
from
November 22, 2026 04:41
39871a4 to
68b7cf1
Compare
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:
|
7 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 genericTryReplace.MatroskaFile.Chaptersnow reads and writes theChapterselement (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.Chaptersbytes. This includes edit-then-revert, and files with CRC-32, Void, or non-minimal encodings that a re-render would change.Tag.Title. This is tested both ways: adding chapters leaves the segment title and theTITLEtag alone, and the reverse.ChapProcess,ChapterSegmentUUID,ChapterTrack,EditionDisplay, and so on.EditionUID,EditionFlag*,ChapterFlagHidden,ChapterFlagEnabledandChapLanguageBCP47.Motivation and Context
Closes #114. Pull request #106 already copies
Chaptersthrough as original bytes. This PR exposes the element and edits it.Spec references
ChapterAtom(20.1).Position.ChapterFlagEnabled(0x4598, default 1) andEditionFlagHidden(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.xmlChapterTimeStartandChapterTimeEndare Matroska ticks (nanoseconds). They are not scaled byTimestampScale, which is RFC 9559 5.1.7.1.4.3 and 4 plus the WebM note "not scaled".Design decisions
Tagskeeps 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 (byRemoveEdition,Clearor theEditionslist), 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 toTags(MatroskaTag.IsAsRead). Without it, a chapter-only save re-renderedTags. On feat: Write Matroska pictures as image attachments #142, a no-op save ofTaglibSharpSamples/matroska/test1.mkvlost its tags in ffprobe: the re-renderedTagswas 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 whoseChaptersheld no chapter atoms (or only a Void) still removes the element.ffprobe,exiftool) stops at the first one. An editedChapterselement 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.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.ChapterAtomrecursion is capped at 32 levels. At most 65,536 child elements are parsed across the wholeChapterselement; 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.Matroska chapter (edition 1, chapter 2, UID 77) ends before it starts.Start/EndthrowArgumentOutOfRangeExceptionpast 2^64 - 1 ns instead of wrapping.EditionUID, the edition flags,ChapterFlagHidden,ChapterFlagEnabled,ChapLanguageBCP47,EditionDisplay,ChapterSegmentUUID,ChapterTrack,ChapterPhysicalEquivandChapProcessare 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.ChapterUIDgets a random one. That UID is written only if the chapters are edited.Chapterscopies (identically recurring) are read from the first. An edit voids every copy and writes one.ChapLanguageis always written. A display withoutChapLanguagereads aseng.Out of scope
TagChapterUID) stays inTags. Nothing prunes it.EditionDisplay(minver 5) andChapProcessare preserved as bytes but not modelled.Type of Change
Checklist
dotnet test)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 faileddotnet format --verify-no-changes: cleanMatroskaChapters,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:Removing the depth cap crashes the test host with a stack overflow.
Three chapter tests changed meaning after stacking on #149:
Env-gated integration tests:
TAGLIBSHARP2_TEST_MATROSKA=<file> dotnet test --filter "FullyQualifiedName~MatroskaChapterIntegrationTests"(MatroskaChapterIntegrationTests.cs). Locally, with these and #142'sMatroskaIntegrationTests, 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.Turning Lime.mkvffmetadatafile (-map_chapters):gen.mkv(H.264/AAC),gen.webm(VP9/Opus),gen.mka(FLAC)nochap.mka(Opus, no chapters)Operations:
After every save I checked:
ffprobe -show_chaptersffmpeg -v error -i out -f null -Positionand CRC-32)Chapterselement bytes were keptCueClusterPositionpoints at an element of its IDPositionequals its offsetChaptersbytes kept; noop byte-identicalA 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:
Chapterscontain only the chapter elements WebM supports (pinned bySaveChapters_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 (
RemoveEditionand list removal of an edition without atoms) are inMatroskaChapterEditTests.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.cscovers 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 infix:/perf:/test:/docs:commits on top of the original commit. New tests are inMatroskaChapterLimitTests.csandMatroskaChapterTests.cs(SaveChapters_Grown_GoBeforeTheClustersAndStayListed,SaveChapters_EditedAfterTheClusters_MoveBeforeThem). The env-gatedRealFile_AddEditAndClearChapters_KeepsClustersAndTagsnow also checks that Chapters precede the first Cluster.After the fix, a piped
cat out | ffprobe -show_chapters -i -andexiftoolfind 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
Positionpatch that this PR used to carry are now in #149.