Skip to content

feat: Move later Matroska elements when a track flag needs room - #148

Merged
decriptor merged 10 commits into
fix/matroska-seekhead-fallbackfrom
feat/matroska-track-enabled-shift
Nov 22, 2026
Merged

decriptor merged 10 commits into
fix/matroska-seekhead-fallbackfrom
feat/matroska-track-enabled-shift

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Stacking

Stacked on #149 (fix/matroska-seekhead-fallback, head 52bf607, itself on #142 2afe3b2, which is on main 85ce8d2), which is itself stacked on #142. Merge order: #142 → #149 → #148. This PR's diff is only the ten commits on top of #149.

This PR supersedes the refusal in #140. #140 writes a missing FlagEnabled only when the Void right after Tracks has room, and refuses every other insert. Here, that insert goes through the shared MatroskaRewrite.TryGrow shift instead. Commits:

  1. feat: Skip disabled Matroska tracks when choosing the main track: the same as feat: Honor and save the Matroska track enabled flag in place #140.
  2. feat: Save the Matroska track enabled flag: feat: Honor and save the Matroska track enabled flag in place #140's save behavior, conflict-resolved onto this base.
  3. feat: Move later elements when the track flag needs room: the new part.

If this lands, #140 can be closed. If #140 lands first, commits 1 and 2 drop out on rebase.

Description

Matroska now reads and writes TrackEntry\FlagEnabled (0xB9).

Selection. The main audio and video track is the first enabled default track of that type, then the first enabled one. A track that stores FlagEnabled 0 can no longer win while an enabled track of its type exists. A missing or empty element counts as enabled (default 1).

API. MatroskaFile.Tracks (IReadOnlyList<MatroskaTrack>) lists the first 4096 known-size TrackEntry elements (MatroskaFile.IsTrackListTruncated is true when a file has more): TrackNumber, TrackUid, TrackType (new MatroskaTrackType, RFC 9559 Table 2), CodecId, IsDefault, and a settable IsEnabled. It is shaped like FlacCueSheet.Tracks.

Saving. Only a track whose IsEnabled the caller set is touched, and only when the stored value differs. The three cases below are tried in order.

  1. A stored 1 to 8 octet element is rewritten in place. The TrackEntry and Tracks CRC-32s are recomputed.
  2. An empty or missing element becomes B9 81 0v, and the TrackEntry and Tracks sizes grow (keeping their width when the new size fits). If the Void right after Tracks can give the octets (shrinking to nothing or to at least 2), nothing moves.
  3. Otherwise (new here), the grown Tracks element goes to MatroskaRewrite.TryGrow. Everything after Tracks moves once. SeekHead, Cues (CueClusterPosition), Cluster Position, and their CRC-32s are patched by that shared code.

Other rules:

  • Second Tracks element: one that needs room and has no adjacent Void still fails the save. TryGrow replaces the first Tracks, and RFC 9559 §5.1.4 allows only one.
  • DocTypeVersion: when a FlagEnabled is added, the EBML header's DocTypeVersion becomes at least 2 (FlagEnabled has minver 2, and RFC 9559 §7 requires DocTypeVersion ≥ the highest element version). A lower stored value is raised in place; an empty or missing one (which means 1) is written, and the header grows. The header is outside the Segment, so no Segment Position moves (round 1, F6).
  • Track identity: the track at each ordinal must still have the number and UID it was read with, or the save fails.

Closes #117

Spec references

  • RFC 9559 §5.1.4.1.4 FlagEnabled; §5.1.4.1.5 FlagDefault; §18.1 Default flag; §5.1.4.1.1-3 TrackNumber, TrackUID, TrackType
  • RFC 9559 §5.1.3.2 Cluster Position, §6.1, §6.2 CRC-32, §16 Segment Position
  • RFC 8794 §6.1, §7.2, §11.2.7 DocTypeVersion, §11.3.1 CRC-32, §11.3.2 Void

Design decisions

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)

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, docs/ROADMAP.md, public API snapshot)
  • My changes generate no new warnings

Testing

Gates (this branch)

  • dotnet build -c Release: 0 warnings, 0 errors on all four TFMs.
  • dotnet test -c Release: net8.0 4639 passed, 17 skipped; net10.0 4639 passed, 17 skipped. The skips are env-gated integration tests.
  • dotnet format --verify-no-changes: clean.

