Skip to content

feat: Read and write raw AAC files - #144

Merged
decriptor merged 21 commits into
mainfrom
feat/aac
Nov 22, 2026
Merged

decriptor merged 21 commits into
mainfrom
feat/aac

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Description

Adds AacFile, which reads and writes raw AAC files (.aac): ADTS streams (MPEG-2 and MPEG-4) and ADIF streams. A file can have an ID3v2 tag in front and APEv2 or ID3v1 tags at the end.

  • Properties (AacAudioProperties): The duration is the sum over complete ADTS frames of 1024 × (number_of_raw_data_blocks_in_frame + 1), divided by the sample rate. Also reported: average bitrate (frame bytes over duration), sample rate, channels, profile (AacProfile), MPEG version (from the ID bit), frame count, and stream format (AacStreamFormat). When channel_configuration is 0, the channels come from the program_config_element at the start of the first raw data block. The CRC case is handled, including the raw_data_block_position fields. For ADIF, the profile, sample rate and channels come from the first PCE, and the duration is the payload bits divided by the header bitrate.
  • Tags: Tag is a CombinedTag over ID3v2, then APEv2, then ID3v1. A write goes to every tag the file has. EnsureId3v2Tag() adds an ID3v2 tag to an untagged file. Setting a tag property to null removes that tag on save.
  • Save: Only the tags are rewritten. The bytes from the end of the original ID3v2 tag to the start of the trailing tags are copied unchanged. A Lyrics3 block in front of ID3v1 is kept, and it is removed with ID3v1. An ID3v2 tag that cannot be read stays in the file as data.
  • Detection (MediaFile): Detection and AacFile.Read use one rule. Without a tag, offset 0 is checked; after a leading ID3v2 tag, the next 8 KB. The audio ends at the first trailing tag (APEv2, a Lyrics3 v1 or v2 block in front of ID3v1, or ID3v1) or at the end of the file, and every check is made against that audio end, so a trailing tag never changes the answer or the frame count. ADIF counts only at the first byte and only when its header parses inside the audio. An ADTS header (sync 0xFFF, layer 00) counts when the next frame header inside the audio names the same stream, and at the first byte also when its frame runs to or past the end of the audio. An MPEG audio frame header that is confirmed, or whose frame runs past the audio, ends the search as MP3, so ID3-tagged MP3, even truncated, stays MP3. A start header cut by a trailing tag is not a header. A file detected as AAC from its content always opens. After an ID3v2 tag, an MPEG program stream is checked before AAC (its PES packets may carry ADTS audio). .aac is an extension fallback. One tail locator (AacTail) places ID3v1, Lyrics3 v1/v2 and APEv2 for span detection, stream detection, both reads and the save (Render), over a span or a stream, so they always judge the same bytes and an unchanged save keeps every frame the read counted. A tag or Lyrics3 block that would start inside the leading ID3v2 tag is not a trailing tag; an APEv2 footer that ends the file decides before ID3v1, so a "TAG" inside that tag is not ID3v1. Placing an APEv2 tag walks only its item headers and keys (ApeTagItem.TryMeasure, the rules ApeTagItem.Parse shares), so detection allocates a constant whatever the tag size, and the tag is built only for a read; an APEv2 footer's "contains a header" flag counts the 32 header bytes only when they start with APETAGEX, as Render reads it. Span detection never copies the input; a plain MP3 is decided at its first frame and never parses its trailing tags.
    • The stream path checks this against the whole stream. The 32-byte peek cannot reach past a long tag or a long first frame.
    • Mp3File.IsValidFormat returns false for an ID3-prefixed AAC file.
    • The sync logic in MpegFrame.TryParse and MpegAudioProperties already rejects layer 00, so it needed no change. No existing MP3 test changed.
  • Reading cost: The start search reads 16 bytes and each successor header. It reads 4 KB chunks only while no sync has decided (padding after the tag). So detection decides an MP3 or a clean AAC file in about 23 bytes. A seekable stream reads 7 bytes per ADTS frame and skips the payload, so it runs in linear time with constant memory. The 24 KB resync buffer is allocated only on the first resync. After a header that does not parse, or that names a different stream, the reader searches forward for the next frame that the header after it confirms. Each byte is searched once.

Motivation and Context

Closes #109

Specifications

Clean room: written from these specs only. External tools were used as black boxes.

Design decisions

  • Shared APE change: ApeTagItem.Parse now runs on a non-copying Measure that holds every item rule, and ApeTagItem.TryMeasure applies the same rules from the first 264 bytes (8-byte header + a 255-byte key + NUL). ApeTagLocation.ItemsMatch (WavPack, Musepack, Monkey's Audio and ApeTag.Parse) uses it instead of Parse, so placing a tag no longer copies item values; the accepted tags are unchanged (0 changed answers across 626 WavPack/Musepack/Monkey's Audio files in review). The one error text that changed is the reserved-key error, which now names the reserved spelling ("ID3", "TAG", "OggS", "MP+") rather than the key as written. Pinned at the key-length limit by literal 254/255/256-byte rows and an AAC file with a 255-byte APE key.

  • Truncated last frame: A frame whose aac_frame_length runs past the trailing tags is not counted. The TagLib# sample.aac has 317 ADTS headers. The last one is cut short by the ID3v1 tag. We report 316 frames (7.3375 s). ffmpeg decodes 7.33 s and logs an error on that frame.

  • HE-AAC / HE-AACv2: SBR and PS are signalled inside the payload, which this reader does not decode. The headers describe the AAC core, so the reader reports the core sample rate and channels. he.aac reports 22050 Hz where ffprobe reports 44100 Hz. hev2.aac reports 1 channel where ffprobe reports 2. The duration is correct either way. The class docs describe this.

  • ADIF: ffmpeg cannot write ADIF. AacTestBuilder.Adif builds it from the §6.1 syntax: copyright id, constant or variable rate, several PCEs, comments, and LFE. For a variable-rate stream the header bitrate is the peak, so the duration is a lower bound. This is documented.

  • Detection precedence: After an ID3v2 tag, detection and AacFile.Read both search up to 8 KB for the first frame, to allow padding. The first decisive sync decides: ADTS makes the file AAC, and MPEG audio makes it MP3. Without a tag, detection looks only at offset 0, so an unrelated file is never scanned. AacFile.Read and the .aac extension fallback still search the window.

  • Read on its own: AacFile.Read fails when no ADTS frame or ADIF header is found. This covers a .aac fallback on unrelated bytes and the 0-byte corrupt/a.aac.

  • Unchanged save: An untagged file saves byte-identical, and so does ffmpeg's APE-only file. A file with an ID3v2 tag does not, because the ID3v2 tag is re-rendered (the same as Mp3File). The frame bytes are always identical. The issue does not ask for a byte-identical no-op save.

  • APEv2 layout: A tag read with a header and a footer (as ffmpeg's -write_apetag 1 writes it), and any new tag (including one assigned in place of a footer-only tag), is saved with both. mediainfo finds the APE tag in ADTS only through the header. The footer-only tag that was read keeps that layout while it is still the file's tag, which the APEv2 spec allows.

  • Reads: ReadFromFile and ReadFromFileAsync read the bytes like the other format classes. MediaFile.Read uses the stream path. Read(ReadOnlySpan) copies the span once, as Mp3File does. ReadFromData wraps an array-backed buffer without copying it.

  • Out of scope:

    • Parameter changes in the middle of the stream. A header that names a different stream is treated as junk.
    • Multiple ID3v2 tags in a row.
    • An ID3v2 tag at the end of the file.
    • Rewriting APE keys that ffmpeg writes in non-standard form. ffmpeg writes date, and ApeTag maps Year to Year. This is existing ApeTag behavior, not specific to AAC.

Real-file verification

Files: TagLib# sample.aac (same bytes as TaglibSharpSamples taglib-samples/sample.aac), corrupt/a.aac, and files generated with ffmpeg -f lavfi -i sine=... -f adts. The generated files cover mono, stereo, 4.0 (channel_configuration 0 + PCE), and 5.1; 22.05, 44.1, and 48 kHz; -write_mpeg2 1; -write_id3v2 1; -write_apetag 1; both tags together; and aac_at LC, HE-AAC (-profile:a 4), and HE-AACv2 (-profile:a 28).

File ours: rate / ch / frames / duration ffprobe nb_read_packets / rate / ch tags read after edit-save: frames ffmpeg decode
sample.aac (ID3v2.3 + ID3v1, MPEG-2) 44100 / 2 / 316 / 7.3375 s 317 (last truncated) / 44100 / 2 ID3v2 + ID3v1 identical same 1 error as the source (truncated frame)
mono44 44100 / 1 / 131 / 3.0418 s 131 / 44100 / 1 – identical clean
stereo48 48000 / 2 / 142 / 3.0293 s 142 / 48000 / 2 – identical clean
surround51 48000 / 6 / 142 142 / 48000 / 6 – identical clean
quad (chan cfg 0, PCE) 48000 / 4 / 142 142 / 48000 / 4 (mutagen: 0) – identical clean
s22 22050 / 2 / 66 66 / 22050 / 2 – identical clean
mpeg2 44100 / 2 / 131, MPEG-2 131 – identical clean
id3v2 / ape / both 44100 / 2 / 131 131 ID3v2 / APEv2 / both identical clean
at_lc 44100 / 2 / 133 133 – identical clean
he (HE-AAC) 22050 / 2 / 68 / 3.1579 s 68 / 44100 / 2 – identical clean
hev2 (HE-AACv2) 22050 / 1 / 68 68 / 44100 / 2 – identical clean
corrupt/a.aac (0 bytes) fails cleanly: "data too short" – – – –
  • Frame counts: The duration is frames × 1024 / rate and matches ffprobe's packet count. ffprobe's own duration field is a bitrate estimate.
  • Tags after save: Every file was saved with the title, artist, album, track and year changed. ffprobe, mediainfo, mutagen (mutagen.id3, mutagen.apev2) and TagLib# read the new values on every file. Before the APEv2 header fix (round 1), mediainfo read nothing from the APE-only ape.aac after a save; it now reads them. exiftool reads only the ID3v2 tag in front: it never reads APE or ID3v1 in ADTS, before or after a save.
  • Frame bytes: The bytes between the tags were compared with a separate script and match before and after the save.
  • Unchanged save: Byte-identical for every untagged file and for ape.aac.
  • MP3 regression scan: All 590 files in the TagLib# samples and TaglibSharpSamples went through MediaFile.Read(path) and MediaFile.ReadFromData. Only the three .aac files are detected as AAC. The stream and data paths agree on every file. ffmpeg MP3s with ID3v2.3, ID3v2.4 and ID3v1, and an MP2 file, are still MP3.
    • opus/malformed/psycho2.opus throws an OverflowException in the Ogg Opus reader. This happens before and after this change. It is unrelated and not fixed here.
  • Bytes read (MediaFile.Read(stream), counting stream, round 2): 60 MP3s read 1,579,710 bytes, against 1,575,091 at 23d5406 and 1,573,842 on main. The largest per-file increase is music.mp3, +4.1 KB, because its first frame does not start at the tag end. 35 AAC files read 124,328 bytes and allocate 134 KB, against 231,435 bytes and 219 KB at 23d5406. stereo48.aac reads 1,266 bytes.
  • Scaling: An 80 MB file with 200,000 frames reads in 0.69 s through a stream with flat memory, and in 0.09 s from bytes. The resync search reads candidates and their successor headers from one 24 KB buffer. A crafted 10 MB file of same-stream false syncs (each one followed by zeros) took 4.9 s through MediaFile.Read(path) before the round-1 fix and takes 0.45 s after it, about the same as a real 10 MB file. Read_FalseSyncRegion_ReadsTheStreamInChunks counts stream reads, so it fails under the per-candidate seek.
  • Integration tests (TestCategory=Integration&TestCategory=Aac): TAGLIBSHARP2_TEST_AAC=<file> takes a valid AAC file. It passes on all 38 positive inputs: every generated file except the two below, both copies of sample.aac, and the round-5 tiny_v1, tiny343_v1 and tiny_lyr2_v1 (tiny.aac with ID3v1, and with Lyrics3 v2 + ID3v1: 4 frames, 92.88 ms, as without the tags). TAGLIBSHARP2_TEST_AAC_INVALID=<file> is a negative control that must not open as AAC. It passes on 14 files: x_sfi12_m2.aac (MPEG-2 ADTS with sampling index 12) and x_sfi13.aac (reserved index 13), which ISO/IEC 13818-7 Table 35 does not define; the 0-byte corrupt/a.aac; falsempeg_gap_adts_v1 and id3_pad_oneframe_v1, which are MP3 like their copies without the ID3v1 tag (a trailing tag no longer changes the answer); and the round-5 cut-header files with Lyrics3 tails (adts3_lyr2_v1 .aac/.bin, id3_adts3_lyr1_v1, id3_adts3_lyr2_v1, id3_adts3_v1, id3_vbr25_lyr2_v1, vbr25_lyr2_v1 .aac/.bin, vbr25).

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)

MediaFormat.Aac is added at the end of the enum. An ID3-prefixed ADTS file used to be reported as Mp3 with no audio properties. It is now Aac. This change is listed under Changed in the CHANGELOG.

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
  • My changes generate no new warnings

Testing

  • dotnet build -c Release: 0 warnings, 0 errors (netstandard2.0, netstandard2.1, net8.0, net10.0)
  • dotnet test -c Release: net8.0 passed 5351, skipped 29, failed 0; net10.0 passed 5351, skipped 29, failed 0 (rebased on main 88f91b7). The skipped tests are env-gated integration tests.
  • dotnet format --verify-no-changes: clean. dotnet pack -c Release: succeeds.
  • New tests:
    • Aac/AacFileTests covers the header fields, the profile, sample-rate and channel tables, PCE with and without CRC and with multiple blocks, truncation, resync, the first-frame search window, ADIF variants, tag priority, and the I/O entry points.
    • Aac/AacFileRoundTripTests checks that frames survive every tag add, edit and removal, Lyrics3, ADIF, and the path, async and stream saves.
    • Aac/AacDetectionTests checks that span, bytes, seekable stream, forward-only stream, path, and the async twins all agree.
    • ScanWithoutAudioTests gets an AAC entry: 1 MiB of frames, header reads only. MalformedInputTests gets AAC entries, including truncation at every byte of a file with all three tags and of an ADIF file.
  • Mutation check: Each of these guards was reverted, and at least one test failed for each: the layer mask, the truncated-frame bound, the same-stream check, the ID3 → AAC branch, the stream probe, the CRC payload offset, the ID3v1 and APE audio-end bounds, the render audio end, Mp3File.IsValidFormat, and the next-header confirmation.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.62376% with 149 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.05%. Comparing base (88f91b7) to head (5bf4cbb).
