Skip to content

fix: Keep the APE tag as it was read through every read and save - #243

Merged
decriptor merged 5 commits into
mainfrom
fix/ape-header-and-crc-helper
Dec 4, 2026
Merged

decriptor merged 5 commits into
mainfrom
fix/ape-header-and-crc-helper

Conversation

@decriptor

Copy link
Copy Markdown
Owner

Description

A save of a Monkey's Audio, WavPack or Musepack file keeps its APEv2 tag as it was read. Every path and stream read now finds the same tag as a read from bytes. Each issue has its own commit.

Commit Change
62610b89 (#241) A path save with Lyrics3 v2 and ID3v1 after the APE tag replaces the tag instead of keeping the old one as audio. 32 of 81 lyrics lengths grew the file by the old tag's size.
d079a1c4 (#217) A save keeps the APE tag header. A save with no edit used to drop it, so sample.ape, 8bit.wv and sample.mpc each shrank by 32 bytes. The tag read from the file is written back the way it was read. A new tag, or one parsed elsewhere and assigned, gets the format's layout as before: footer-only here, and with a header in raw AAC.
64b637e1 (#218) Test only. The Matroska CRC test helper descends only into master elements, so a random UID that starts like a CRC-32 element no longer fails two save tests from time to time.
df4d8352 (#240) One rule for "has a header": bit 31 set, the header starting at or after the first byte the tag may use, and APETAGEX in front of the items. The path reads, the MPEG-PS trailer search, AAC and DFF all use it. Before this, a footer that claimed a header it did not have made a small Musepack file read no tag from a path, a Monkey's Audio file read a bitrate of 0, and MPEG-PS miss an appended ID3v2 tag.
a0d79573 (#242) A path or stream read with no tag at the end of the file no longer takes a tag from the header bytes the reader keeps.

Black box, a save with no edit (file sizes in bytes):

File Original main This branch
sample.ape 395,624 395,592 395,624
8bit.wv 1,050,683 1,050,651 1,050,683
sample.mpc 60,648 60,616 60,648
sample_v8.mpc 86,023 85,991 86,023

The header is in the original and on this branch, and missing on main. An edited save keeps it too.

Motivation and Context

A save with no edit should write the file back unchanged, and every entry point should read the same file the same way. #240, #241 and #242 are bugs in the same code that turned up while fixing #217. #242 is on main too.

Fixes #217
Fixes #218
Fixes #240
Fixes #241
Fixes #242

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)

Behaviour callers may rely on that changes:

  • ApeTag.Render () writes a parsed tag with the header it was read with. A new tag is still written footer-only. RenderWithOptions is unchanged.
  • A save of these three formats keeps a header the file had, so the file keeps its size.

No public API is added or removed.

Checklist

  • I have read the CONTRIBUTING guidelines
  • 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)
  • My changes generate no new warnings (Release build: 0 warnings)

Implementation guide (docs/IMPLEMENTATION-GUIDE.md)

  • Design note with the behaviour table: in each commit message
  • Twin table: the four carriers, AAC, DFF and MPEG-PS, with the span, path, async path and stream entry points, full and SkipPictures, each pinned by a matrix test
  • Kit run: black-box no-edit and edited saves of the sample files, and mutation checks on each fix (reverting a fix turns its rows red)
  • Pre-review: five independent review rounds. The last found nothing blocking.

Testing

At head a0d79573, a Release build of all target frameworks has 0 warnings, and dotnet format --verify-no-changes is clean.

Suite Passed Skipped Failed
net10.0 20,544 71 0
net10.0 with the sample corpus 20,557 58 0
net8.0 20,544 71 0
net8.0 with the sample corpus 20,557 58 0

… it (#241)

A path save reads the end of the file first and reads further only when what it holds asks for more. With an APEv2 tag, a Lyrics3 v2 block and ID3v1 at the end, a lyrics block 14 to 45 bytes longer than the shortest put LYRICSBEGIN in that first read with only part of the APE footer in front of it. The save stopped there, so Locate saw no footer: it kept the old tag as audio and wrote the new one after it, and the file grew by the old tag's size. A span save of the same file was right.

The read now goes back for the 32 footer bytes before LYRICSBEGIN when it holds only part of them. The new test saves through WriteFromSource with lyrics of 0 to 80 bytes, which move LYRICSBEGIN across the first read, and compares each file with what Rewrite writes; 32 of the 81 lengths failed before.
A save of a tagged Monkey's Audio, WavPack or Musepack file, even with no edit, dropped the APEv2 tag's 32-byte header and cleared the footer's "has header" flag to match: ApeTag.Render always rendered footer-only, and the three formats render through it. sample.ape, 8bit.wv and sample.mpc each shrank by 32 bytes.

An ApeTag now remembers whether it was read with a header, by the rule ApeTagLocation already used to place the tag (bit 31 set and "APETAGEX" in front of the items). The header is optional at the end of a file ("must have at least a footer", APEv2). Every carrier now saves by one rule, ApeTag.RenderForSave: the tag its read produced is written back with the layout it was read with, so a save with no edit reproduces it; any other tag, a new one or one parsed elsewhere and assigned, gets the format's layout, footer-only for the three formats and a header for raw AAC, as before. AAC had that rule on its own, by comparing tag references; its special case goes. ApeTag.Render writes a parsed tag with the header it was read with.

A skip-pictures read rebuilt the header from the flag alone, so with the header's magic damaged it read as having a header while the full read did not; it now copies those bytes as they are unless they are a header. MP3, DFF and MPEG-PS keep a trailing APE tag as raw bytes and were not affected.

ApeTagHeaderSaveTests is a matrix over the four carriers, a tag read with and without a header, nothing, ID3v1, or Lyrics3 v2 and ID3v1 after it, no edit, an edit and a replacement by a parsed tag with and without a header, and the span, path and async path saves. A save with no edit must reproduce the file; the others must keep the bytes in front of the tag and after it, and give the tag the layout above. The Lyrics3 v2 builder two AAC test files each had moves to AacTestBuilder.
Save_CoverAndTrackFlag_AreBothWritten and SaveChapters_OrderedEdition_GoesAfterInfoAndBeforeTracks failed now and then. The test helper CrcTreeMatches, which AssertEverySeekAndCue and EveryCrcMatches use, walked into every element's payload as if it held children. The saves write random 8-byte UIDs (MatroskaAttachments.NewUid, MatroskaChapters.NewUid); a UID that starts with 0xBF and a size that fits read as a CRC-32 element whose checksum did not match.

The helper now descends only into the master elements of a Segment body: RFC 9559 section 5.1, the four masters of its Appendix A that older files can carry, and EditionDisplay and ChapterTrack from the Matroska schema. A leaf such as a FileUID, EditionUID, ChapterUID or SimpleBlock is a value. The new test feeds it leaves whose value starts like a CRC-32 element; it failed before. Another has one row per master, listed apart from the set, with a broken CRC-32 inside it, so leaving a master out of the set turns its row red.
An APEv2 footer can set bit 31 ("Tag contains a header") with no header in front of its items. The span read (ApeTagLocation), the AAC tail and DFF counted a header only when the 32 bytes in front of the items start with "APETAGEX". The stream tag read of Monkey's Audio, WavPack and Musepack (ApeTagTail) and the MPEG-PS trailer search took bit 31 alone, so a path read took 32 bytes of audio as tag: a small Musepack file whose tag claimed a header that would start before the file read no tag from a path, a small Monkey's Audio file read a bitrate of 0, and an MPEG-PS file did not find an ID3v2 tag appended before such an APE tag.

ApeTagFooter now holds the one rule: CanHaveHeader (bit 31 set, and the header would start at or after the first byte the tag may use: 0, the end of the prepended ID3v2 tag in AAC and MPEG-PS, or the end of the DFF form header) and HeaderIn ("APETAGEX" at HeaderStart). ApeTagLocation.HeaderSpan applies it to bytes and to a stream; the span read, ApeTagTail, the AAC tail, both DFF trailer searches and the MPEG-PS trailer search use it. The MPEG-PS search reads the 8 bytes where a claimed header starts before it measures the tag. The first read of a path save (TagBytesStart) still takes in the 32 bytes a claimed header would use; that sizes the read, and Locate decides on those bytes.

The decision is made once, on the file's bytes, where the tail is read, and the copy carries it. A carrier parses the copy joined behind its own header bytes, so a footer that still claimed a header would have the parse look for one in those bytes: with "APETAGEX" 32 bytes before their end, the path read of a WavPack file invented a header and its no-edit save grew by 32 bytes. ApeTagTail now clears bit 31 in a copy without a header, and the skip-pictures copy sets bit 31 exactly when it rebuilds one, so the parse of a copy finds a header only when the copy starts with the file's.

The new tests read such files from a span and from a path or stream in each carrier, full and without pictures, and compare the tag, every audio property and the no-edit save; find the appended ID3v2 tag in MPEG-PS; pass over "APETAGEX" inside the prepended tag in MPEG-PS and AAC; keep the DFF sound chunk whole on a span and a path save, with and without a real header; and have both DFF searches take the same trailer when the form's size field reads "APETAGEX" where a claimed header would start. Making HeaderIn trust bit 31 alone turns them red, with four existing AAC detection tests and an APEv2 Rewrite test.
A path or stream read of Monkey's Audio, WavPack or Musepack keeps the header bytes at the front of the file, reads the APE tag at the end (ApeTagTail), and parses the two joined. With no tag at the end the tail is empty and the header bytes are parsed alone, so a footer and items at their end became the file's tag: a WavPack file whose first block ended with a footer-only tag holding Title=Phantom, then 4,096 bytes of audio and no tag, read that title from a path and nothing from bytes, and a save from the path read wrote it at the end of the file. It is on main too.

ApeTag.Parse takes a floor, the first byte the tag may use. The four stream reads that parse header bytes joined to the tail (Monkey's Audio, WavPack and RIFF-wrapped WavPack, Musepack) pass the length of the header bytes, so a tag that starts in them is not read; reads from bytes pass 0. AAC parses its tail bytes on their own, and DFF and MPEG-PS do not parse the APE tag.

ApeTagAtTheEndTests puts a whole footer-only tag at the end of the header bytes the reader keeps, in {Monkey's Audio, WavPack, Musepack} × {full, SkipPictures} × {path, async path, stream}, and compares the tag with the read from bytes and, for a full path read, the no-edit save with the save from bytes. All 18 rows failed before, here and on main. Six more read a RIFF-wrapped WavPack file whose kept window ends with a footer-only tag, "TAG" and the rest of 128 bytes, the footer-before-ID3v1 placement, in {full, SkipPictures} × {path, async path, stream}; with the floor of that read set to 0 they fail.
@codecov

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.00176% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.68%. Comparing base (33ce8eb) to head (a0d7957).

Files with missing lines Patch % Lines
...ts/TagLibSharp2.Tests/Ape/ApeTagHeaderRuleTests.cs 90.12% 0 Missing and 8 partials ⚠️
src/TagLibSharp2/Ape/ApeTagTail.cs 80.00% 1 Missing and 1 partial ⚠️
tests/TagLibSharp2.Tests/Ape/ApeCarrierFixtures.cs 97.14% 1 Missing and 1 partial ⚠️
...Sharp2.Tests/Ape/ApeFamilySaveStreamsAudioTests.cs 92.30% 1 Missing and 1 partial ⚠️
src/TagLibSharp2/Ape/ApeTagFooter.cs 66.66% 0 Missing and 1 partial ⚠️
...ests/TagLibSharp2.Tests/Ape/ApeTagAtTheEndTests.cs 96.29% 0 Missing and 1 partial ⚠️
...ts/TagLibSharp2.Tests/Ape/ApeTagHeaderSaveTests.cs 99.42% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #243      +/-   ##
==========================================
+ Coverage   93.65%   93.68%   +0.03%     
==========================================
  Files         590      594       +4     
  Lines      112493   112959     +466     
  Branches    14799    14835      +36     
==========================================
+ Hits       105358   105831     +473     
+ Misses       4221     4206      -15     
- Partials     2914     2922       +8     

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

What was checked:

  • Five review rounds. Every finding from rounds 1–4 is fixed in the commit it belongs to, with a red-first test. That includes the round-2 blocker, where a path read found a header in the joined buffer. Round 5 found nothing.
  • [Bug]: A path read of an APE, WavPack or Musepack file with no trailing tag can read a tag from the header bytes #242 came out of review: a related bug that predates the branch. It was filed and fixed here in its own commit, and its test fails on main.
  • Mutation checks: reverting each fix, or zeroing each floor argument, turns its test rows red. The one exception is the SV7 floor, which can't be reached because that read keeps only 16 bytes.
  • Black box: a save with no edit of sample.ape, 8bit.wv, sample.mpc and sample_v8.mpc keeps each file's size and its APE tag header. On main, each loses 32 bytes.
  • Gates at the head: a Release build of all target frameworks has 0 warnings, and dotnet format --verify-no-changes is clean. net10.0 and net8.0 each pass 20,544 tests (71 skipped), and 20,557 with the sample corpus (58 skipped), with 0 failures.
  • CI: build and test on Ubuntu, Windows and macOS, format, pack, the security scan and Codecov are green.

History: five commits, one per issue, so this should be rebase-merged rather than squashed.

@decriptor decriptor added the approved AI has reviewed and signed off label Dec 4, 2026
@decriptor
decriptor merged commit 28323c6 into main Dec 4, 2026
8 checks passed
@decriptor
decriptor deleted the fix/ape-header-and-crc-helper branch December 4, 2026 06:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment