Skip to content

fix: Keep items in read order, and make a save after a save match a fresh read - #279

Merged
decriptor merged 12 commits into
mainfrom
fix/order-and-save-state
Dec 4, 2026
Merged

decriptor merged 12 commits into
mainfrom
fix/order-and-save-state

Conversation

@decriptor

Copy link
Copy Markdown
Owner

Description

Items keep the order they were read in, a save after a save writes what a fresh read of the saved file would write, and a few API gaps are closed. Each issue has its own commit.

Commit Change
8e721d0d (#234) Picture.DetectMimeType types RIFF data as WebP only when its form type is WEBP. WAV or AVI bytes given as a picture are no longer labelled WebP.
e413fee3 (#235) WAV and AIFF get SaveToFile () back to their source, and WavFile.Tag and AviFile.Tag are public. Setting a value through the view updates every tag a reader shows, and Clear clears them all. A tag the caller holds stays the file's tag through a clear and a save, so a later edit through it is written.
47583e01 (#236) An Ogg Vorbis, Opus or FLAC file keeps a Tag after its Vorbis comment is removed. The first value set creates the comment.
3a7572f7 (#238) APE items keep the order they were read in, and new items go last. Every APE, WavPack and Musepack sample now saves byte-identical with no edit (72 corpus files changed on main). sample_v8.mpc declares 11 items but holds 8, so its item count is now written as 8.
01f85e52 (#220) AVI INFO under a declared code page (CSET) saves a non-ASCII change next to a guessed field instead of refusing it. For code pages the library does not decode, such as 932 and 1251, the original bytes are kept and the CSET is dropped. Nothing the library reads changes.
60b2e42a (#251) RIFF INFO fields keep the order they were read in, so a field added after a removal no longer takes the removed field's place.
09fd27ad (#250) New AsfFile.FileProperties, the ASF File Properties Object, so IsBroadcast is reachable without parsing the file again.
8926c6ab (#252) MP4 ilst items keep the order they were read in, and new items go last, in all three metadata layouts. Every MP4 save with no edit is now byte-identical. A read that was quadratic in a crafted order is linear.
d035cb96 (#253) An ASF save that changes the file's length writes the true File Size. A save that keeps the length keeps the field.
3eb31d1d (#257) ASF header objects keep the order they were read in, so a save with no edit is byte-identical.
db18df80 (#258) A save writes no APE tag that holds no item, whether from the same object or a fresh read.
cb3f401a (#259) Test only: pins the order of pictures set on an ID3v2 tag in every carrier. The cause was #255, fixed in #276.

All of these share one rule: a save to another path changes nothing about what the object believes its source holds. A save over the source updates that belief, checked against the bytes written.

Motivation and Context

These came from the reviews of #249 and from the new format contract tests. Each was checked against a fresh read of the saved file, and against ffprobe, exiftool and MediaInfo.

Fixes #220
Fixes #234
Fixes #235
Fixes #236
Fixes #238
Fixes #250
Fixes #251
Fixes #252
Fixes #253
Fixes #257
Fixes #258
Fixes #259

Related and still open: #195 (stacked ID3 tags, option D, v0.7.1) and #278 (an MP4 render leaves an added key in the keys meta, v0.7.1).

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Performance improvement
  • Code refactoring (no functional changes)

Public API, from the snapshot:

  • WavFile.SaveToFile () and AiffFile.SaveToFile (), with their async and file-system overloads;
  • the public WavFile.Tag and AviFile.Tag;
  • AsfFile.FileProperties.

Behaviour a caller may notice:

  • After a clear and a save, a held ID3v2 tag on WAV, AIFF or AVI becomes a new ID3v2.4 tag. Its Version reads 4.
  • SetCustomField on an INFO-only WAV or AVI returns false, as on main, because INFO holds only FOURCC names.

Checklist

  • My code follows the project's code style (dotnet format --verify-no-changes passes)
  • I have added tests that prove my fix/feature works (red first for each fix)
  • All new and existing tests pass (dotnet test): see Testing
  • I have updated documentation as needed (CHANGELOG, XML docs)
  • My changes generate no new warnings (Release build: 0 warnings)

Implementation guide

  • Twin table: every save entry point (path, async path, span, async span, in place, async in place, save elsewhere) and every sibling format, pinned by matrix tests
  • Kit run:
    • random save sequences over 74 to 381 real files against a fresh-object oracle (0 differences at the head);
    • corpus grid;
    • fuzz;
    • black-box readers;
    • mutation checks on changed lines.
  • Pre-review: five review rounds; the last found nothing

Testing

At head cb3f401a, rebased on main 7bac6b5a: a Release build of all target frameworks with 0 warnings, and dotnet format --verify-no-changes clean.

Suite Passed Skipped Failed
net10.0 33,873 80 0
net10.0 with the sample corpus 33,895 58 0
net8.0 33,873 80 0
net8.0 with the sample corpus 33,895 58 0

Cause: Picture.DetectMimeType returned image/webp for any data that
starts with "RIFF", so WAV or AVI bytes, or a mislabelled picture, were
typed as WebP, and the file extension was never consulted.

Fix: RIFF data is image/webp only when bytes 8-11 are "WEBP" (RFC 9649
section 2.4: "RIFF", the file size, then "WEBP"). Any other RIFF form,
or a header cut off before its form type, falls through to the
extension, or application/octet-stream without one. Every caller that
types a picture from its bytes takes the rule: PictureFrame and
FlacPicture FromBytes/FromFile, ApePicture, the Audible cover, and
Matroska's MediaTypeOf (a picture given no MIME type), whose save now
refuses WAV bytes as "not an image/ media type" instead of writing them
as an image/webp attachment.

Tests: PictureTests.DetectMimeType_RiffIsWebPOnlyWithTheWebPFormType
({WEBP, WAVE, AVI, webp, WEBQ, none, cut} x {no path, .webp, .jpg,
.bin}), DetectMimeType_RiffPrefix_IsWebPOnceTheFormTypeIsThere (every
prefix, no read past the end), DetectingPictures_TypeRiffByItsFormType
(ID3v2, FLAC, APE, Audible, Matroska x {WEBP, WAVE, AVI}).
PictureFrameTests.DetectMimeType_WebP now uses a real WebP header; its
six-byte "RIFF" input pinned the bug.

Red: 28 of the new cases failed on main with "image/webp".
…AV and AVI a public Tag (#235)

Cause: every other format has SaveToFile (IFileSystem?) that writes back
to SourcePath; WAV and AIFF had only SaveToFile (path) and the async
SaveToFileAsync (). WavFile's tag view was only the explicit
IMediaFile.Tag, so `wav.Tag.Title = x` did not compile on a WavFile
(Stephen's comment on the issue). AviFile had the same gap: its view
was only IMediaFile.Tag, over an internal UnifiedTag.

Fix: SaveToFile (IFileSystem? fileSystem = null) on both, the twin of
their SaveToFileAsync (): a SkipPictures read refuses, a file with no
SourcePath fails with "No source path available", and the save goes
through the file system the file was read with unless one is given.
WavFile.Tag is public (same view, same remarks). AviFile.Tag is public
too: the same view (the INFO tag, combined with the ID3v2 tag when there
is one), never null because InfoTag always exists, so typed Tag as
AsfFile.Tag and MatroskaFile.Tag are; IMediaFile.Tag returns it and the
internal UnifiedTag, which had no other caller, is folded in. The public
API snapshot gains exactly these four members.

The views had to reach every store a reader shows (review 1 N6, N7):
- A WAV file with both an ID3v2 tag and an INFO list (sample.wav) had
  the ID3v2 tag alone as its view, so a title set left the INFO title
  (MediaInfo showed the old one, ffprobe both) and Clear left the whole
  INFO list. Tag is now a CombinedTag over both, ID3v2 first, as MP3's
  is over ID3v2 and ID3v1; with only one of them it is that tag, and
  with neither the view that creates ID3v2, as before.
- After a successful save, WAV drops an ID3v2 tag or INFO list it
  emptied, and AVI and AIFF an ID3v2 tag they emptied: the save wrote
  none, a fresh read of the saved file holds none, so the next value
  set goes where that read's would (a kept emptied v2.3 tag wrote a
  v2.3 tag where a fresh read's view creates a v2.4 one). Before, a Clear and a save left the AVI
  object with an empty ID3v2 tag that stored a MusicBrainz ID the
  fresh read dropped. WAV also forgets an id3 chunk it could not parse
  once an empty tag replaced it, so a later save does not bring it back.
- On an AVI with no ID3v2 tag, a field INFO cannot hold is not stored;
  AviFile.Tag says so and how to keep one (assign Id3v2Tag), and that it
  is never null, after Dispose too, as AsfFile.Tag and MatroskaFile.Tag.
AIFF's view already covered its ID3 chunk and text chunks (ffprobe,
ExifTool and MediaInfo show the new title only); only an emptied tag
needed handling, which the review's harness found on sample.aif. A
save writes no empty tag; the object keeps the emptied instance, so a
reference the caller holds (Id3v2Tag, InfoTag) stays the file's tag
and a value set later through it is written (review 2 B1; a first
version dropped it). After a save over the source that wrote none
(SavedOverSource.HoldsFile: the source now holds, byte for byte, the
file written) the view goes on without it while it stays empty
(ViewId3, ViewInfo), as a fresh read of that file has no such tag, so
the next value set through Tag goes where that read's would; an
assignment, or a later save over the source that writes the tag,
ends that. That save also makes the kept ID3v2 tag a new one
(Id3v2Tag.ResetToNew, internal: no frame, version 4), so its next
value, through the held reference or the view, is written as a fresh
read's view-created tag is; and a view write that needs an ID3v2 tag
takes the kept instance rather than creating another, so the caller's
reference stays the file's tag (review 3 B1: a view write after a
clear-and-save replaced it, and the next edit through the held tag was
lost). A view write that empties it again hides it again rather than
dropping it. A save to
another path changes none of it: the object still describes its
source, which holds the tag (contract suite round 3, R2: a WAV
cleared, saved elsewhere, then given a custom field wrote an ID3v2 tag
where a fresh read wrote none). The fresh read in that report stores
no custom field because SetCustomField on an INFO-only WAV (and AVI)
returns false for a name that is not a FOURCC, as on main; the
contract's Edit ignores that return value.

Tests: SaveToSourceTests over every format in TaglessFixtures (19):
PublicTag_IsTheView, SaveToFile_NoPath_SavesBackToTheSourceAsTheAsyncSaveDoes
(the sync save writes the same bytes as SaveToFileAsync ()),
SaveToFile_NoPath_WritesToTheFileSystemGiven, and for WAV and AIFF
SaveToFile_NoPath_RefusesAsTheAsyncSaveDoes (not from a path, and
SkipPictures). Members are reached through dynamic, so the next format
without them fails a row rather than compiling away. MP4 is skipped in
PublicTag_IsTheView (its public Tag is the ilst, null until created, as
documented). RiffTagViewTests: Wav_SetThroughTag_WritesBothTags over
seven INFO fields, Wav_ClearThroughTag_RemovesBothTags,
SaveAfterSave_IsTheFreshReadsSave over {WAV, AVI, AIFF} x {Clear,
title, MusicBrainz ID} x {the same}, Wav_UnparsedId3ReplacedByAnEmptyTag_StaysGoneAfterTheNextSave,
Avi_FieldInfoCannotHold_IsStoredOnlyWithAnId3v2Tag,
ClearSave_ThenViewAndHeldEdits_AreBothWritten over {WAV, AVI, AIFF} x
{held edit first, view edit first} (both values on disk, the held tag
still the file's, the bytes a fresh read's with its ID3v2 tag, or a
new one assigned, standing for the held one),
ViewWriteThatEmptiesTheKeptTag_LeavesTheHeldReferenceLive (WAV, AIFF),
SaveElsewhereTwice_IsTheFreshReadsSave over {WAV with both tags, WAV
with INFO only, AVI, AIFF} x {Clear, Title = null} x {title, custom
field, MusicBrainz ID}, each saved twice to another path by the sync
and the async path save (Core/SaveElsewhere, the contract suite's C2
shape). Black box on
sample.wav: after a title set ffprobe, ExifTool (RIFF and ID3v2_3) and
MediaInfo show only the new title; after Clear none shows a tag.

Red: 9 rows failed on main with RuntimeBinderException ("No overload
for method 'SaveToFile' takes 0 arguments"; "WavFile does not contain a
definition for 'Tag'"); with the AVI row included, PublicTag_IsTheView
("avi") failed the same way ("AviFile does not contain a definition for
'Tag'"). Of RiffTagViewTests, 13 rows failed at the round-1 head, and
the two AIFF Clear rows (with a v2.3 fixture) without the AIFF drop.
Of SaveElsewhereTwice_IsTheFreshReadsSave, 15 of 24 rows failed at the
round-2 head (every row whose first edit empties a tag).
Of ClearSave_ThenViewAndHeldEdits_AreBothWritten, all 6 rows failed at
the round-3 head.

SavedOverSource.HoldsFile skips its compare when the save went to the
source's own full path on the same file system (review 3: a save over
the source compared the file with itself while a tag was empty);
another spelling is still compared (HoldsFileTests). A source another
process rewrites between the save and the compare gets the answer its
bytes give; a wrong false keeps the earlier bookkeeping, as a save
elsewhere does (noted in the code).
Cause: OggVorbisFile, OggOpusFile and OggFlacFile returned the stored
VorbisComment as Tag, so `VorbisComment = null` (Vorbis, Opus) or
RemoveVorbisComment () (Ogg FLAC) made Tag null. FlacFile, and every
other audio format since 0.7.0, keeps an empty view there.

Fix: Tag is CombinedTag.SingleOrView over the comment with a
TagCreation, the shape WavPack, Monkey's Audio, Musepack, DSF and DFF
use: the stored comment itself when there is one, else a view that
creates nothing when read, creates the comment on its first write
(NewComment, the factory EnsureVorbisComment now uses too, so the
vendor is the same either way), and drops it again when a write leaves
it empty. Ogg FLAC writes its comment block only when present, so its
Render, which every Ogg FLAC save goes through, settles the created
comment first, as FlacFile's saves do; Vorbis and Opus always write a
comment header (an empty one when none is stored), so a dropped comment
already saves as before. Tag is null after Dispose.

Tests: OggTagViewTests over {Vorbis, Opus, Ogg FLAC}: the view is empty,
of type None, creates nothing when read; the first write creates and
saves (Render and path save); write-then-clear and a created comment
emptied through VorbisComment save as no write; Tag null after Dispose;
a kept comment is the Tag. TagNeverNullTests sweeps every format in
TaglessFixtures: every settable stored-tag property set to null and
every Remove...Tag/Remove...Comment called, Tag is not null and takes a
write; only the three Ogg formats failed before the fix.

Red: 12 of 18 OggTagViewTests rows failed on main (NullReference on
file.Tag), and the sweep failed for ogg, opus and oga only.
Cause: ApeTag.RenderWithOptions sorted the items by rendered size, so a
file that stores them in another order changed on a save with no edit
(sample.ape, 8bit.wv, sample.mpc). The items lived in a Dictionary
whose enumeration order is its slot order: after a removal a new item
reused the freed slot, and OrderBy is stable, so items of equal size
came out in slot order. A save from the object that saved before and a
save from a fresh read of that save then ordered them differently (the
review finding folded into this issue).

Fix: OrderedMap<TValue> (Core), the tag's item store: a dictionary
from key to (value, place), keys compared case-insensitively for APE,
places drawn from a counter that only grows.
Set keeps the place of the item it replaces, else appends; Set with an
alias puts a value written under its key in the alias item's place;
Remove and Clear forget the place; InOrder sorts by place. Render
writes InOrder with no size sort (APEv2 only recommends sorting). Parse
uses Set, so a key read twice keeps the first place and the last value,
as the dictionary did. The Pictures setter replaces cover items in
place and removes the other "Cover Art" items (the same final set as
before), SetCustomField replaces in place instead of remove-then-add,
and SetTextList and SetOrRemove share one alias-aware helper. Lookups,
replacements and removals stay O(1); a render is O(n log n), whatever
the keys. SkipPicturesFixtures read ApeTag._items by reflection as a
Dictionary; it now reads the OrderedMap, with its own picture rule.

Tests: ApeTagItemOrderTests. NoEditRender_IsTheTagAsRead (three orders,
with and without a header); SaveAfterSave_IsTheFreshReadsSave over
{3 orders} x {13 edits} x {13 edits}: replace, remove, add, custom
field, pictures, remove-then-add; Edit_PutsItemsWhereTheRuleSays;
AliasItem_WrittenUnderItsKey_KeepsItsPlace; WriteBack_KeepsTheBytes
(title, custom field, pictures); DuplicateKey_KeepsTheFirstPlaceAndTheLastValue;
NoEditPathSave and PathSaveAfterSave for each carrier (Monkey's Audio,
WavPack, Musepack, raw AAC); EditAndRender_AllocateLinearlyInTheItemCount.
Grid over the corpus samples: the no-edit save of sample.ape,
sample.mpc, cover-art.ape, cover-art.mpc, 128kbps.wv, 256kbps.wv and
512kbps.wv is now byte-identical; sample_v8.mpc differs only in its
item count, declared 11 for 8 items, which the save writes as 8.

Red: 38 of 527 rows failed on main, each carrier's no-edit and
save-after-save rows among them.
… CSET (#220)

Cause: when a changed value did not fit the code page an AVI INFO
list's CSET declares, the list became UTF-8 under a CSET of 65001, and
RiffInfoTag.TryRenderAvi refused the save if an unchanged value's code
page was a guess: a CSET of 932, 1251 or another code page the library
does not decode, or a byte the declared code page leaves undefined
(0x81 in 1252, 0x80-0x9F under code page 0). So a value the reader
returned could not always be saved; copying a title read from a guessed
field into another field failed.

Fix, by kind of guess (review 1's recommendation, for Stephen's
review):
- A CSET of a code page this library does not decode (932, 1251, any
  other): the save drops the CSET, keeps every unchanged value's bytes
  and writes the changes by the no-CSET read rule (Windows-1252 when
  that reads back as the value, else UTF-8), as a list with no CSET is
  written. The library reads such a list by that rule already
  (InfoText.Decode under InfoCharacterSet.Other equals it under None),
  so every value reads back as it read, and the Shift-JIS or cp1251
  bytes stay for a reader that decodes the code page.
- A byte CSET 1252 or 0 leaves undefined: the list becomes UTF-8 under a
  CSET of 65001, as it already did next to text decoded exactly, and the
  guessed value is written as the UTF-8 of the text the reader returned.
  The guessed byte has no defined meaning to keep, and dropping a 1252
  or 0 CSET would change the meaning of exactly decoded text that is
  also valid UTF-8 ("é").
A list whose own CSET is 65001 keeps its guessed bytes, as before. A
changed value is never refused: TryRenderAvi is RenderAvi (out
InfoCsetWrite: keep, 65001 or drop), both AviRewrite call sites (span
rewrite and stream plan) lose their refusal branch and remove the CSET
chunks for a drop, and InfoText.GuessReason and Escape, used only by
the refusal message, are gone. AviFile.InfoTag remarks and the
[Unreleased] Added line describing the refusal are updated.

Trade-off: dropping the CSET loses the declaration. ExifTool then reads
the list as Latin-1, so a UTF-8 change shows as mojibake there
(ffprobe shows it right); before the save ExifTool and ffprobe showed
the untouched Shift-JIS field as undecoded bytes, and they still do.
The first version of this commit rewrote the guessed field as the UTF-8
of its Windows-1252 misreading under CSET 65001, which every reader
then showed as mojibake and which lost the original bytes.

Tests: AviInfoTextTests. The CSET matrix {none, 0, 28591, 932, 1252,
65001} x {ASCII, UTF-8, legacy} x {ASCII, non-ASCII change}, through a
mapped field and through the custom-field API, expects a save in every
cell: under 932 a non-ASCII change keeps the unchanged bytes and drops
the CSET; under 1252 and 0 the guessed value becomes UTF-8 under 65001.
Save_GuessedValueNextToAChangeItsCodePageCannotHold_ReadsBackAsItRead
over {1252 undefined byte, CSET 0 C1 byte, 932 Shift-JIS, 1251, 1251
holding UTF-8, undefined code page 4242} x {Render, span save, path
save, async path save}, and Save_GuessedTextCopiedToAnotherField_ReadsBackTheSame
(the issue's case, the Shift-JIS bytes kept) on each entry point. They
replace the two refusal tests, which pinned the old behaviour on
purpose.

Black box (CSET 932, IART Shift-JIS, title set to non-ASCII): the save
succeeds, ffmpeg decodes the file, the IART bytes are 93fa967b82cc89cc00
before and after, exiftool reports no CodePage after (932 before), and
ffprobe shows the new title.

Red: 36 of 141 rows failed on main with the refusal; after the switch,
26 of 141 failed against the first version.

Left as it is (review 2 nit): once the CSET is dropped, a later
non-ASCII change goes by the no-CSET rule, so Title = "Zoë" is written
as the Windows-1252 byte EB and ffprobe shows a replacement character.
That is the existing no-CSET behaviour, and the same object and a
fresh read agree.
Cause: RiffInfoTag kept its fields in a Dictionary, which enumerates in
slot order: a field added after a removal reused the freed slot, so it
was written in the removed field's place. Read a WAV with INFO
[IART, INAM, ISFT], clear Title, save over the source, set Album, save:
the object wrote [IART, IPRD, ISFT], and a fresh read of the first save
given the same edit wrote [IART, ISFT, IPRD]. The twin of #238's
equal-size finding; WAV and AVI share RiffInfoTag.

Fix: the fields live in the OrderedMap #238 added: a changed value
keeps its field's place, a new field goes last, a removal forgets the
place. Parse uses Set, so a field read twice keeps the first place and
the last value, as before. FieldIds, SameFieldsAs, RenderAvi and
RenderFields walk the fields in place order.

Sweep of the other tag stores that could write in a hash enumeration
order: see the #251 report; none of them is RIFF code, so nothing else
changes here.

Tests: RiffInfoFieldOrderTests. SaveAfterSave_IsTheFreshReadsSave over
{WAV, AVI} x {9 edits} x {9 edits} (set, remove, add, custom field add
and remove, remove-then-add), path saves over the source against a
fresh read of the saved file; Edit_PutsFieldsWhereTheRuleSays;
DuplicateField_KeepsTheFirstPlaceAndTheLastValue (a mutant that moved
a re-read field to the end survived until it was added).

Red: 18 of 166 rows failed on main (the remove-then-add cells).
Cause: AsfFile parsed the File Properties Object to build its audio
properties and dropped it, so AsfFileProperties.IsBroadcast, added in
ID, size, creation date, packet counts, durations, flags and bit rate
could be reached only by calling AsfFileProperties.Parse on the bytes.

Fix: AsfFile.FileProperties (AsfFileProperties?), read-only, set from
the object the header parse already holds; null when the header has
none. Shape and name follow the existing sub-structure properties
(Mp4File.VideoProperties, nullable when absent; the type is
AsfFileProperties, so the member is FileProperties). Every read entry
point (span, stream, path, async path, ReadFromData and the SkipPictures
reads) goes through the one header parse, so all fill it. A save copies
the object unchanged, so after a save over the source the object's
value is the saved file's. XML docs; the public API snapshot gains this
one member.

Tests: AsfFilePropertiesExposedTests. Read_ExposesTheFilePropertiesObject
over {broadcast, not} x {span, stream, path, async path, data,
skip-stream, skip-path, skip-data}: the object is there, IsBroadcast
and the fields read, and Properties.Duration is its Duration;
Read_HeaderWithoutFileProperties_IsNull on every entry point;
SaveOverSource_KeepsTheFilePropertiesOfTheSavedFile (sync and async,
the header grows) against a fresh read.

Red: the tests did not compile on main ("AsfFile does not contain a
definition for 'FileProperties'").
Cause: Mp4Tag kept its standard atoms in a Dictionary, which
enumerates in slot order, so an atom added after a removal took the
removed atom's slot; an iTunes ilst render wrote the standard atoms in
that order, then the freeform fields, the cover art and the kept atoms,
so a save grouped the items by kind. A save with no edit reordered
sample.m4a, bgo_676934.m4a, bgo_701689.m4a, sample_replaygain.m4a and
"01 Horrible Theme.m4a", and after a save over the source the same
object wrote new atoms in another order than a fresh read of the saved
file (ffmpeg m4a: clear Title and Genre, save, set Composer, Year,
Conductor, save: ©day first from the object, last from a fresh read).
The object's memory of the file also went stale after such a save, in
a keys meta and in a moov/meta beside udta/meta: slots, key indexes,
the movie meta a field lived in, the places of fields read from the
second meta, and the placement after a Clear (review 1 B2, N2).

Fix: every ilst item takes a place from one Places counter, in read
order. Standard atoms and freeform fields live in OrderedMaps sharing
it (OrderedMap gains an optional shared Places, Placed () and
TryGetValue with the place), the cover art keeps a place while it has
pictures, and each kept atom records its place (a field's earlier value
kept by KeepCurrentValue takes the field's place). The iTunes render
writes all items in place order; the keyed render appends fields
without a slot in place order. Freeform fields are now replaced in
place (they moved to the end).

After a save over the source, on every save entry point, the object
goes on as a fresh read of the saved file does: Mp4File.Adopt parses
the moov the save wrote, the tag the object holds takes that read's state
(Mp4Tag.AdoptStateOf, every field), or a new tag's when the save wrote
no ilst, and the placement follows. That tag keeps its identity
whether the file read it, the caller assigned it or a view created
it, so a reference to it stays live and a later edit through it is
written (review 2 B1: a first version replaced an assigned tag by the
one read back, and set Tag to null when no ilst was written, so
"strip, save, retag, save" lost the retag).
Whether the save went over the source is decided by #179's rule
(SavedOverSource.Holds: the file at SourcePath holds the written moov
at its offset and the written length), so a path with a "." segment or
an explicitly passed default file system counts (review 1 N1); the
other formats already decide it by content. That read-back costs one
source length read, which Mp4SaveStreamsAudioTests and
Mp4ChapterSaveStreamsTests now expect, as the MP3 tests do. Before a
save, or after a save to another path, a field cleared and set again
still goes back where it was read
(BothMetas_ClearedThenSetFieldStaysInMovieMeta keeps passing).

KeepCurrentValue finds the field it keeps by its id instead of walking
and sorting every field, so a read where a second meta overrides n
fields is linear in n in every order (review 1 B1: 16,000 overridden
freeform fields took 8.5 s and 17.7 GB).

Tests: Mp4IlstItemOrderTests. SaveAfterSave_IsTheFreshReadsSave over
{iTunes ilst with interleaved standard, cover, freeform and unknown
atoms; mdta meta; mdta moov/meta beside an iTunes udta/meta} x {12
edits} x {12 edits}; RandomSequence_EverySaveIsTheFreshReadsSave (four
layouts, a keyed moov/meta alone included, 60 seeds each, three saves
of one to three edits from 21, Clear and an assigned tag among them,
through a random one of the six saves);
RemoveSaveSetAgain_OnEverySaveEntryPoint;
SaveOverTheSource_UnderAnySpelling_IsTheFreshReadsSave (real files: a
"." segment, an explicit default file system);
RemoveSavedElsewhere_SetAgain_GoesBackWhereItWasRead;
SaveOverTheSource_KeepsTheReadTagLive; AdoptStateOf_TakesEveryField
(every instance field, by reflection, so a field added later is
caught); ClearOrAssign_PicturesSetAfterATitleGoAfterIt (pins both
_picturesPlace resets); Read_SecondMetaOverridingEveryField_AllocatesLinearly
(both orders); NoEditSave_KeepsTheItemsInTheirOrder;
Edit_PutsItemsWhereTheRuleSays; EditAndRender_AllocateLinearlyInTheItemCount.
Offline, the review's exhaustive two-step matrix (every pair of steps
of zero to two edits from 19, 145,161 sequences per layout, the six
saves in rotation): 0 differences in the iTunes, keys and two-meta
layouts (head of round 1: 0, 436 and 9,330). Grid: every MP4 sample's
no-edit save is byte-identical now (5 were not). Black box: the ffmpeg
scenario writes the same bytes from both objects; qt-artwork.mov Clear,
save, set, save is the fresh read's; a title edit of sample.m4a shows
in ffprobe, exiftool and MediaInfo, and ffmpeg decodes it.

Red: 72 of 454 rows failed on main; of the round-2 tests, 22 failed at
the round-1 head (random sequences, both scaling rows, the four
spellings).
HeldTagTests' MP4 rows (#258) and Mp4_AssignedTag_TakesALaterEdit
pin the kept identity.
…length (#253)

Cause: an ASF save rebuilds the header and copies the File Properties
Object unchanged, so a save that grew or shrank the header left File
Size, "the size, in bytes, of the entire file" (ASF Specification
01.20.03, File Properties Object), at the old length: an ffmpeg WMA of
10,332 bytes given a 4,000-character title read 10,332 at 18,314.
AsfFile.FileProperties (#250) then kept the old value too.

Fix: the header rebuild (RenderRebuiltHeader, shared by Render, the
span saves and the path save that copies from the source) writes the
File Size into every File Properties Object of the rebuilt header that
holds a whole one (AsfFileProperties.SavedFileSize). The value comes
from the object, not from the bytes the payload is copied from: a save
whose length differs from the file the object describes (the one it
read, or after a save the one it wrote) writes the length it writes; a
save that keeps that length writes the object's File Size, so a save
with no edit leaves the field as it was, even where another tagger left
it stale (both WMA files in the TagLib# test set declare a size smaller
than the file). While the Broadcast Flag is set the specification calls
the field invalid, and the bytes stay as they are. The specification
allows one File Properties Object; in a header with more the File Size
goes into the last, the one the read takes and FileProperties gives,
and the others stay as stored, so a save with no edit is byte for byte
(review 2; a first version wrote it into each, review 1 N4). After a
successful save over the source (SavedOverSource.Holds on the length
and the header written) the object describes the file it wrote: its
length, and FileProperties as that save wrote it (WithFileSize). A save
to another path, or one from an object read from bytes, leaves the
source described, as a fresh read of it given the same edits describes
it (contract suite round 3, R3: a save elsewhere then made the next one
write another File Size than a fresh read); until a save over the
source the length described is the one the read saw (SourceLength.First),
whichever bytes a span save copies. A failed save changes neither. A first version
patched only the first File Properties Object and decided from the
copied bytes, so an object read from bytes with a stale File Size
wrote the stale value back after a grow and a revert.

Sweep: the rest of the header holds nothing a length change moves. The
Header Object's size and object count are written fresh, nothing
records where the Data Object starts, and Data Packets Count and the
Play and Send Durations describe the packets, which are copied. Index
entries count packets from the Data Object, not file offsets (from the
specification as read, not re-checked). Siblings, by a growing title
save of an ffmpeg file: the WAV and AVI RIFF size, the AIFF FORM size
and the Matroska Segment size all equal the written length.

Tests: AsfFileSizeTests. Save_FileSizeIsTheLengthWritten over {grow,
shrink, no edit} x {span, async span, path, async path, no-path,
async no-path, path and async path after a stream read}: File Size is
the written length, a no-edit save is byte for byte, and FileProperties
matches a fresh read; SaveAfterSave_IsTheFreshReadsSave;
Save_FileSizeThatWasNotTheLength (broadcast, 0, larger, smaller; with
and without a length change);
GrowThenRevert_FromBytesWithAStaleFileSize_IsTheFreshReadsSave (path,
span, and span from the bytes the first save wrote; its oracle is now
the contract suite's, a fresh read of the bytes read given both edits,
where review 1 N4 took the file the first save wrote);
AsfSaveElsewhereTests over {titled, bare} x every ordered pair of
{Title = null, custom field, title, Clear}, saved twice to another
path; TwoFilePropertiesObjects_TheLastHoldsTheLengthWritten (a no-edit save
is byte for byte);
ShortFilePropertiesObject_IsNotWrittenInto (pins the whole-object
check); FailedSave_LeavesTheFileProperties (pins IsSuccess).
AsfHeaderObjectsSaveTests' CountShortOrLong_SaveCarriesEveryObject
compared the File Properties Object byte for byte; it now expects its
File Size to be the written length. Black box: sample.wma given a long
title reads File Size = length in exiftool, ffprobe and MediaInfo read
it, and ffmpeg decodes it. A no-edit save of the two corpus WMAs moved
the description objects to the end of the header (a pre-existing bug,
commit does not claim it.

Red: 37 of 92 rows (AsfFileSizeTests and AsfHeaderObjectsSaveTests)
failed on main; of the round-2 tests, 3 failed at the round-1 head. Of
AsfSaveElsewhereTests, 6 of 32 rows failed at the round-2 head (the
File Size, offset 70). AsfSaveStreamsAudioTests now count two source
length reads: the save reads the source back.

Inverted on purpose: review 1 N4's oracle took an object read from
bytes and saved to a path as describing the file it wrote; under the
contract suite's C2 that is a save elsewhere, so the object still
describes the bytes it read, and the test now says so.

Left as they are (review 2 nit): a path-read object with a stale File
Size that grows, saves elsewhere, reverts and saves over the source
writes the true length, not the stale value, because the File Size is
computed from the length written whenever it differs from the
described file's; it is the true value.
Cause: the header rebuild copied every object but the Content
Description and Extended Content Description Objects, then appended
those two rendered from the tag. A header that held them earlier
([File Properties, Header Extension, Extended Content Description,
...] in sample.wma) came out with them last, so a save with no edit
changed both WMA files in the TagLib# test set (sample.wma from
offset 4,330, "01 - I'm Yours.wma" from 6,297), with the same length.
Found by review 1 of the v0.8.0 branch (N3).

Fix: ParseHeaderStructure keeps every object, in order
(HeaderParseInfo.Objects), and RenderRebuiltHeader renders each
description object from the tag where the first of its kind was read;
a later copy of either (the specification allows one) is dropped, as
before, and one the file did not have goes after the others, as
before. The specification sets no order for header objects (ASF
Specification 01.20.03, Header Object), so the order read is kept.

Tests: AsfHeaderObjectOrderTests. NoEditSave_IsByteForByte over every
order of {File Properties, Extended Content Description, Stream
Properties, Content Description} x {Render, path save, path save after
a stream read}; Edit_KeepsEveryObjectInItsPlace over every order;
NewDescriptionObjects_GoLast; SecondDescriptionObject_IsDropped_TheFirstKeepsItsPlace.
Black box: the no-edit save of sample.wma and "01 - I'm Yours.wma" is
now byte-identical.

Red: 45 of 50 rows failed on the branch before the fix.
Cause: an APE carrier rendered its tag whenever the object held one,
so Clear on a tagged file wrote an empty 32-byte APE tag (header and
footer when the tag was read with a header). The object that saved
then still held the emptied tag, with the layout it was read with,
while a fresh read of the saved file found an empty tag, so the two
diverged: a fresh read cleared again wrote the empty footer where the
object wrote nothing (review 1, NoLegacy-cut.ape), and a value set
after the Clear went into a tag with a header from the object and a
footer-only tag from a view-created one.

Fix: ApeTag.RenderForSave (Monkey's Audio, WavPack, Musepack) and the
raw AAC plan write nothing for a tag that StoresNothing. The object
keeps the emptied tag, so a reference the caller holds stays the
file's tag and a value set later through it is written (review 2 B1;
a first version dropped the tag and lost that value with a success
result). After a successful save over the source (HoldsFile in each
carrier's Saved; AacFile's existing over-source Adopt) the file holds
no APE tag, so the kept tag is no longer the tag read: the next value
set is written footer-only, as a fresh read's view-created tag is, and
raw AAC's view goes on without it (its first write goes to the ID3v2
tag, as a fresh read's does). After a save to another path the object
still describes its source, whose tag it emptied, and keeps the read
layout (contract suite round 3, R1: the same object wrote a 128-byte
footer-only tag where a fresh read kept the source tag's header, 160
bytes).

Tests: ApeEmptyTagTests over {.ape, .wv, .mpc, .aac} x {tagless, tag
with a footer, tag with a header} x {no edit, title, Clear}: Clear and
a save leave the audio with no APE tag, and the next save is the fresh
read's; EmptyThenSaveElsewhere_TheNextSaveIsTheFreshReadsSave over
{.ape, .wv, .mpc, .aac} x {footer, header} x {Title = null, Clear} x
{title, custom field}, each saved twice to another path (sync and
async). HeldTagTests (review 2 B1, across formats): {held ApeTag on
.ape, .wv, .mpc, .aac; Mp4File.Tag; WAV Id3v2Tag and InfoTag; AIFF and
AVI Id3v2Tag; MP3 Id3v2Tag, FLAC and Ogg VorbisComment as the
reference} x {Clear, every field removed} x {save over the source,
save elsewhere}, then a title through the held tag and the same save:
the title is on disk, and the bytes are a fresh read's (of the source
given the same edits after a save elsewhere; of the saved file given
the title through its view after a save over it, where the view edits
that tag); and Mp4_AssignedTag_TakesALaterEdit.

Red: the 24 tagged rows failed on the branch before the fix; the 12
tagless rows passed. Of EmptyThenSaveElsewhere, 20 of 32 rows failed
at the round-2 head: every header row, and the AAC footer rows (AAC's
default is a header). Of HeldTagTests, 19 of 49 failed before the keep:
every save-over-the-source row but the MP3, FLAC and Ogg references,
and the assigned MP4 tag.
…259)

Review 1 saw the APIC frames of a WAV, AIFF or AAC file in a different
place from a same-object save than from a fresh read's after
Pictures = [back, front]. The cause is not the order: a picture is
written into an ID3v2.3 tag with text encoding 3 (UTF-8), which
ID3v2.3 does not define and which PictureFrame.Read rejects, so a fresh
read of the saved file has no pictures and keeps the APIC frames as
unread frames, written after the comments. That is #255, fixed on its
own branch (fix/id3v23-encoding), which also reads such frames
leniently and covers every other frame with an encoding byte. No order
fix is needed here.

Tests: Id3v2PictureOrderTests over {mp3, aac, wav, aiff, dsf, dff, mpg,
avi} x {v2.3, v2.4}: Pictures = [back with a non-Latin-1 description,
front with a Latin-1 one] reads back in that order with those
descriptions, and the next save is the fresh read's. The 8 v2.3 rows
fail until #255 is on main; the 8 v2.4 rows pass. With an APIC encoding
fix applied (Latin-1 when the description fits, else UTF-16 with BOM,
in a v2.3 tag) all 16 passed.
@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.17514% with 76 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.00%. Comparing base (7bac6b5) to head (cb3f401).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
src/TagLibSharp2/Core/SavedOverSource.cs 78.04% 5 Missing and 4 partials ⚠️
src/TagLibSharp2/Mp4/Mp4File.cs 76.31% 5 Missing and 4 partials ⚠️
src/TagLibSharp2/Mp4/Mp4Tag.cs 92.92% 3 Missing and 4 partials ⚠️
tests/TagLibSharp2.Tests/Ogg/OggTagViewTests.cs 92.40% 1 Missing and 5 partials ⚠️
tests/TagLibSharp2.Tests/Riff/RiffTagViewTests.cs 96.84% 0 Missing and 6 partials ⚠️
tests/TagLibSharp2.Tests/Asf/AsfFileSizeTests.cs 96.42% 0 Missing and 5 partials ⚠️
tests/TagLibSharp2.Tests/Core/HeldTagTests.cs 94.50% 2 Missing and 3 partials ⚠️
tests/TagLibSharp2.Tests/Core/PictureTests.cs 86.84% 1 Missing and 4 partials ⚠️
...ts/TagLibSharp2.Tests/Mp4/Mp4IlstItemOrderTests.cs 98.55% 1 Missing and 3 partials ⚠️
src/TagLibSharp2/Aiff/AiffFile.cs 91.42% 1 Missing and 2 partials ⚠️
... and 12 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #279      +/-   ##
==========================================
+ Coverage   93.94%   94.00%   +0.05%     
==========================================
  Files         643      660      +17     
  Lines      119109   120794    +1685     
  Branches    15950    16231     +281     
==========================================
+ Hits       111900   113555    +1655     
+ Misses       4160     4148      -12     
- Partials     3049     3091      +42     

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

@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at cb3f401.

What was checked:

History: 12 commits, one per issue, so this is rebase-merged rather than squashed.

@decriptor decriptor added the approved AI has reviewed and signed off label Dec 4, 2026
@decriptor
decriptor merged commit 005d065 into main Dec 4, 2026
8 checks passed
@decriptor decriptor mentioned this pull request Dec 4, 2026
4 of 9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment