Skip to content

feat: Write Matroska pictures as image attachments - #142

Merged
decriptor merged 41 commits into
mainfrom
feat/matroska-cover-attachments
Nov 22, 2026
Merged

decriptor merged 41 commits into
mainfrom
feat/matroska-cover-attachments

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Setting MatroskaTag.Pictures now writes image attachments. Before this change the save copied the Attachments element through and ignored the pictures.

Invariant: every attachment the caller did not change keeps its bytes, and the pictures read back from a saved file are the pictures that were set.

  • Matching. An existing image attachment that matches a picture keeps its element bytes, FileName, FileUID and place in storage order. A match needs the same media type (compared as stored, case-insensitive, so a picture read from a file with a loose FileMediaType such as image/ or image/jpeg still matches its own attachment), picture type, description and bytes. Only pictures that will be written are validated. tag.Pictures = tag.Pictures, copies into another IPicture type, and reorders are all no-ops.
  • Fonts and other non-image attachments are always copied unchanged. Removing a picture removes only its attachment. With no attachment left, the element is voided along with its SeekHead entry.
  • Naming (RFC 9559 §21.1, https://www.matroska.org/technical/cover_art/index.html):
    • A new front cover is cover.jpg or cover.png, chosen from its media type; another image type keeps its own extension (a GIF front cover is cover.gif; RFC 9559 recommends only JPEG and PNG). It goes first in storage order, as the RFC asks, unless the file keeps its normal cover (a cover.* attachment, matched case-sensitively as the guidance says): that one keeps its place and the new one goes after the kept attachments. A kept small_cover, cover_land or other image read as a front cover is not the normal cover, so the new cover.jpg still goes first.
    • The guidance names only cover variants, so every other PictureType gets a fixed stem: back, artist, band_logo, other, and so on. None of them contain "cover", so readers that look for cover names do not pick them. A repeated name becomes cover_2.jpg, other_2.jpg, and so on.
    • The description goes in FileDescription. It is left out when it is empty or equal to the name.
    • PictureType round-trip: reading maps those exact names back to the type before the existing "cover"/"Front" heuristic runs, so a saved picture keeps its type and description. small_cover, cover_land and small_cover_land read as the front cover.
  • FileUID comes from RandomNumberGenerator: nonzero, and different from every FileUID already in the file (Track, Chapter and Edition UIDs are separate spaces and are not checked).
  • Media types. An image/* type is written as given: JPEG and PNG are recommended, and GIF, WebP and SVG are written with their own type. An empty type is detected from the bytes. A non-image type, non-ASCII text, or empty data fails the save. I chose to refuse because such an attachment would not read back as a picture, so Pictures could never remove it.
  • WebM has no Attachments element. A save that would add an attachment to a WebM file fails, and the file is untouched. Pictures = [] on a WebM file still saves the tags.
  • Tags that target an attachment. RFC 9559 §5.1.8.1.1.6 says a TagAttachmentUID MUST match an attachment. A removed attachment's UID is stripped from tag targets, and a tag left with no target is dropped rather than turned into a file-level tag.
  • No-op save. A save that does not set Pictures (or call Clear()) leaves the Attachments element byte for byte, as feat: Save Matroska and WebM tags #106 does today.
  • Clear() removes every picture, so Clear() and a save now also remove the image attachments (cover art). Fonts and other non-image attachments stay. This is listed under Changed in the CHANGELOG.

Save placement

The attachments pass runs first through the generalized Tags engine, so both elements follow the same rules (RFC 9559 §6.7 and §25.3.2):

  1. Fit in place, or in a Void.
  2. Otherwise replace the element if it is last, or insert before a last unknown-size Cluster, patching Cues and SeekHead.
  3. Otherwise append after the last Cluster.

Clusters do not move, and Cues and SeekHead offsets are patched the same way as for Tags.

  • SeekHead reference required for Attachments. RFC 9559 §6.3 says the SeekHead MUST reference every top-level element, and players only find attachments after the Clusters through it. So a new or moved Attachments element must either get a SeekHead entry or sit before the first Cluster; otherwise the save fails and the file is untouched. Without this check, a cover that ffprobe could not see was written to test1.mkv.
  • SeekHead growth. The SeekHead now widens its size field when it grows into the Void after it. test2.mkv needed this: its payload was 110 of 126 bytes.
  • Void after the SeekHead. An element the SeekHead does not reference yet skips the Void right after the SeekHead, so the SeekHead can grow into it (RFC 9559 §25.2).
  • Second SeekHead. A new entry is added only to the first SeekHead (RFC 9559 §6.3: a second one references Clusters only). This also stops Tags entries being added twice.
  • CRC-32. An existing CRC-32 that led the Attachments element is rebuilt.
  • Large pictures. EbmlWriter.Size now writes 5 to 8 byte sizes, so a picture over 256 MB no longer gets a corrupt size.

Out of scope

Spec references: RFC 9559 §5.1.6 (Attachments, AttachedFile, FileDescription, FileName, FileMediaType, FileData, FileUID), §5.1.8.1.1.6, §6.2, §6.3, §6.7, §21.1, §25.2, §25.3; RFC 8794 §6.2 (sizes), §11.3.1 (CRC-32); cover art guidance page above.

Motivation and Context

Closes #115

Type of Change

  • New feature (non-breaking change that adds functionality)

The changes in behaviour are listed under Changed in the CHANGELOG:

  • A save that sets Pictures can now fail (non-image picture, WebM, or a cover the SeekHead cannot reference).
  • back.jpg, artist.png and similar names now read with their picture type instead of Other.

No public API changed; the PublicApi snapshot is unchanged.

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, README, ROADMAP, MIGRATION-FROM-TAGLIB, Pictures XML docs)
  • My changes generate no new warnings

Testing

Gates

Unit tests are in tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs, 49 test methods, 89 cases with data rows. They cover:

  • placement after the last Cluster, in a Void, and before an unknown-size Cluster (Cues and SeekHead shifted)
  • SeekHead growth with a widened size field, no room, no SeekHead, and a second SeekHead
  • every PictureType round trip, numbered names, and name collisions
  • no-op saves (same, copied and reordered pictures), idempotent re-saves
  • add, replace and remove, Clear(), and the only attachment voided
  • fonts kept byte for byte, tags targeting a removed UID
  • CRC-32, two Attachments elements merged, and malformed Attachments (fails only when pictures change)
  • a cut at every byte of Attachments (never throws), a 3 MB picture, and EBML size widths
  • media types: non-image, detected and other image types
  • WebM refusal and WebM tag-only save
  • async save and MediaFile save twins

I reverted each guard in turn: void skip, tag drop, matching, WebM, name map, front-first, size width, CRC, first-SeekHead-only, SeekHead widening and reachability. Each revert turned at least one test red.

Integration tests. TAGLIBSHARP2_TEST_MATROSKA runs MatroskaIntegrationTests, which saves a temporary copy with untouched pictures and with a back cover added then removed. The run passed on withcover.mkv, withcover.mka, fontonly.mkv, bare.mkv, Turning Lime.mkv, test5.mkv and test2.mkv. It is inconclusive (a documented refusal, with the file shown unchanged) on test1/3/6/7/8.mkv, test4.mkv and bare.webm.

Real-file verification

Inputs:

  • taglib-sharp Turning Lime.mkv, which has cover.png.
  • TaglibSharpSamples/matroska/test1..8.mkv, which have no attachments.
  • ffmpeg-generated files (H.264/AAC mkv and FLAC mka), made with -attach cover.jpg -metadata:s:t mimetype=image/jpeg -metadata:s:t filename=cover.jpg plus a TrueType font attachment, a font-only mkv, a bare mkv, and a VP9/Opus webm.

Checks after each save:

  • Layout: a small EBML walker printed the SeekHead entries and confirmed each points at its element.
  • Streams: ffprobe -show_streams (attachment and attached_pic streams).
  • Font bytes: ffmpeg -dump_attachment:t "" (it only dumps the font).
  • Image bytes: ffmpeg -map 0:N -c copy -f data - for the image streams, comparing sha256 with the source images.
  • mediainfo: Attachments, Cover and Cover_Type.
  • Decode: ffmpeg -v error -i out -f null -.
  • Clusters: the sha256 of all Cluster bytes compared with the input.
File Operation Result
withcover.mkv / .mka Title only Attachments element byte-identical (sha c45e58…); clusters equal; decode clean
withcover.mkv Pictures = Pictures Attachments byte-identical; clusters equal
withcover.mkv / .mka add BackCover PNG ffprobe: cover.jpg, font.ttf, back.png; extracted bytes match the sources; font identical; mediainfo Cover_Type: Cover / Cover (back); SeekHead → Attachments after the Cues; clusters equal; decode clean
withcover.mkv replace front cover cover.jpg (new bytes, FileDescription "New front") then font.ttf in place; clusters equal; decode clean
withcover.mkv / .mka remove all pictures font.ttf only, byte-identical; clusters equal; decode clean
bare.mkv, fontonly.mkv add cover SeekHead grew into the 82/66-byte Void; ffprobe and mediainfo see cover.jpg; bytes match; clusters equal
test2.mkv add cover SeekHead size widened (110 → 127 bytes of payload); ffprobe sees cover.jpg; 47 clusters equal; decode clean
test5.mkv add cover ffprobe stream 11 = cover.jpg, bytes match; 25 clusters equal
Turning Lime.mkv same / replace / remove same: Attachments byte-identical; replace: cover.jpg after Tags, old voided, SeekHead retargeted; remove: voided with its entry dropped; clusters equal; decode clean
test1/3/6/7/8.mkv add cover refused (SeekHead has no room); file byte-identical
test4.mkv (live layout, no SeekHead) add cover refused (no SeekHead … after a Cluster); file byte-identical
bare.webm add cover refused (WebM does not support attachments); file byte-identical

The input files test4.mkv and test7.mkv already fail ffmpeg -f null with the same errors; this change does not touch them.

Additional Notes

On every save, Tags are re-rendered by the existing Tags pass. So a save of Pictures = Pictures is byte-identical only in the Attachments element, not in the whole file. That behaviour already exists for any tag save.

The Attachments element is built in a buffer sized from what is written (kept attachments plus new pictures), not from the file size. A picture save still makes two passes over the file (Attachments, then Tags), so on test2.mkv (21 MB) it allocates 196.8 MB against 156.5 MB for a tag-only save.

Working with the track enabled flag (#140)

The save runs the track flag pass first, then Attachments, then Tags, each on the previous pass's output.

  • Save_CoverAndTrackFlag_AreBothWritten (a stored and a missing FlagEnabled) checks that a save which disables a track and adds a cover writes both.
  • Save_UntouchedCoverAndTracks_IsByteIdentical checks that an unchanged save is byte-identical.
  • The env-gated Save_RealMatroska_CoverAndTrackFlag_AreBothWritten repeats the check on real files.

Real files:

  • test5.mkv and Turning Lime: both changes land. The disabled audio track has FlagEnabled 0 (independent EBML walk; ffprobe and mediainfo do not expose that flag), ffprobe and mediainfo see the new cover, Clusters are byte-identical, and decode is clean.
  • Track flag alone: byte-identical to a main b2887cd build.
  • No-op saves on 7 files: byte-identical to main's output.
  • Refused files: test1/2/3, bare and withcover refuse, because main's flag writer needs a Void after Tracks. The save is all or nothing, so they are left untouched.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.30211% with 587 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.06%. Comparing base (ebd6138) to head (3c146b0).
⚠️ Report is 29 commits behind head on main.

Files with missing lines Patch % Lines
...bSharp2.Tests/Matroska/MatroskaIntegrationTests.cs 1.58% 310 Missing ⚠️
....Tests/Matroska/MatroskaChapterIntegrationTests.cs 2.83% 103 Missing ⚠️
src/TagLibSharp2/Matroska/MatroskaRewrite.cs 86.36% 48 Missing and 36 partials ⚠️
src/TagLibSharp2/Matroska/MatroskaChapters.cs 96.01% 6 Missing and 15 partials ⚠️
src/TagLibSharp2/Matroska/MatroskaAttachments.cs 94.09% 4 Missing and 13 partials ⚠️
...ibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs 98.57% 4 Missing and 7 partials ⚠️
...rp2.Tests/Matroska/MatroskaChapterPropertyTests.cs 94.83% 4 Missing and 4 partials ⚠️
...ibSharp2.Tests/Matroska/MatroskaShiftWidthTests.cs 97.83% 2 Missing and 4 partials ⚠️
...rc/TagLibSharp2/Matroska/MatroskaRewrite.Tracks.cs 86.20% 2 Missing and 2 partials ⚠️
src/TagLibSharp2/Matroska/MatroskaTag.cs 89.74% 2 Missing and 2 partials ⚠️
... and 8 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #142      +/-   ##
==========================================
- Coverage   93.12%   93.06%   -0.06%     
==========================================
  Files         310      334      +24     
  Lines       63960    70883    +6923     
  Branches     6440     7468    +1028     
==========================================
+ Hits        59560    65967    +6407     
- Misses       2536     2911     +375     
- Partials     1864     2005     +141     

☔ 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.

Setting Pictures now rewrites the image attachments (RFC 9559 sections
5.1.6 and 21.1). An attachment that matches a picture by media type,
type, description and bytes keeps its FileName, FileUID, bytes and
place. Fonts and other attachments are copied unchanged. A new front
cover is cover.jpg or cover.png and goes first; other types get names
such as back.jpg, which read back as that type. FileUID is random,
nonzero and unique. A tag that targeted only a removed attachment is
dropped.

The rewrite places Attachments the way it places Tags: in a Void or
after the last Cluster, so Cues and cluster positions stay correct.
The SeekHead must reference a new or moved element, and it can widen
its size field to grow into the Void after it. A new entry goes only
in the first SeekHead. A save fails for a non-image picture, a WebM
file, or a cover no player could find.
TAGLIBSHARP2_TEST_MATROSKA names an .mkv or .mka file. A copy is saved
with untouched pictures and with a back cover added and then removed;
cluster bytes and every original attachment must stay the same.
The reader surfaces every image/ attachment, but the writer trimmed and
validated the media type before matching. A picture read with
FileMediaType "image/" failed the save, and one with "image/jpeg "
was rewritten under a new FileUID, which dropped the tag that targeted
it. Matching now uses the media type as stored, and only a picture
that will be written is validated.

A new front cover goes first only when no kept front cover is there,
so the file's cover.jpg stays the first attachment (RFC 9559 section
21.1). The Attachments body is sized from what is written instead of
a quarter of the file, and each picture is copied once.
Only a kept cover.* is the normal cover that RFC 9559 section 21.1
puts first. A kept small_cover, cover_land, or other image read as a
front cover no longer pushes a new cover.jpg to second place; names
are case-sensitive, so Cover.jpg is not the normal cover either.

Tests pin the empty-media-type retry, the case-insensitive media type
match, and the front-cover ordering for each kept name.
…n a refusal

Render and TryRender described a track-flag and Tags save. They also
write the Attachments element when Pictures was set, and an empty
result can mean a refused picture or track-flag save. The test helper
that reads CueClusterPosition now follows only the RFC 9559 section
5.1.5 path.
@decriptor
decriptor force-pushed the feat/matroska-cover-attachments branch from 07d9906 to f3a6078 Compare November 22, 2026 03:14
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.
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.
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 3c146b0.

This branch now also carries #149 (SeekHead fallback, position engine and track-flag shift; approved at 686041d) and #146 (chapters; approved at 8766d27). The tree is byte-identical to #149's approved head 686041d.

What was checked:

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit 88f91b7 into main Nov 22, 2026
8 checks passed
@decriptor
decriptor deleted the feat/matroska-cover-attachments branch November 22, 2026 05:36
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]: Write new Matroska cover attachments

1 participant