⚠️ Report is 21 commits behind head on main.

Files with missing lines Patch % Lines
tests/TagLibSharp2.Tests/Aac/AacDetectionTests.cs 89.85% 12 Missing and 36 partials ⚠️
...ests/TagLibSharp2.Tests/Aac/AacIntegrationTests.cs 6.97% 40 Missing ⚠️
src/TagLibSharp2/Aac/AacStream.cs 90.75% 10 Missing and 12 partials ⚠️
src/TagLibSharp2/Aac/AacFile.cs 92.81% 3 Missing and 9 partials ⚠️
src/TagLibSharp2/Aac/AacTail.cs 92.56% 3 Missing and 6 partials ⚠️
tests/TagLibSharp2.Tests/Aac/AacFileTests.cs 98.29% 0 Missing and 5 partials ⚠️
src/TagLibSharp2/Core/MediaFile.cs 81.25% 1 Missing and 2 partials ⚠️
src/TagLibSharp2/Aac/AacBitReader.cs 93.33% 1 Missing and 1 partial ⚠️
src/TagLibSharp2/Aac/AdifHeader.cs 93.33% 1 Missing and 1 partial ⚠️
...ts/TagLibSharp2.Tests/Aac/AacFileRoundTripTests.cs 99.16% 1 Missing and 1 partial ⚠️
... and 3 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #144      +/-   ##
==========================================
- Coverage   93.06%   93.05%   -0.01%     
==========================================
  Files         334      348      +14     
  Lines       70883    72864    +1981     
  Branches     7468     7801     +333     
