Repository navigation
feat: Write Matroska pictures as image attachments - #142
Merged
Merged
Conversation
This was referenced Nov 21, 2026
decriptor
force-pushed
the
feat/matroska-cover-attachments
branch
3 times, most recently
from
November 22, 2026 02:13
0dc60cb to
07d9906
Compare
7 tasks done
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
force-pushed
the
feat/matroska-cover-attachments
branch
from
November 22, 2026 03:14
07d9906 to
f3a6078
Compare
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.
… empty added edition
…h a stored track flag
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:
|
13 of 18 tasks
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
Setting
MatroskaTag.Picturesnow writes image attachments. Before this change the save copied theAttachmentselement 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.
FileName,FileUIDand 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 asimage/orimage/jpegstill matches its own attachment), picture type, description and bytes. Only pictures that will be written are validated.tag.Pictures = tag.Pictures, copies into anotherIPicturetype, and reorders are all no-ops.cover.jpgorcover.png, chosen from its media type; another image type keeps its own extension (a GIF front cover iscover.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 (acover.*attachment, matched case-sensitively as the guidance says): that one keeps its place and the new one goes after the kept attachments. A keptsmall_cover,cover_landor other image read as a front cover is not the normal cover, so the newcover.jpgstill goes first.PictureTypegets 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 becomescover_2.jpg,other_2.jpg, and so on.FileDescription. It is left out when it is empty or equal to the name.small_cover,cover_landandsmall_cover_landread as the front cover.FileUIDcomes fromRandomNumberGenerator: nonzero, and different from everyFileUIDalready in the file (Track, Chapter and Edition UIDs are separate spaces and are not checked).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, soPicturescould never remove it.Attachmentselement. 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.TagAttachmentUIDMUST 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.Pictures(or callClear()) leaves theAttachmentselement byte for byte, as feat: Save Matroska and WebM tags #106 does today.Clear()removes every picture, soClear()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):
Clusters do not move, and Cues and SeekHead offsets are patched the same way as for Tags.
Attachmentselement 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 totest1.mkv.test2.mkvneeded this: its payload was 110 of 126 bytes.Attachmentselement is rebuilt.EbmlWriter.Sizenow writes 5 to 8 byte sizes, so a picture over 256 MB no longer gets a corrupt size.Out of scope
Positionand cue patching (fix: Update Matroska cluster positions and disc numbers #132). When attachments are inserted before a last unknown-size Cluster, the shift goes through the same plan as a Tags insert, so fix: Update Matroska cluster positions and disc numbers #132's ClusterPositionandCueCodecState/CueClusterPositionpatching applies.Save_NewAttachments_ShiftClusterPositionAndCues_LikeATagsInsertpins this: it fails with fix: Update Matroska cluster positions and disc numbers #132's cluster patching removed. The earlier note thatCluster\Positiongoes stale no longer applies.TaglibSharpSamples/matroskafiles. They refuse a new cover. Supporting them means growing the SeekHead by shifting everything after it; fix: Update Matroska cluster positions and disc numbers #132's ClusterPositionpatching is now on main, and the shift fallback is stacked in fix: Keep a moved Matroska element listed in the SeekHead and move later elements for a track flag #149. Writing an unindexed cover instead is the other option; I did not take it because players never find it.cover_land,small_coverand similar would need image dimensions. A new front cover is alwayscover.*.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
The changes in behaviour are listed under
Changedin the CHANGELOG:Picturescan now fail (non-image picture, WebM, or a cover the SeekHead cannot reference).back.jpg,artist.pngand similar names now read with their picture type instead ofOther.No public API changed; the PublicApi snapshot is unchanged.
Checklist
dotnet test)PicturesXML docs)Testing
Gates
dotnet build -c Release: 0 warnings, 0 errors on netstandard2.0, netstandard2.1, net8.0 and net10.0.dotnet test -c Release:dotnet format --verify-no-changes: clean.Unit tests are in
tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs, 49 test methods, 89 cases with data rows. They cover:PictureTyperound trip, numbered names, and name collisionsClear(), and the only attachment voidedAttachmentselements merged, and malformedAttachments(fails only when pictures change)Attachments(never throws), a 3 MB picture, and EBML size widthsMediaFilesave twinsI 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_MATROSKArunsMatroskaIntegrationTests, which saves a temporary copy with untouched pictures and with a back cover added then removed. The run passed onwithcover.mkv,withcover.mka,fontonly.mkv,bare.mkv,Turning Lime.mkv,test5.mkvandtest2.mkv. It is inconclusive (a documented refusal, with the file shown unchanged) ontest1/3/6/7/8.mkv,test4.mkvandbare.webm.Real-file verification
Inputs:
Turning Lime.mkv, which hascover.png.TaglibSharpSamples/matroska/test1..8.mkv, which have no attachments.-attach cover.jpg -metadata:s:t mimetype=image/jpeg -metadata:s:t filename=cover.jpgplus a TrueType font attachment, a font-only mkv, a bare mkv, and a VP9/Opus webm.Checks after each save:
ffprobe -show_streams(attachment and attached_pic streams).ffmpeg -dump_attachment:t ""(it only dumps the font).ffmpeg -map 0:N -c copy -f data -for the image streams, comparing sha256 with the source images.Attachments,CoverandCover_Type.ffmpeg -v error -i out -f null -.Pictures = PicturesCover_Type: Cover / Cover (back); SeekHead → Attachments after the Cues; clusters equal; decode cleanSeekHead has no room); file byte-identicalno SeekHead … after a Cluster); file byte-identicalWebM does not support attachments); file byte-identicalThe input files
test4.mkvandtest7.mkvalready failffmpeg -f nullwith 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 = Picturesis byte-identical only in theAttachmentselement, not in the whole file. That behaviour already exists for any tag save.The
Attachmentselement 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_IsByteIdenticalchecks that an unchanged save is byte-identical.Save_RealMatroska_CoverAndTrackFlag_AreBothWrittenrepeats the check on real files.Real files: