Skip to content

fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag - #149

Merged
decriptor merged 31 commits into
feat/matroska-cover-attachmentsfrom
fix/matroska-seekhead-fallback
Nov 22, 2026
Merged

decriptor merged 31 commits into
feat/matroska-cover-attachmentsfrom
fix/matroska-seekhead-fallback

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Stacked on #142 (feat/matroska-cover-attachments @ f3a6078, rebased on main ebd6138, which has #140, #132, #135 and #143). Merge order: #142 → this PR → the chapters PR (#146). The track-flag shift that was #148 is merged into this branch, so this PR also carries it. See "Restack onto main ebd6138" at the end.

When a Matroska save writes a top-level element (Tags, Attachments, and later Chapters) and the existing plan leaves it unlisted, the element now moves right after the first SeekHead. That happens when the SeekHead has no room for a new Seek, or when the element's Seek cannot hold its new offset. The SeekHead is written again with every Seek at the width it needs, and everything after it moves once. This replaces #142's "Matroska SeekHead has no room to reference the attachments" refusal, and it fixes a bug already on main where Tags disappear.

Invariant: after a save that moves elements, every Seek that named an element still names it, at whatever width it now needs, and the element that was written is listed in the first SeekHead. Every CueClusterPosition, CueCodecState, CueRefCluster and CueRefCodecState still names its position; a Cluster Position follows its Cluster, or is voided when it cannot widen in place. The deprecated ReferenceVirtual (RFC 9559 Appendix A.4) is left as it is. Block bytes are unchanged.

Remaining cases where the written element is not listed:

  • Unreadable SeekHead: the first SeekHead cannot be read or has an unknown size. A Tags save then keeps the old best-effort placement, and an Attachments save fails.
  • Later elements cannot be moved (for example a malformed Cues): a Tags save keeps the old best-effort placement and saves with the Tags unlisted, while an Attachments save fails and names the cause.
  • Unlisted Tags edited in place: a Tags element that was never listed and is edited where it is stays unlisted. This predates the PR (review follow-up 1).
  • Optional Cluster Position: one that cannot widen in place is voided.

The bug on main

An artist edit of TaglibSharpSamples/matroska/test1.mkv or test6.mkv re-renders Tags a few bytes larger. Before #132's Tags rendering change, a no-op save did the same; on main ebd6138 a no-op save of these two files is byte-identical. The larger Tags no longer fit, so they are appended after the clusters. The old 2-byte SeekPosition cannot hold the new offset, so the Seek is voided, and ffprobe and mediainfo then show no tags. With this PR, the Tags move after the SeekHead and stay listed. See the table below.

Spec references

  • RFC 9559 section 6.1: when new Top-Level Elements are added, the SeekHead MUST be updated to list all of them.
  • RFC 9559 section 6.3: a second SeekHead lists only Clusters. New entries still go only in the first SeekHead, as in feat: Write Matroska pictures as image attachments #142.
  • RFC 9559 section 25.3.4: without a SeekHead, a reader finds elements before the first Cluster. In that case the element is inserted before the first Cluster.
  • RFC 9559 section 5.1.3.2: Cluster Position is the cluster's own Segment Position.
  • RFC 8794 section 11.3.1: a CRC-32 is the first child. Changed parents get recomputed CRCs.

Design

  • One offset map. Plan.Map (ulong old) is the only place a shift is applied. It adds the insert (ShiftFrom, Delta) and the growth of every rewritten SeekHead or Cues. SeekPosition, every Cues position, Cluster Position and the reachability check all go through it.
  • Values that no longer fit (round 1, F1). When a shifted value does not fit its field in place, that SeekHead or Cues is written again with each value at the width it needs (RFC 8794 §6.1). This applies in any SeekHead, any Cues, during the move, TryGrow, or the insert before a live cluster. Its growth is added to the map, and the lengths are settled until they stop changing. A rendered piece never shrinks below its last length; a Void takes the slack. A Seek for another element is never voided for lack of room. Only the written element's own Seek may be voided, because the move lists it again.
  • Cues positions (round 1, F2). CueCodecState (RFC 9559 §5.1.5.1.2.6) and the historic CueRefCluster/CueRefCodecState (§A.37, §A.39, inside CueReference) follow the map. A zero codec state names the TrackEntry and stays zero.
  • Memory (round 1, F3). The body is sized first and written into one array, and so is the output. A move drops the first body before building its own, and rebuilds the first only if the move is refused. Peak RSS on test1: 176 MB at feat: Write Matroska pictures as image attachments #142, 198 MB at the round-0 head, 153 MB now. test5: 224 → 163 MB.
  • Move plan (TryPlanMove). The first SeekHead is rendered like the pieces above, with a Seek for the target added. The new element goes right after it, and old copies are voided in place. A second SeekHead is patched in place through Plan.Map, or rewritten wider when a value does not fit.
  • When the move is used. It runs only when the normal plan placed the element but no Seek lists it, or when there is no SeekHead and the element would sit after the first Cluster. It cannot be planned when the first SeekHead cannot be read, and it fails when the later elements cannot be moved. In that case the first plan is built again.
  • API for a growing element (internal static bool MatroskaRewrite.TryGrow (ReadOnlySpan<byte> data, byte[] replacement, out byte[] rewritten, out string error)). It replaces the first top-level element that has the replacement's ID. A shorter replacement is padded with a Void in place. A longer one grows in place, and everything after it moves once, with SeekHead, Cues, Cluster Position and CRC-32 values updated. The replacement's own CRC-32 is recomputed. The [Feature]: Honor Matroska TrackFlagEnabled #117 TrackEntry follow-up uses this.
  • Cluster Position and fix: Update Matroska cluster positions and disc numbers #132. fix: Update Matroska cluster positions and disc numbers #132, now on main, patched Cluster Position and CueCodecState in place. This PR folds both into Plan.Map (see "Restack onto main ebd6138"). A Position is rewritten only when it equalled the cluster's old offset, and it is voided if it cannot be widened.
  • Not fixed here. A no-op save still rewrites 8 of the 12 sample files. test1, test4, test6 and gen.webm are byte-identical at base and here. The cause is different: Tags is always re-rendered. The chapters PR fixes it by comparing against what was read.

Tests changed from #142

  • Save_NewAttachments_WithoutSeekHeadRoom_FailsAndLeavesTheFile is now ..._GoAfterTheSeekHeadAndAreListed. It asserts the attachments are listed, are before the cluster, and that the cluster is intact.
  • Save_NewSeekEntry_NeverGoesInTheSecondSeekHead now succeeds. The first SeekHead lists the attachments, and the second still lists only the Cluster.
  • Save_NewAttachments_WithoutASeekHead_GoBeforeTheClusters_OrFail is now ..._GoBeforeTheClusters. The cluster moves whole.
  • Save_RewritesCommonFields_AndLeavesTheClusterBytes covers a file with no SeekHead. The grown Tags now go before the cluster, and the cluster moves whole. I checked that ffprobe does not find Tags after the clusters in a file with no SeekHead.
  • MatroskaIntegrationTests: cluster comparisons ignore Position and CRC-32. The "SeekHead" inconclusive branch is gone, because test1/3/6/8 now pass outright. A new Save_RealMatroska_ArtistEdit_KeepsTheTagsListed test was added.

New unit tests are in MatroskaSeekHeadFallbackTests.cs:

  • grown Tags with a full, CRC'd SeekHead, CRC'd Cues and a Cluster Position
  • the first SeekHead's Seeks widen instead of being voided
  • a move whose second-SeekHead Cluster Seek cannot hold the moved offset widens that SeekHead (round 1: it was refused before)
  • TryGrow growing and shrinking, including a stale caller CRC
  • TryGrow with a missing element