==========================================
+ Hits        65966    67805    +1839     
- Misses       2911     2980      +69     
- Partials     2006     2079      +73     

☔ 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
decriptor force-pushed the feat/aac branch 5 times, most recently from 49b2512 to 98ffbc3 Compare November 22, 2026 05:32
AacFile reads ADTS (ISO/IEC 13818-7 §6.2, MPEG-2 and MPEG-4) and ADIF
(§6.1) streams with an ID3v2 tag in front and APEv2 or ID3v1 tags at the
end. Duration counts 1024 samples per raw data block over every complete
ADTS frame; ADIF uses the header bitrate. Saving rewrites only the tags
and copies the frame bytes unchanged.

MediaFile detects ADIF or a confirmed ADTS sync (layer '00') at offset 0
or right after a leading ID3v2 tag. An MPEG audio frame after the tag
stays MP3. .aac is an extension fallback.
Detection and AacFile.Read now share one rule: after an ID3v2 tag the
first confirmed ADTS header in the next 8 KB starts the stream, unless an
MPEG audio frame comes first. A padded ID3-tagged AAC file is no longer
routed to MP3. A trailing ID3v1, APEv2, or Lyrics3 tag after a frame
confirms it like the end of the file does.

The resync search reads candidates and their successors from one buffer
instead of seeking once per false sync.
A tag read with a header and a footer, or a new tag, is written with
both. A tag that had only a footer keeps that layout.
… frame

An MPEG frame header that cannot be checked because its frame runs past
the data now ends the search as MP3, the same benefit of the doubt an
unconfirmable ADTS header gets. An unconfirmable ADTS header counts only
as the first sync after the tag. Truncated ID3-tagged MP3 data no longer
detects as AAC.

The stream search reads 16 bytes and each successor header, and reads
4 KB chunks only while no sync has decided, so an MP3 or a clean AAC
file is decided in about 23 bytes. The resync buffer is allocated on the
first resync.
Only the footer-only tag that was read keeps its layout. Any tag
assigned in its place is written with a header and a footer.
…ading

AacFile.Read judged the first frame against the audio region without
the trailing tags, while detection saw the whole file. A one-frame stream
confirmed by a trailing ID3v1 tag, or a gap holding a false MPEG header
whose successor lies in that tag, detected as AAC and then failed to
open. Both paths now judge the start against the whole stream and count
frames only inside the audio region.

An ADIF header is detected only when it parses, as the reader requires,
and both read it with a 256-byte first read.

Tests pin the first-byte rule for an unconfirmable ADTS header on
ID3-tagged non-MPEG data, the MPEG stop on its own, and the re-read of a
header cut by the stream chunk edge.
Detection and AacFile.Read judged the start against the whole file, so a
cut ADIF or ADTS header could take its missing bytes from a trailing
ID3v1 or APEv2 tag and open with fields parsed from it. Both paths now
reject a start whose header runs past the start of the trailing tags,
while a frame's successor may still be a trailing tag. Detection reads
the tail only for an AAC start, and only when a tag marker is present.

The prefix test also drives the stream twin of the first-byte rule. A
negative-control integration test takes TAGLIBSHARP2_TEST_AAC_INVALID.
…hout a copy

The audio region now also ends at a Lyrics3 v1 or v2 block in front of
ID3v1, found with the ApeTagLocation helpers Render already uses, so a
cut start header is not completed from the block's bytes and a last
frame cut by it is not counted.