Unit tests

  • New in this PR (written first, red before the change):
    • insert without a Void (sync and async) moves later elements; seeks, Cues, and CRC-32s all land
    • a Void before Tracks stays where it was and later elements move
    • a 4-octet Void is not used
    • a Void past a Cluster is not used
    • Cluster Position gets its new value
    • unknown-size segment with a live cluster
    • a second Tracks without room fails
  • Mutation check: I disabled the grow route and 7 tests failed. I removed the second-Tracks guard and 1 test failed.
  • Carried from feat: Honor and save the Matroska track enabled flag in place #140: all read and save tests (in place, adjacent Void, CRC, DocTypeVersion, identity, malformed input).

Integration: MatroskaTrackIntegrationTests, env var TAGLIBSHARP2_TEST_MATROSKA, 3/3 on all 13 files below.

  • An untouched save keeps the Tracks and Cluster payloads.
  • Toggling the first audio track round-trips. The cluster blocks stay identical; only Cluster Position values are excluded from the comparison.
  • Toggling back is in place.

Real files (track #2 disabled; #3 for multi.mkv, #1 for audio.mka)

Columns:

  • Shift: the shift (in bytes) of every ffprobe packet pos.
  • Packets: packet pts and order are identical in every row.
  • Seek 1.5 s: packets from ffprobe -read_intervals 1.5%+#5 match the original.
  • Cues / Position: CueClusterPosition and Cluster Position values that point at their cluster.
  • CRC-32: checksums verified by a local EBML walker.
  • enzyme: enzyme 0.5.2 (MIT, PyPI), used only as an independent reader. ffprobe and mediainfo do not report FlagEnabled at all.
File Path Shift Seek 1.5 s Seeks Cues / Position CRC-32 Decode errors enzyme
test1.mkv shift +169 (166 is #149's own SeekHead rewrite on an unchanged save, re-derived on an 8769001 build) same 4/4 10/10, none stored none stored 0 (orig 0) #2 DISABLED
test2.mkv shift +3 same 5/5 47/47, 47/47 12 ok 0 #2 DISABLED
test3.mkv shift +3 same 4/4 47/47, 47/47 11 ok 0 #2 DISABLED
test4.mkv (unknown-size segment, 0x0A filler, DocTypeVersion 1) shift +3 same none stored - header ok 0 can't parse (original too); DocTypeVersion 1→2
test6.mkv shift +201 (#149 on an unchanged save: +198) same 3/3 none stored - 0 #2 DISABLED
test7.mkv shift +3 same 4/4 37/37, 37/37 11 ok 1 (orig 1) #2 DISABLED
test8.mkv shift +3 same 4/4 47/47, 47/47 11 ok 0 #2 DISABLED
ffmpeg multi.mkv (H.264 + 2 AAC) shift +3 same 4/4 1/1 4 ok 0 #3 DISABLED
ffmpeg multi.webm (VP9 + 2 Opus) shift +3 same 4/4 1/1 - 0 #2 DISABLED
ffmpeg audio.mka (2 FLAC) shift +3 same 4/4 2/2 4 ok 0 #1 DISABLED
ffmpeg live.mkv (-live 1) shift +3 same 3/3 - 3 ok 0 #2 DISABLED
test5.mkv adjacent Void 0 same 4/4 46/46 - 4 (orig 4) #2 DISABLED
Turning Lime.mkv adjacent Void 0 same 6/6 cue already off in the original (670 vs 818) - 0 #2 DISABLED

The matrix above was re-run after rebasing onto 8769001.

Round 1 (rebased onto #149 ad69aca)

New tests (MatroskaTrackEnabledShiftTests.cs), each failing at round-0 head a3fe3c5:

  • a Cues Seek that crosses 65534 → 65537 is kept (F1)
  • a CueClusterPosition that crosses 65533 → 65536 widens (F4)
  • CueCodecState and CueRefCluster follow their Cluster (F3)
  • an unknown-size Tracks names its reason (F5)
  • a missing DocTypeVersion is added (F6)
  • an empty DocTypeVersion is replaced (F6)

AssertSeeksLand now takes the original file, and fails when any Seek that landed in the input is missing or no longer lands (F2). The real-file toggle test compares the set of Seeks that land before and after. The reviewer's F2 mutation (drop the Cues Seek whenever it moves) now turns 12 tests red; before, all 233 passed.

The reviewer's grid (45 file × track cells) was run at a3fe3c5 and this head. All 45 cells are identical: same save result, Seek/Cue/Position/CRC summary, packet positions and seek frames. The intended changes show on the reviewer's trigger files:

Trigger a3fe3c5 this head
edge-65534.mka saved, Seeks 4 → 3 (the Cues Seek was voided) saved, Seeks 4 → 4. The SeekHead widened 1 octet, so packets shift +4. Frames identical
cl-65533.mka "Matroska Cues cannot be updated" saved, all 39 cues land, packets shift +3, frames identical
codecstate.mkv CueCodecState 198 → 198 (now inside Cluster 1) 198 → 201 (Cluster 2)
cueref.mkv CueRefCluster 120 → 120 120 → 123
nodtv.mkv DocTypeVersion missing after the insert DocTypeVersion 2 written
unknowntracks.mkv "…in a second Tracks…" "…but Tracks has an unknown size and no Void right after it"

The env-gated toggle test passes 3/3 on all 25 inputs (samples, Turning Lime and the reviewer's gen files), and fails at a3fe3c5 on edge-65534 and cl-65533. Patch coverage on this PR's source lines vs ad69aca is 93%.

Cluster bytes. In test2/3/7/8, every cluster is byte-identical to the original apart from the patched Position value. In the other files every cluster payload is identical.

Main audio after disabling: test5 and multi.mkv switch to the other, enabled audio track (44100 Hz). audio.mka switches to the 22050 Hz FLAC track.

Additional Notes

Implemented from RFC 9559 and RFC 8794 only. No media files are committed; tests build their inputs in code.

Round 2

The stack is rebased onto #142 2afe3b2, which is on main 85ce8d2; this PR is on #149 52bf607. Restacked from 04d5de3 after #149's round 3, and again from 84fdb03 after round 4. This PR's code is unchanged from the approved ca7f1cd; the only difference is one CHANGELOG context line that comes from #149. At the current head: net8.0 and net10.0 4643 passed / 17 skipped, 0 warnings, format clean, and env-gated tests 7/7 on test1, test3 and test7.

Round 3 (from #140's round 3)

Commit 583fbd6: MatroskaFile.TracksTruncated is renamed to IsTrackListTruncated, matching the library's other public bools. The code, tests, PublicApi snapshot, CHANGELOG and this body are updated.

@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch from d1293ad to a3fe3c5 Compare November 21, 2026 09:16
@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch from a3fe3c5 to cc9c823 Compare November 21, 2026 19:10
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch from ad69aca to 0311603 Compare November 21, 2026 19:25
@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch from f20a858 to e103f67 Compare November 21, 2026 19:30
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch from 0311603 to 22f84e7 Compare November 21, 2026 19:40
@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch 2 times, most recently from fedf2b8 to f6b9a29 Compare November 21, 2026 20:13
@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-track-enabled-shift branch from f6b9a29 to 0f385b9 Compare November 21, 2026 20:21
decriptor added a commit that referenced this pull request Nov 21, 2026
DocTypeVersion has maxOccurs 1, but a file can store it twice. Every copy
below 2 is now raised, and an empty copy is written as 2, as every
FlagEnabled copy is written, so a reader that takes the first copy no
longer sees 1. The header CRC is recomputed only when a copy changed.
The same change as #148 round 2.
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at ca7f1cd.

The last review round (at 583fbd6) found nothing. The only commit since then, ca7f1cd, is a test-only change: it adds the (empty, empty) DocTypeVersion row. All 277 Matroska tests pass at ca7f1cd.

What was checked:

  • Original triggers: every round-1 and round-2 trigger file now saves correctly when a track flag needs room, and packets and frames are unchanged in each:
    • edge-65534 keeps its Cues Seek, and cl-65533 saves with all 39 cues landing;
    • CueCodecState and CueRefCluster follow their Cluster;
    • files with a missing, empty or duplicated DocTypeVersion get version 2 in every copy.
  • Linear shift: the shift inherits fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149's linear widening. A crafted Cues cascade through a track-flag save drops from 2.66 GB / 5.9 s to 15.9 MB / 27 ms, and every cue and CRC stays valid.
  • Robustness: the 1,244-variant EBML header grid is all correct, with valid CRCs. Fuzzing ran about 20k inputs with 0 library exceptions. Every targeted guard revert fails a test.
  • Builds and tests: Release build has 0 warnings on all four targets; tests pass on net8.0 and net10.0; format, pack and the vulnerable-package check are clean. The integration tests pass on 31 real files.
  • Merge order: feat: Write Matroska pictures as image attachments #142 → fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149 → this PR. The whole stack merges into main cleanly. CI will run once this PR is retargeted to main.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 21, 2026
@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch from ca7f1cd to 7903cb6 Compare November 21, 2026 21:39
FlagEnabled (0xB9) defaults to 1 and a stored 0 marks the track as not
usable (RFC 9559 5.1.4.1.4). The main audio and video track is now the
first enabled default track of that type, then the first enabled one.
When every track of a type is disabled, the same order runs over the
disabled tracks, since chapter codecs or control tracks can still make
them usable. A missing or empty element is enabled.

MatroskaFile.Tracks lists each known-size TrackEntry with its number,
UID, type, codec ID, default flag, and enabled flag.
Setting MatroskaTrack.IsEnabled writes FlagEnabled back on save. A
stored 1 to 8 octet element is rewritten in place. An empty or missing
one becomes a 3-octet element, and the TrackEntry and Tracks sizes grow
to hold it, keeping their width when the new size fits. The growth
comes out of the Void right after Tracks, so no element moves; without
that room the save fails and nothing is written. A stored
DocTypeVersion of 1 is raised to 2 when an element is added, since
FlagEnabled has minver 2.

A track the caller never set keeps its bytes. The track at each ordinal
must still carry the number and UID it was read with, or the save fails.
This is the same change as #140.
When no Void right after Tracks can take a new FlagEnabled, the grown
Tracks goes through MatroskaRewrite.TryGrow: everything after it moves
once, and the SeekHead, Cues, Cluster Position, and CRC-32 values follow.
In-place edits and the adjacent Void are still preferred, since they
move nothing. A second Tracks element without room still fails, as
only one is allowed (RFC 9559 5.1.4, maxOccurs 1).

The real-file test compares cluster payloads with Position zeroed,
since a moved cluster's Position changes and its blocks do not.
…sion 2

A FlagEnabled insert that moves later elements now runs through the
widened engine, so a Seek or Cues position that crosses a width boundary
is written wider and CueCodecState and CueRefCluster follow their
Cluster. The save tests compare every Seek that landed in the input with
the output, so a dropped Seek fails them; the real-file toggle test does
the same.

Adding FlagEnabled (minver 2) makes the EBML header's DocTypeVersion at
least 2 (RFC 9559 section 7): a lower stored value is raised in place,
and an empty or missing one is written, growing the header and its CRC.
The header is outside the Segment, so no Segment Position moves.

An unknown-size Tracks with no Void after it names that reason instead
of calling itself a second Tracks. The track fixtures use an EBML header
with DocTypeVersion 4, as muxers write it.
The same change as #140 round 1 (its F2 and F4), applied to this stack:
MatroskaFile.Tracks keeps at most 4096 entries while every entry still
ranks for the main track, and FlagDefault and TagDefault share IsFlagSet.
The same change as #140 round 2 (its #1 and #3), applied to this stack:
MatroskaFile.Tracks is documented as the first 4096 known-size
TrackEntry elements, MatroskaFile.TracksTruncated says when a file had
more, and tests pin the EBML header size widening (+5, 40 7F) and the
wide empty DocTypeVersion shrink (-6).
…e refusals

DocTypeVersion has maxOccurs 1, but a file can store it twice. Every copy
below 2 is now raised, and an empty copy is written as 2, as every
FlagEnabled copy is written, so a reader that takes the first copy no
longer sees 1. The header CRC is recomputed only when a copy changed.

The IsEnabled remarks list the refusals as examples: an unknown-size
Tracks without room, a second Tracks, a SeekHead or TrackEntry that
cannot be bounded, a FlagEnabled over 8 octets, a changed track number
or UID.
Every other public bool in the library has an Is, Has or Uses prefix.
The property is unreleased, so the rename breaks no one. The same change
as #140 round 3.
A header with two empty DocTypeVersion copies must end with both at 2.
Without this row, replacing only the first empty copy stayed green.
@decriptor
decriptor force-pushed the feat/matroska-track-enabled-shift branch from 7903cb6 to 09f9e3a Compare November 21, 2026 22:30
@decriptor
decriptor merged commit 336ed70 into fix/matroska-seekhead-fallback Nov 22, 2026
@decriptor
decriptor deleted the feat/matroska-track-enabled-shift branch November 22, 2026 01:45
decriptor added a commit that referenced this pull request Nov 22, 2026
DocTypeVersion has maxOccurs 1, but a file can store it twice. Every copy
below 2 is now raised, and an empty copy is written as 2, as every
FlagEnabled copy is written, so a reader that takes the first copy no
longer sees 1. The header CRC is recomputed only when a copy changed.
The same change as #148 round 2.
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.

1 participant