New in round 1 (MatroskaShiftWidthTests.cs):

  • a 70 KB cover over a 2-byte CueClusterPosition, with the Cues before the Cluster (F1); also pins Cluster Position == offset and a kept non-Seek SeekHead child (F5)
  • a 70,000-character title whose 1-byte Tags Seek forces the move (F1)
  • CueCodecState, CueRefCluster and CueRefCodecState follow the move, and a zero CueCodecState stays zero (F2)
  • TryGrow across a SeekPosition width boundary (65534 → 65537) and a CueClusterPosition boundary (65533 → 65536), both checked with AssertSeeksPreserved, which fails if any Seek that landed before is missing after (feat: Move later Matroska elements when a track flag needs room #148 F1/F2)
  • the insert before a live, unknown-size Cluster widens its cue
  • a wide SeekHead (4-byte positions, 8-byte size) is written shorter, padded with a Void
  • a move refused because the SeekHead cannot be read rebuilds the first plan

The first six fail at round-0 head 8769001 and pass now. The reworked second-SeekHead test fails at 8769001 too.

I reverted each guard and confirmed a test goes red:

  • the move itself, and the Cluster Position patch
  • the grown-element CRC
  • the Seek widening
  • the Cues widening
  • the CueCodecState mapping, the CueReference walk, and the zero codec state
  • the kept SeekHead children

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature
  • Breaking change
  • Documentation update (CHANGELOG)

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed
  • My changes generate no new warnings

Testing

  • dotnet build -c Release: 0 warnings, 0 errors
  • dotnet test -c Release (rebased on feat: Write Matroska pictures as image attachments #142 e7b7d9d): net8.0 4541 passed / 14 skipped / 0 failed; net10.0 the same. The reviewer's 115-cell grid gives the same answers before and after the rebase.
  • dotnet format --verify-no-changes: clean
  • TAGLIBSHARP2_TEST_MATROSKA=<file> dotnet test --filter "FullyQualifiedName~MatroskaIntegrationTests", run locally:
    • 4/4 passed on test1–8.mkv, Turning Lime.mkv, and the reviewer's gen/genfull/manyfull/test6-2shmin/test6-2sh4/live/cuesfront/manyclusters/nocrc/small/piped.mkv and gen.mka
    • 2 passed and 2 inconclusive on gen.webm (WebM has no attachments)
    • the new 70 KB cover test fails at 8769001 on test1

Round 1: before/after (round-0 head 8769001 vs this head)

I ran the reviewer's grid: 22 inputs × noop, artist, 200-character title, 247 B cover and 67 KB cover. Each output went through the same verify.py (every Seek, Cue, CueRelativePosition, Position, PrevSize, CRC, and the cluster hash), ffprobe, mediainfo and ffmpeg -f null.

8 of 115 cells changed, all intended. The 67 KB cover on test1, test3, test7, test8, genfull, manyfull, live2shfull and test6-2shmin was refused with "no room", and now saves. In every one:

  • no bad Seek, Cue, Position or CRC
  • ffprobe shows 1 attached pic, and mediainfo shows Cover=Yes
  • decoded frames after -ss 0/3.3/7.7/12.1/20.5, and a full decode, are identical to the input

The other 107 cells are unchanged.

A 70,000-character title on test1 was saved at 8769001 with the Tags Seek dropped (ffprobe and mediainfo showed no title). Now it is listed, and ffprobe and mediainfo read it. test3 and test7 are unchanged.

In test3/7/8 the first cluster's 2-byte Position cannot hold its new 3-byte offset, so that optional element is voided (46 of 47 Positions remain, all correct).

Real files: main build vs this branch

Inputs: TaglibSharpSamples/matroska/test1..8.mkv, taglib-sharp Turning Lime.mkv, and ffmpeg 9.0.2 gen.mkv, gen.mka and gen.webm.

Operations:

  • noop: save without edits
  • artist: set the artist
  • cover: add a JPEG front cover

After every save I checked:

  • ffprobe format tags (TITLE, ARTIST)
  • attached-picture streams
  • mediainfo Title, Performer and Cover
  • ffmpeg -v error -i out -f null -
  • the cluster payload (every child except Position and CRC-32) compared to the input
  • every SeekHead entry and every CueClusterPosition points at its element
  • top-level CRC-32 values
  • every Cluster Position equals its offset
File main noop / artist: ffprobe tags this branch noop / artist / cover Decode Clusters Offsets
test1.mkv none / none (Tags Seek dropped) TITLE / TITLE+ARTIST / TITLE + 1 attached pic clean payload identical all Seeks and 10 Cue refs correct
test6.mkv none / none (Tags Seek dropped) TITLE / TITLE+ARTIST / TITLE + 1 attached pic clean payload identical all Seeks correct
test2, test3, test8 TITLE / TITLE+ARTIST same / same / + 1 attached pic (#142 refused test3/8) clean payload identical; only Position changes when moved all 47 Position values correct
test5 TITLE / TITLE+ARTIST same / same / + 1 attached pic clean identical correct
test7 (junk in clusters) TITLE / TITLE+ARTIST same / same / + 1 attached pic "Invalid track number 87", same as the input only Position bytes differ 37 Position values correct
test4 (live, no SeekHead, ffprobe cannot open it) none / none none / ARTIST / 1 attached pic same error as the input n/a no SeekHead
Turning Lime.mkv TITLE / TITLE+ARTIST same / same / cover clean identical correct (the input's one wrong CueClusterPosition is unchanged)
gen.mkv, gen.mka TITLE+ARTIST / changed ARTIST same / same / + 1 attached pic clean identical correct
gen.webm TITLE+ARTIST / changed ARTIST same / same / refused (WebM has no attachments) clean identical correct

mediainfo agrees with ffprobe in every row, including Cover = Yes after cover saves.

Round 2

Commits e984cda and 39c4b3f (head 39c4b3f):

  • F1, linear work. This was the cascade where each widened Cues pushes the next over a width boundary. Now:

    • on the first value that does not fit, every known-size SeekHead and Cues is rendered, so the body is built at most twice;
    • Map uses a binary search over prefix sums;
    • after 4 rounds of minimal widths, every moved value is written at 8 octets. The rounds are capped at 7. A value that first moves after the wide round can still grow once, so a crafted file can reach the cap; the save then refuses that plan (a move falls back to its first placement). Corrected in round 3: this line used to say the lengths settle within 2 more rounds, which is not always true.

    The reviewer's 6,400-Cues, 132 KB file with 3-byte values now saves in about 70 ms of CPU (it was 140 s). At 1,600 two-byte Cues it is 27 ms, against 2,746 ms at 22f84e7.

    Pin: TryGrow_CascadingCueWidths_SettleInLinearWork compares allocated bytes for 150 against 300 cascading Cues, and must come in under 3x. At 22f84e7 it fails: 18 MB vs 72 MB. Now it is 0.7 MB vs 1.4 MB. TryGrow_CascadingCueWidths_EveryCueFollowsTheCluster checks every value.

  • F2: TryGrow_ClusterPositionThatCannotWiden_IsVoided. A 2-byte Position at 0xFFFE is voided, the Cluster keeps its length, the cue lands and the CRCs stay valid. The reviewer's V1 (leave it stale) and V2 (fail the save) reverts both turn it red. The real-file large-cover test now also asserts that every remaining Position equals its Cluster's offset; V1 fails it on test3.

  • F3: the CHANGELOG, the invariant and the test summary name the positions that are moved, say a Position that cannot widen is voided, and say ReferenceVirtual is left as it is.

  • F4: RenderSeekHead refuses a moved position that would wrap. The move is then refused and the first plan is used, and the garbage Seek is left as it was. Pin: Save_Move_SeekPositionThatWouldWrap_IsNotWritten, which fails at 22f84e7 ("wrapped to 38").

Before/after: the reviewer's 115-cell grid gives identical answers at 22f84e7 and 39c4b3f. Gates (on #142 2afe3b2): net8.0 and net10.0 4585 passed / 14 skipped, 0 warnings, format clean. (Corrected in round 3: this line used to claim 100% patch coverage on the round's lines. The reviewer measured 69/73; MakeSeek's 8-octet branch never ran.)

Round 3

Commits 108397b, 2677552 and 84fdb03 (head 84fdb03):

  • F1, stack overflow on nested CuePoints. A 90 KB Cues of 10,000 nested CuePoints overflowed the stack of a title-edit save run on the thread pool and killed the process; base 2afe3b2 saved it. Both Cues walkers, TryPatchCueValues (in place) and RenderCueMaster (rendered), now follow only the RFC 9559 §5.1.5 paths: Cues > CuePoint > CueTrackPositions > CueReference. A position is read only where the spec puts it: CueClusterPosition and CueCodecState in CueTrackPositions, and CueRefCluster and CueRefCodecState in CueReference. Any other nesting is copied as it is, so the recursion is at most four levels deep.

    • Pins: Save_Move_DeeplyNestedCuePoints_SavesOnASmallStack (title-edit save) and TryGrow_DeeplyNestedCuePoints_RendersOnASmallStack (render path). Both run on a thread with a 256 KiB stack. At 04d5de3 both crash the test host with a stack overflow.
    • Pin: TryGrow_CuePositionOffTheSpecPaths_IsCopiedAsItIs, in place and rendered. It fails at 04d5de3.
    • Reverting either walker alone to its old any-depth rule crashes the matching small-stack test.
    • The reviewer's triggers now save: thread pool at depths 5,000 to 200,000; main thread at 50,000 and 200,000, with both the title200 and cover ops.
    • Sweep: the only other recursive EBML walker on the read/save path is ReadSimpleTag and SimpleTag.Render. It is pre-existing on main and unchanged here, so it is listed as a follow-up below.
  • F2, the linear-work pin. MatroskaRewrite.SettleCalls and SettleSteps are thread-static counters with no allocation, for values placed and growth entries examined. TryGrow_CascadingCueWidths_SettleInLinearWork now also requires:

    • steps > 0;
    • steps at most 10 per value (log2 of the growth count, plus 1);
    • steps and values growing less than 3x from 150 to 300 Cues.

    The reviewer's M1 (a linear scan over Growth) fails it whether or not the scan counts its steps.

  • F3, the 8-octet SeekPosition branch. TryGrow_CascadingSeekPositions_GoWideAndEverySeekLands builds twelve SeekHeads of five Seeks, each for its own empty Chapters element at 0xFFFF − 5k. It asserts:

    • every Seek lands on a Chapters element;
    • all 60 SeekPositions are 8 octets;
    • the CRCs are valid.

    M5 (rendered SeekHeads ignore WideValues) turns it red. The round-2 coverage claim above is corrected.

  • F4: the TrySettle summary, the CHANGELOG and the round-2 line above now say the rounds are capped and a file that reaches the cap is refused.

Before/after, 04d5de3 vs 84fdb03:

  • The reviewer's 138-cell grid has 0 changed answers. One cover cell differs by one byte between runs, at both heads, because of the random attachment UID's width. The test4 lines differ only in ffprobe's pointer addresses.
  • The chain1–4 and seekc files are byte-identical.
  • The nested-CuePoint files change in 2 bytes: the innermost, off-path CueClusterPosition is now left as it was.

Gates:

  • dotnet build -c Release: 0 warnings.
  • dotnet test -c Release: net8.0 and net10.0 4589 passed / 14 skipped.
  • dotnet format --verify-no-changes: clean.
  • Env-gated tests: 4/4 on test1/2/3/7/8 and Turning Lime.
  • Patch coverage on this round's changed lines in MatroskaRewrite.cs (VS code coverage, net10.0): 26/26. MakeSeek's 8-octet branch now runs.

Follow-up, pre-existing on main and not changed here: nested SimpleTags (RFC 9559 makes SimpleTag recursive) drive MatroskaFile.ReadSimpleTag into unbounded recursion, and 10,000 levels overflow a thread-pool Read.

Round 4

Commit 52bf607 (head 52bf607), test-only:

  • F1: MatroskaIntegrationTests.CollectCues, the oracle behind LandingCues, walked the Cues at any depth. It counted off-path CueClusterPositions that the save rightly leaves alone, and had no depth bound. It now reads only the RFC 9559 §5.1.5 path, the same as production and the unit helper Collect. The same fix goes to its twin MatroskaSaveTests.TryFindCuePosition, which is pre-existing.
  • Env-gated TAGLIBSHARP2_TEST_MATROSKA results:
    • the reviewer's nine off-path files, mf-*.mkv: mf-nest and mf-flat failed 42 vs 0 before; all nine now pass 4/4;
    • all 23 real samples pass (gen.webm 2 passed, 2 skipped);
    • the nested-CuePoint files d10000 and m50000 pass 4/4.
  • Gates: 0 warnings; net8.0 and net10.0 4589 passed / 14 skipped; format clean.

Restack onto main ebd6138 (#140, #132, #135 and #143 merged; #148 merged into this branch)

This branch was rebuilt on #142 f3a6078 as two commits:

Why two commits instead of the earlier 16:

  • fix: Update Matroska cluster positions and disc numbers #132 threaded a clusters list through TryBuild/TryPatch and patched Cluster Position and CueCodecState in place.
  • Replaying the old commits over that left every intermediate commit failing to compile, and keeping each one correct would have meant rewriting all of them.
  • Both commits here build and pass. The final tree's Seek and Cues positions are unchanged from the reviewed head.

How #132 is folded in. Main's in-place Delta patching on this path (TryPatchClusterPosition, TryAddDelta, TryAddDeltaOrVoid, UpdatePieceCrc) is replaced by this PR's shared map:

Deliberate change from #132: CueCodecState is widened, not voided. RFC 8794 §7.2 lets an unsigned integer use 0 to 8 octets, so widening keeps the value. A missing CueCodecState reads as 0, "the codec state is in the TrackEntry" (RFC 9559 §5.1.5.1.2.6). Voiding it would therefore change its meaning.

  • The test is renamed Save_CueCodecStatePastOneByte_WidensAndFollowsTheCluster. It now asserts that the value read back equals the Cluster's new offset. That assertion fails at 304bc06, where the element is voided.
  • The CHANGELOG line from fix: Update Matroska cluster positions and disc numbers #132 says so.
  • Real file: in genfull.mkv I turned a 1-octet CueRelativePosition into a 1-octet CueCodecState naming Info (161). After a title edit it is 631 in 2 octets; after an artist edit, 483. Both still name Info, every CRC-32 matches, ffprobe and mediainfo read the new tags, and ffmpeg -v error -f null decodes cleanly.

Cluster Position is unchanged from #132's rule: a value that cannot widen in place is voided, because it is optional and a wrong value is worse than none.

Cues walker. #132's TryPatchCueValues walked the Cues at any depth.

Track flag and Cluster Position. The new Save_InsertWithoutAVoid_EveryClusterPositionFollowsItsCluster covers three Clusters with Position, the second under a CRC-32, moved by an added FlagEnabled. It checks that every Position equals its Cluster's new offset, the blocks are unchanged, the Cues follow, and every CRC-32 matches.

  • Real files, track-flag toggle with verify.py:

    file Cluster Positions bad / total bad Cues bad Seeks bad CRC-32 payload
    test2 0 / 47 0 0 0 unchanged
    test3 0 / 47 0 0 0 unchanged
    test7 0 / 37 0 0 0 unchanged
    test8 0 / 47 0 0 0 unchanged
  • test1, test5, manyclusters and Turning Lime also save. Their payloads are unchanged, apart from the one cue already broken in Lime's source.

  • ffmpeg -v error decodes cleanly, except test7's "Invalid track number 87", which the original file also gives.

Test reconciliation with main and #142:

  • Main keeps the real-file track tests in MatroskaIntegrationTests and the Save helper in MatroskaTrackEnabledSaveTests, so the shift versions were folded in there. The separate MatroskaTrackIntegrationTests is gone.
  • feat: Write Matroska pictures as image attachments #142's combined real-file test Save_RealMatroska_CoverAndTrackFlag_AreBothWritten used to compare raw Cluster bytes. A file without a Void after Tracks now saves instead of refusing, and the move rightly changes Position and CRC-32. The test now compares payloads and checks that every Seek and Cue still lands. On test2/3/7/8 that save was checked with verify.py, ffprobe, mediainfo and a decode.

Gates at fbce9f2 (superseded by Round 5 below):

  • dotnet build -c Release: 0 warnings, 0 errors.
  • dotnet test -c Release: net8.0 and net10.0 4934 passed / 23 skipped.
  • dotnet format --verify-no-changes: clean.
  • Env-gated TAGLIBSHARP2_TEST_MATROSKA: all 23 real samples and the nine mf-*.mkv files pass 8/8 (gen.webm: 5 passed, 3 skipped).
  • Commit 3c4bdf9 alone: 4925 passed / 23 skipped.

Before/after: the reviewer's grid (25 inputs × 6 ops), 336ed70 against the 07d9906-based tree, whose Matroska code is the same as this head's.

  • 80 of 150 cells changed, all from fix: Update Matroska cluster positions and disc numbers #132's Tags rendering on main: an omitted TargetTypeValue is no longer written as 50.
  • The Tags come out 4 bytes shorter. On noop and cover saves, test1, test6-2sh4, nocrc and gen.webm used to move their Tags after the SeekHead; now the re-rendered Tags fit where they were, and a noop save keeps the file's exact length.
  • In every changed cell the tag values, ffprobe and mediainfo output, decode result and payload hash are the same, and no Seek, Cue or Cluster Position is bad.

Follow-up, PR #151: when it merges, #142 and this PR rebase onto it. This PR's spec-path walker then replaces #151's loops; it also walks CueReference and widens instead of voiding.

Round 5

Commits 65a9189, dd51322, 16b39a6, 498c1e2, d913c38, 6f43934, ef530c7 and fb58a98 (head fb58a98):

  • F1 (major), empty CueRefCluster. RFC 8794 §7.2 reads an empty unsigned integer with no default as 0. CueClusterPosition and the historic CueRefCluster and CueRefCodecState have no default. CueCodecState's default is 0 (RFC 9559 §5.1.5.1.2.6), so an empty one reads the same. (Corrected after round 6: this bullet used to say none of the four has a default.)
    • TryMoveCueValue, which both Cues walkers use, now reads an empty value as 0. It stays as it is when 0 does not move, and is written wider when it does.
    • The in-place walker's separate empty-CueClusterPosition refusal is gone. That also fixes the refusal base had (review follow-up).
    • Pins: Save_InsertBeforeLiveCluster_EmptyCueValues_AreKept (live insert, in place) and TryGrow_EmptyCueValues_AreKeptWhenTheCuesAreWrittenAgain (rendered). Both fail at fbce9f2.
    • The reviewer's kl-ref-empty.mkv now saves an artist edit and a 200-character title. k-ref-empty.mkv now saves cover, bigcover, flag and flagtitle; all were refused at fbce9f2.
  • F1, masked error. When the move after the first SeekHead fails and the first plan cannot list the element either, the save now returns the move's error from the reachability check, where it used to return the SeekHead one. The fallback build in between rebuilds a plan that just succeeded, so it cannot fail, and has no override.
    • Pins: Save_NewAttachments_MoveThatCannotUpdateTheCues_NamesTheCues, plus a matrix, Save_NewAttachments_ThatMustMove_SucceedOrNameTheirCause. The matrix has one success row and three refusals, each naming its own cause and leaving the file unchanged: malformed Cues → "Cues", unreadable SeekHead → "SeekHead", WebM → "WebM". The Cues rows fail at fbce9f2.
  • Twin sweep for empty values:
    • Seek readers (TryReadSeek, used by in-place and rendered SeekHeads) already read an empty SeekPosition as 0.
    • Cluster Position (ef530c7): an empty Position is 0. It follows only when its Cluster was at offset 0; it cannot widen in place, so it is voided. Pinned by Save_InsertAtOffsetZero_EmptyValuesThatNameIt_Move, which also covers an empty CueClusterPosition that must move and be written wider. fix: Update Matroska cluster positions and disc numbers #132's Save_EmptyClusterPosition_KeepsThePayloadWhenTheClusterGrows (empty, not at 0) still keeps it.
    • CueCodecState and CueRefCodecState: empty or 0 still names the TrackEntry and is kept.
  • F2: the MatroskaTag.Pictures remarks now say that new Attachments go right after a full first SeekHead, or before the first Cluster when there is no SeekHead. They also list the remaining refusals.
  • F3: the toggled-track real-file test compares Cluster payloads without Position, CRC-32 and Void, as ClusterPayloads does.
    • The large-cover test's Position check now keeps a Position that was already wrong in the source as stored. A correct Position must stay correct or be voided.
    • The reviewer's crafted files all pass 8/8: CRC'd Clusters with Position, and stale, empty and zero Positions.
    • Skipping the Cluster Position pass still fails the large-cover test on test3.mkv.
  • F4: Save_InsertedFlagWhoseLaterElementsCannotMove_FailsAndWritesNothing. A missing FlagEnabled, no Void after Tracks, and a 9-octet CueClusterPosition: the save fails, the file is unchanged, Render is empty, and the error names the Cues. Reverting M9 turns it red.
  • F5: the "bug on main", "Cluster Position and fix: Update Matroska cluster positions and disc numbers #132" and "Not fixed here" lines above are updated, and so is the title.

Before/after, on the reviewer's 384-cell grid, fbce9f2 against 6f43934 (ef530c7 changes only an empty Position at offset 0):

  • k-ref-empty: 4 cells refused → saved, as intended.
  • Cover cells: the sha differs, because each save writes a random FileUID.
  • test4: only ffprobe pointer addresses differ.
  • Every other cell's tag values, Seeks, Cues, Positions and CRC-32s are the same. The payload-hash differences in the recorded grid go away when both outputs are hashed with the current verify.py.

Gates at fb58a98:

  • dotnet build -c Release: 0 warnings, 0 errors.
  • dotnet test -c Release: net8.0 and net10.0 4944 passed / 23 skipped.
  • dotnet format --verify-no-changes: clean.
  • Env-gated TAGLIBSHARP2_TEST_MATROSKA: 51 files pass. They are the 8 TaglibSharpSamples Matroska files, Turning Lime, 13 generated files (gen.webm: 5 passed, 3 skipped), the 9 mf-* files, the reviewer's 18 crafted files, and 2 new crafted files with empty values.
  • Fuzz (reviewer's harness, new head, empty-value files): 220,295 runs, 0 exceptions, 0 slow.
  • Allocation is linear: about 57 bytes per Cue at 5,000 and at 10,000 empty-value CuePoints.
  • Targeted reverts of every new guard turn tests red.
  • Patch coverage on this round's changed source lines: 8 of 8.

PR #151: this PR's MatroskaRewrite.cs replaces #151's Cues loops when both merge. #151's SimpleTag depth cap and tests are kept.

Round 6

Commit cf7efc9 (head cf7efc9), docs only:

  • F1: the TryMoveCueValue comment and the Round 5 bullet now say that CueCodecState defaults to 0 (RFC 9559 §5.1.5.1.2.6), while the other three Cues positions have no default. The CHANGELOG says an empty Cues position is kept, or written wider when the offset 0 it names moves.
  • F2: the unlisted-cases list now includes a Tags save whose move cannot update the Cues (best-effort placement; Attachments fail instead). The Design line about when the move is used is corrected the same way.
  • Gate: dotnet build -c Release, 0 warnings, 0 errors; dotnet format --verify-no-changes, clean. No code changed.

An edited or added top-level element stays listed in the SeekHead (RFC 9559
section 6.1). When the SeekHead has no room for the element's Seek, or the
Seek cannot hold the new offset, the element goes right after the first
SeekHead and everything after it moves once. Without a SeekHead the element
goes before the first Cluster.

Every Segment Position follows a move through one map: each SeekPosition in
every SeekHead, the Cues CueClusterPosition, CueCodecState, CueRefCluster and
CueRefCodecState (RFC 9559 sections 5.1.5, A.37, A.39), and Cluster Position
(section 5.1.3.2), with their CRC-32 values. A value that no longer fits its
field is written wider (RFC 8794 sections 6.1 and 7.2), and its SeekHead or
Cues grows. The lengths settle in linear work, going to eight octets after
four rounds and capped at seven. A Cluster Position that cannot widen in
place is voided, since it is optional.

This replaces the in-place Delta patching from main (#132) on the same path:
- Cluster Position and CueCodecState now follow the shared map.
- A CueCodecState that outgrows its field is widened rather than voided. A
  missing CueCodecState reads as 0, "the codec state is in the TrackEntry",
  which is a different value.
- The Cues walkers follow only the RFC 9559 section 5.1.5 paths, so a file
  that nests CuePoints thousands deep cannot exhaust the stack.
- Main's names (MatroskaIds.Position, TryVoidElement, OffsetSteps) are kept.

Before this, an artist edit or a no-op save on test1.mkv or test6.mkv
dropped the Tags Seek, a cover over about 64 KB on a file with two-byte
CueClusterPositions was refused, and a nested-CuePoint Cues overflowed the
stack on a live insert.
Adding a missing FlagEnabled used to need a Void right after Tracks; without
one the save failed. Now the room comes from that Void when it has enough,
and otherwise Tracks grows through TryGrow: everything after it moves once,
and every SeekHead, Cues and Cluster Position value and CRC-32 follows,
widened when it no longer fits. DocTypeVersion is still raised to at least 2
in every copy. A save still fails, writing nothing, when an unknown-size or
second Tracks has no Void to give the room.

The DocTypeVersion tests move to MatroskaTrackEnabledShiftTests with the
other shift tests, and the in-place-only refusals become move tests. A new
test checks that every Cluster Position, including one under a CRC-32,
follows its Cluster after the move. The real-file toggled-track test checks
every Seek and compares clusters without their Position, and the combined
cover and track-flag tests check their Seeks against the original file.
@decriptor
decriptor force-pushed the fix/matroska-seekhead-fallback branch from 336ed70 to fbce9f2 Compare November 22, 2026 03:18
RFC 8794 section 7.2 reads an empty unsigned integer with no default as 0,
and CueClusterPosition, CueCodecState, CueRefCluster and CueRefCodecState
have none. The Cues walkers refused an empty CueClusterPosition or
CueRefCluster, so a save that moved the Cues failed on a file that readers
accept; since this branch walks CueReference, that included an artist edit
on a live stream. An empty value is now 0: it stays as it is when 0 does
not move, and is written wider when it does.

When the move after the first SeekHead fails and the first plan cannot
list the element either, the error is now the move's, which names what the
file needs fixed, instead of the SeekHead one.
…e save

When adding FlagEnabled must grow Tracks and TryGrow cannot move what
follows, the save fails, writes nothing, Render is empty, and the error
names the Cues. Reporting success there would silently drop the flag.
The Pictures remarks still said a SeekHead without room fails the save.
The Attachments now go right after the first SeekHead, or before the first
Cluster without one, and the save fails only when the first SeekHead cannot
be read or the later elements cannot be moved.
… real-file tests

The toggled-track test compared Cluster payloads with only Position zeroed,
so a correct save of a file whose moved Cluster has a CRC-32, or whose
Position had to be voided, failed it. It now leaves out Position, CRC-32
and Void as ClusterPayloads does. The large-cover test required every
Position to name its Cluster, which a Position already wrong in the source
cannot; such a Position must now be kept as stored, and a correct one must
still be correct or voided.
… own cause

An Attachments save that must move after a full SeekHead either lists the
element or fails with the cause of that refusal and leaves the file as it
was: malformed Cues name the Cues, an unreadable SeekHead names the
SeekHead, and WebM names WebM.
@decriptor decriptor changed the title fix: Keep a moved Matroska element listed in the SeekHead fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag Nov 22, 2026
An empty Position is 0 (RFC 8794 section 7.2), which names a Cluster at
Segment offset 0. Such a Position was skipped, so after an insert before
that Cluster it still claimed offset 0. It now follows like any other
Position: it cannot widen in place, so it is voided as optional. The
CueClusterPosition that names offset 0 the same way is written wider.

The fallback-build branch of the move no longer replaces its own error:
it rebuilds the plan that just succeeded, so it cannot fail there, and the
move's error still reaches the caller through the reachability check.
… is widened

RFC 9559 section 5.1.5.1.2.6 gives CueCodecState a default of 0, so an
empty one reads as 0 by that default; the other three Cues positions have
none and read as 0 by RFC 8794 section 7.2. An empty position is kept, or
written wider when the offset 0 it names moves.
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 686041d.

This branch now also contains #146 (Matroska chapters, approved at 8766d27). It is stacked on #142. Merge order: #151 first, then #142, then this PR. #151 fixes the Cues and SimpleTag stack overflow (#150), and its tests sit on top of this PR's Cues walker. When #151 is merged into this branch, take this PR's MatroskaRewrite.cs, keep #151's SimpleTag depth cap and tests, and rename #151's WideFile test helper (it clashes). The reviewer checked that merge: it builds and passes 4953/23.

What was checked:

  • Round 6 approved fb58a98. Its two trivial doc findings are fixed in cf7efc9:
    • The CueCodecState comment now gives its default of 0 (RFC 9559 §5.1.5.1.2.6).
    • The CHANGELOG says when an empty Cues position is written wider.
    • The PR body's list of unlisted cases is complete.
      That commit is docs-only, and I verified it directly.
  • Earlier rounds:
    • All findings from rounds 1–5 are fixed and pinned. Every pinning test fails at its earlier head and passes here.
    • The 384-cell before/after grid shows no save that went from saved to refused, and no bad Seek or CRC in any output.
    • Fuzzing threw 0 exceptions.
    • The fixer's twin table was checked row by row against the code.
  • 686041d contains cf7efc9 plus feat: Read and write Matroska and WebM chapters #146's commits. Its diff against feat: Read and write Matroska and WebM chapters #146's approved head is only cf7efc9's doc change.
  • Gates:

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit 3c146b0 into feat/matroska-cover-attachments Nov 22, 2026
@decriptor
decriptor deleted the fix/matroska-seekhead-fallback branch November 22, 2026 05:20
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