Span detection judges the start against the audio end on the span
itself instead of copying the input, and reads the tail only when an
ADTS candidate or an undecided MPEG candidate needs it, so a plain MP3
never parses its trailing tags. ReadFromData no longer needs a stream
view.

The start is judged against the audio end only: a frame that ends at a
trailing tag is treated like one that ends at the end of the file, so a
trailing tag no longer changes the answer either way.
…eads

The span detection placed an APEv2 tag through ApeTagLocation and the
stream read through ApeTagTail, which disagreed when a footer claims a
header that is not there. AacTail now locates ID3v1, Lyrics3 v1 and v2,
and APEv2 once, over a span or a stream, and counts the 32 header bytes
only when they start with APETAGEX, as Render reads it. A property test
runs a cut x tail grid and a mutated-tag fuzz through every entry point
and asserts they agree.

The IsValidFormat and IsConfirmed docs drop the trailing-tag
confirmation that the previous change removed.
… copying items

Render placed the trailing tags with ApeTagLocation.Locate, so a tag or
Lyrics3 block reaching into the ID3v2 tag made an unchanged save drop
every frame the read counted. It now uses AacTail against the read's
audio start and keeps a Lyrics3 block from AacTail's own placement.

AacTail places an APEv2 tag by walking its item headers and keys with
ApeTagItem.TryMeasure, the rules ApeTagItem.Parse now shares, and
builds the tag only for a read, so detection allocates a constant
whatever the tag size. ApeTagLocation's item check uses the same
non-copying walk. ReadFromData locates and parses the tags on the
caller's bytes.

An APEv2 footer that ends the file now decides before ID3v1, so a
"TAG" inside that tag is not read as ID3v1 and saves stay stable.

The agreement property now also covers tags that start inside, at, and
just after the ID3v2 tag, an unchanged save, Mp3File.IsValidFormat,
and an allocation matrix over every trailing tag shape.
…ReadTail

Literal 254, 255 and 256-byte key rows for ApeTagItem.Parse and
TryMeasure, and an AAC file whose APEv2 item has a 255-byte key, fail
with the measure window one byte short. ReadTail's tag branch had no
caller left. The changelog lists the shared APE item check and the
reserved-key error text, and the AAC entries sit under Added.
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 5bf4cbb.

What was checked:

  • Round 8 (98ffbc3) found one test-gap major and two trivials. All three are fixed at 5bf4cbb, verified directly:
    • The APE item window now has literal-value rows for 254/255/256-byte keys, plus an AAC test with a 255-byte key.
    • Cutting the window by one byte turns 2 tests red (Measure_KeyLengthsAroundTheLimit(255) and Read_ApeTagWithTheLongestKey_IsATag(255)).
    • The PR body and CHANGELOG describe the shared APE item check and the reserved-key error text.
    • The unused ReadTail is gone.
    • The rebase onto 88f91b7 changed only docs context.
  • Earlier rounds:
    • All findings from rounds 1–7 are fixed and pinned.
    • Detection, span read, stream read and save share one tail locator. The 148,824-run tail matrix, the span/stream fuzz and the save grids are all at 0 disagreements and 0 lost frames.
    • Detection allocates under a fixed 96 KB bound on every tail type, including 2 MB APE and ID3v2 payloads. It peaks at 65 KB, against 4 MB before.
    • The shared APE change gives 0 changed answers across 626 WavPack/Musepack/Monkey's Audio files, and the item rules match ApeTagItem.Parse on 400k inputs.
    • Reserved sample-rate files are negative controls.
    • Integration: 38/38 positive and 14/14 negative.
  • Release build: 0 warnings on 4 TFMs. net8.0 and net10.0: 5351 passed / 29 skipped. Format clean.
  • CI 8/8 green, including codecov. GitHub reports the PR clean and mergeable.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit ecf5e3d into main Nov 22, 2026
8 checks passed
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]: Read and write raw AAC files

1 participant