Skip to content

feat: Read and write Audible .aa and .aax metadata - #145

Merged
decriptor merged 8 commits into
fix/mp4-gnrefrom
feat/audible
Nov 22, 2026
Merged

decriptor merged 8 commits into
fix/mp4-gnrefrom
feat/audible

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #133 (fix/mp4-gnre). MP4 metadata behaviour (unknown ilst items kept, gnre/©cpy aliases, QuickTime keys items) comes from #133 alone; this PR adds only what Audible .aa and .aax need on top of it. Review the diff against fix/mp4-gnre.

Description

Adds Audible audiobook support.

  • .aa: new AudibleFile / AudibleTag (MediaFormat.Audible, TagTypes.Audible). Reads the header, table of contents, text dictionary, cover chunk, and duration. Writes the dictionary.
  • .aax: it is MPEG-4 (ftyp brand aax ). It stays on the MP4 reader. .aax is now also mapped to MP4 by extension. Mp4Tag and Mp4File gain the Audible item atoms as named properties. An aavd sample entry now reports AAC.

Decryption and activation are out of scope. The audio payload, including ciphertext, is copied byte for byte.

Motivation and Context

Closes #110

Clean room and sources

No ISO or vendor specification exists for .aa. I did not read TagLib#, ffmpeg (aadec.c) or any other GPL/LGPL implementation. The layout comes from two sources:

  1. The prose description at https://wiki.multimedia.cx/index.php?title=Audible_Audio (revision of 14 May 2025). It is a wiki page of field descriptions, not code, and it says "There is no published specification". I fetched it as prose only and did not follow its links to code.
  2. Black-box analysis of the three sample .aa files (hexdump + a small Python dump script), cross-checked against ffprobe -show_format -show_streams on the same files.

For .aax atom codes, the sample cannot help: second.aax is cut at 10 KiB inside moov/trak/mdia/minf/stbl/stsz, before udta, so it has no ilst (box dump below). The codes and names come from running ExifTool as a black box (exiftool -listx -QuickTime:all, ItemList table). I then confirmed each one round-trips by writing it with TagLibSharp2 into a synthetic aax file and reading it back with exiftool and ffprobe.

.aa layout, field by field (all integers big-endian)

Offset / field Meaning Evidence
0, u32 File size, including this field Wiki. Samples: 0x002edc5f = TOC entry 0 size = end of entry 11 (0x2eb486 + 0x27d9). The samples are truncated to 10240 bytes, so the declared size is larger than the file.
4, u32 Magic 0x57907536 Identical in all three samples. Repeated at offset 4 of chunk 1.
8, u32 TOC entry count 12 in every sample. Wiki: "third 32-bit word".
12, u32 Unknown 0 in every sample. Kept as is.
16 + 12·i {u32 type, u32 offset, u32 size} Wiki. In the samples, entry i has type i, and chunks 1 to 11 are contiguous: each offset equals the previous offset + size.
type 0 Whole file (offset 0, size = file size) Wiki ("entire file"). Samples match.
type 2 Text dictionary: u32 count, then count × {u8 0x00, u32 keyLen, u32 valueLen, key, value}. No terminators. Keys are ASCII, values UTF-8. Wiki. Samples: 26 entries that end exactly at the chunk end. Each of the 26 key/value pairs matches ffprobe's TAG: lines. ffprobe hides codec, HeaderSeed, and HeaderKey, and cuts long_description at 128 chars.
type 6 Chapter/seek table. Offsets are relative to the audio. Wiki ("offset inside the chapter"). Samples: the first entries are 0, 0x415, 0x82a, …, which start at 0, so no absolute positions. Copied unchanged.
type 10 Encrypted audio Wiki. Largest chunk. Duration check below.
type 11 Cover: u32 imageLength, u32 filePosition (the next byte), image Wiki only. The samples are truncated before chunk 11. Exercised with synthetic files.
types 1, 3, 4, 5, 7, 8, 9 Opaque Copied unchanged. Chunk 3 holds the title id and the audio size and second count, not file offsets. Chunks 7 to 9 are past EOF in every sample (see risks).

Duration = chunk 10 size × 8 / bit rate, with the bit rate taken from the codec key. This matches ffprobe to the microsecond on all three files:

file codec chunk 10 bytes TagLibSharp2 ffprobe
first.aa acelp85 (8500 bit/s) 3032215 2853.849412 s 2853.849412
third.aa mp332 (32000 bit/s) 11437320 2859.330000 s 2859.330000
fourth.aa acelp16 (16000 bit/s) 6752464 3376.232000 s 3376.232000

Sample rate and channels: acelp16 is 16000 Hz mono and mp332 is 22050 Hz, both as ffprobe reports. For acelp85, ffprobe reports sample_rate=8500, which is its bit rate. I report 8000 Hz, the sampling rate of the ACELP.net 8.5 kbit/s mode. MP3 channels are reported as 0 (unknown) because they live only inside the encrypted payload. ffprobe also reports channels=0.

Design decisions

  • Write = dictionary only. Render copies everything before the dictionary, writes the new dictionary, then copies everything after it. It then patches: the header size (+Δ), TOC entry 0 size (+Δ), every TOC entry at or after the old dictionary end (offset +Δ), and the cover's absolute image position (+Δ). An entry that would be split by the shift (it starts before the dictionary and ends inside it) makes Render return empty and the save fail, instead of writing a broken file. Any 32-bit overflow does the same.
  • Unchanged save is byte-identical. Entries keep their order, their lead byte, and their raw key and value bytes. Bytes after the last entry inside the chunk are kept. A truncated file stays truncated by the same amount.
  • DRM keys are protected. SetValue throws ArgumentException for codec, HeaderSeed, HeaderKey, and EncryptedBlocks. Clear() removes only the descriptive keys (title, author, narrator, provider, price, dates, descriptions, keywords, copyright, short and parent titles). Identifiers, licensing keys, and unknown keys stay.
  • Mapping. Title→title. Artist and Author→author. Narrator, Provider, PublishDate (raw pubdate). Year is the year of pubdate; setting it keeps DD-MON-. Description→description. LongDescription, Keywords, Copyright (raw, may contain ©), ShortTitle, ParentTitle, ParentShortTitle, ProductId, TitleId, read-only Codec. Every key is reachable by name through GetValue/SetValue/Keys. Album, Comment, Genre, and Track have no key in the format: they return null and ignore a set, the same no-op as the base Tag.Pictures.
  • Cover is read-only. It is exposed as a front-cover IPicture (MIME from magic bytes). Rewriting it would change the size of the last chunk, and I have no real file with a cover chunk to check that against. The cover chunk is kept unchanged, and its position field moves with the chunk.
  • No payload in memory. Path and stream reads load only the header, TOC, dictionary (max 16 MiB), and cover (max 16 MiB); the TOC is capped at 1024 entries. A save re-reads the source like the other formats. Added to ScanWithoutAudioTests (1 MiB payload, sync and async).
  • .aax names follow ExifTool, and the AudibleTag names where they overlap: Narrator ©nrt, ShortTitle @sti, ParentTitle @pti, ParentShortTitle @PST, ParentProductId @ppi, ProductId prID, ReleaseDate rldt, ProductVersion VERS. @ is a literal 0x40. CDEK/CDET/AACR/GUID have no known meaning (ExifTool calls three of them Unknown_*). They get no property, but the ilst fix keeps them across saves.

Out of scope, and risks

  • The README, package README, CHANGELOG, AudibleFile remarks, and migration guide now carry the same caution: edited .aa files were checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps. Keep a copy, or save to a new path.

  • Decryption, activation, and checksum validation. I don't know what the 68ec733412b9 key (a 40-hex digest) or chunk 3's 40 opaque bytes cover. If Audible's own player checks a digest over the dictionary, an edited .aa could be refused by that player, even though ffprobe and ffmpeg read it. I cannot test that without the player.

  • Chunks 7 to 9 are past the end of every sample, so I cannot prove they hold no absolute file offsets. Chunk 3 (seen whole) and chunk 6 (seen in part) hold only sizes and offsets relative to the audio.

  • Writing the cover, and chapters (chunk 6 has the per-chapter sizes).

  • second.aax does not open. Its moov is cut off inside stsz, and ffprobe also rejects it ("contradictionary STSC and STCO … error reading header"). Making the MP4 reader accept a truncated moov would change MP4 behaviour in general and is not part of this issue. The env-gated .aax test reports Inconclusive for that file. It passes on a complete synthetic aax file.

Testing

Gates

  • dotnet build -c Release: 0 warnings, 0 errors (netstandard2.0, netstandard2.1, net8.0, net10.0, plus the tests, benchmarks, and examples).
  • dotnet test -c Release (on top of fix: Read MP4 gnre and keep unedited ilst atoms #133 ee9e7ec): net8.0 4867 passed, 15 skipped, 0 failed. net10.0 4867 passed, 15 skipped, 0 failed. The skips are env-gated integration tests.
  • dotnet format --verify-no-changes: clean. dotnet list package --vulnerable --include-transitive: none.
  • Every commit in the series builds Release with 0 warnings and passes dotnet test on net10.0, each checked in a detached worktree on fix: Read MP4 gnre and keep unedited ilst atoms #133's head ee9e7ec: 4842 → 4867 passed, 15 skipped, 0 failed.

Real files (taglib-sharp samples/audible/)

The env-gated tests AudibleIntegrationTests (TAGLIBSHARP2_TEST_AA, TAGLIBSHARP2_TEST_AAX) ran locally on net8.0 and net10.0 with each .aa file: 5/5 pass for first, third, and fourth.

For each .aa: read, an unchanged render, then a save that changed title (to a non-ASCII value), narrator, and year, and added custom_key.

file unchanged render vs original (cmp) Δ dictionary ffprobe on saved file TOC/header consistent bytes after dictionary ffmpeg -v error -i out -f null -
first.aa identical −6 new title, narrator, pubdate=20-JAN-2012, custom_key; duration 2853.849412 (unchanged) yes (size 3071071→3071065) identical same (empty) output as the original
third.aa identical −6 new values; duration 2859.330000 (unchanged) yes identical same output as the original (payload is encrypted and truncated, so mp3 "Header missing" appears on both)
fourth.aa identical +9 new values; duration 3376.232000 (unchanged) yes (size 6790137→6790146) identical same (empty) output as the original

A synthetic full-length .aa was built from first.aa's chunks plus a 64×64 JPEG cover in chunk 11. TagLibSharp2 reads the cover. After a save, ffprobe reads the new tags and the same duration (8.022588 s), the cover position equals the new chunk offset + 8, the image bytes and audio chunk are identical, and the header size equals the file length.

.aax: second.aax box dump: ftyp (aax , compatible aax M4B mp42 isom), then moov (487335 bytes declared, file 10240), mvhd, trak, tkhd, edts, tref/chap, mdia, mdhd, hdlr, minf, stbl, stsd (an aavd entry holding esds with object type 0x40), stts, stsc, and stsz, where it is cut off. There is no udta. A synthetic aax file (ffmpeg … -brand "aax ", sample entry renamed mp4a→aavd as in the sample) was tagged with all eight Audible properties through TagLibSharp2. ExifTool then reports Narrator, ShortTitle, ParentTitle, ParentShortTitle, ParentProductID, ProductID, ReleaseDate, and ProductVersion with the written values. ffprobe reads it as aac/aavd, the mdat payload is byte-identical, ffmpeg -v error … -f null - is clean, and TagLibSharp2 reads every value back.

Unit tests

  • AudibleFileTests: dictionary mapping; duration for each codec, including the first.aa size against ffprobe's value; cover parsing and rejection of a bad cover position or length; reading a truncated file; every prefix shorter than the dictionary end fails without throwing; wrong magic, bad TOC count, missing or overlapping dictionary, bad entry counts and lengths; 2000 random mutations never throw; path, stream, unseekable-stream, and async reads agree; detection by magic and extension; .aax→MP4; an MP4 named .aa stays MP4; dispose.
  • AudibleRoundTripTests: unchanged render is byte-identical (including invalid UTF-8 and non-ASCII keys, and bytes after the last entry); every chunk past the dictionary moves by Δ and keeps its bytes; the cover position moves; truncated-file save; a chunk that would be split, or data from another file, fails the save; Clear keeps the DRM keys; sync and async save to the source twice, to another path, from bytes, and from a stream without a path.
  • AudibleTagTests: every property round-trips under its key; the unmapped fields; Year; SetValue position and duplicates; protected and invalid keys; IsEmpty; every truncation of the dictionary; the exact rendered bytes.
  • Mp4AudibleAtomTests: exact atom codes (0x40 vs 0xA9), the Mp4File forwarders, one item after a set on a file that has it, CDEK/CDET/AACR/GUID carried through a save, the Audible atoms round-tripping through a QuickTime keyed (mdta) meta, the aax brand, and aavd→AAC.
  • MalformedInputTests and ScanWithoutAudioTests include Audible.

I reverted each guard to check that a test fails: cover-position patch, whole-file entry resize, the layout update after a save to the source, aavd, the dictionary/TOC overlap check, the DRM-key guard, Clear's key list, and magic detection. Every revert turned at least one test red.

Type of Change

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

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed (CHANGELOG Unreleased, README format list and tag table, MIGRATION-FROM-TAGLIB)
  • My changes generate no new warnings

Review round 1

finding fix pinning test(s)
F1 legacy gnre/©cpy/keyed items beside a set value moved to #133 in round 2 (it has the same fix); round-1 commits 0e394f9 and 88300f4 were dropped #133's own tests (Mp4GnreTests, Mp4PreservationTests, Mp4SetterReplacementTests); the round-1 tests were dropped with those commits
F2 save through another spelling of the source path 5d4d942: after a save, read the source's own header and TOC back and adopt them when they match what was written SaveToFile_SourceUnderAnotherSpelling_CanSaveAgain, SaveToFile_SourceUnderAnotherCase_CanSaveAgain, SaveToAnotherPath_SourceReplacedMeanwhile_NextSaveStillRefuses
F3 real-file save test vs a complete .aa with a cover 9038b73 RealAa_EditedSave_KeepsEveryOtherByte (env-gated), passes on complete files
F4 Audible-app caution in shipped docs 8294c5a —
F5 five guards unpinned 92f9f4e AudibleGuardTests
F6 package description, tags, package README, migration notes 8294c5a —

Before/after (old head 6aa1db2, new head): over 568 corpus files plus a QuickTime-keys file, 10 read answers changed, all intended. Genre now comes from gnre on 9 files, and Copyright from ©cpy on 4 of them; each genre matches ffprobe and ExifTool. The keyed title is now read on the QuickTime-keys file. Setting Genre, Copyright, and Title on all 36 MP4s now gives single values in ffprobe, where the old head gave Acid Punk;Jazz, M4A copyright;New (c), and T;rv-title. mdat is byte-identical in every save. ffmpeg decode output is the same as for the originals.

Review round 2

Review round 3

Review round 4

  • History: I folded the two code-list commits into feat: Map the Audible .aax atoms on MP4 (b97971c), so the Audible properties land together with their codes. This used git rebase -i driven by a GIT_SEQUENCE_EDITOR script that adds fixup and exec lines. The redundant ContainerBoxes line is gone, and the PR no longer touches Mp4BoxParser.cs. Every commit is green (see Gates). The head tree differs from the round-3 head only by that removed line.
  • Pins for the tag-atom entry:
    • Removing all eight codes turns 9 tests red: this PR's seven Mp4AudibleAtomTests cases (4 UnnamedAudibleItem rows, RoundTripUnderTheirExactCodes, InAQuickTimeKeyedMeta_RoundTrip, SetOnAFileThatHasIt_LeavesOneItem), plus fix: Read MP4 gnre and keep unedited ilst atoms #133's EveryProperty_IsWrittenAsAKeyedItem and EveryMappedAtom_IsReadAndReplacedWithItsTwin.
    • Removing only VERS turns 4 red: AudibleAtoms_RoundTripUnderTheirExactCodes, AudibleAtoms_InAQuickTimeKeyedMeta_RoundTrip, EveryProperty_IsWrittenAsAKeyedItem, and EveryMappedAtom_IsReadAndReplacedWithItsTwin.
  • Gates at the head:
    • 0 warnings.
    • net8.0 and net10.0 each 4844 passed, 15 skipped.
    • Format clean.
    • No merge-tree conflict with main.
    • Env-gated first, third, fourth, full and full4 .aa pass 5/5 each, and syn.aax passes.
  • Restacked onto fix: Read MP4 gnre and keep unedited ilst atoms #133's ee9e7ec, a fast-forward from eb1a4cc and 78d0591, still on main 85ce8d2. The only conflicts were in CHANGELOG.md: the Audible lines stay after fix: Read MP4 gnre and keep unedited ilst atoms #133's QuickTime-keys entry. The diff against fix: Read MP4 gnre and keep unedited ilst atoms #133 is Audible code, the Audible MP4 properties, aavd, the eight tag-atom codes, and docs. Every commit is green. The gates and env-gated tests pass as above.

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.97219% with 127 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.21%. Comparing base (d84ceb9) to head (edc1dfd).

Files with missing lines Patch % Lines
...LibSharp2.Tests/Audible/AudibleIntegrationTests.cs 7.46% 61 Missing and 1 partial ⚠️
src/TagLibSharp2/Audible/AudibleFile.cs 90.08% 20 Missing and 15 partials ⚠️
...sts/TagLibSharp2.Tests/Audible/AudibleFileTests.cs 96.74% 7 Missing and 1 partial ⚠️
...ts/TagLibSharp2.Tests/Audible/AudibleGuardTests.cs 95.48% 5 Missing and 1 partial ⚠️
...ests/TagLibSharp2.Tests/Audible/AudibleTagTests.cs 95.72% 4 Missing and 1 partial ⚠️
...agLibSharp2.Tests/Audible/AudibleRoundTripTests.cs 98.64% 0 Missing and 3 partials ⚠️
...s/TagLibSharp2.Tests/Audible/AudibleTestBuilder.cs 97.63% 2 Missing and 1 partial ⚠️
src/TagLibSharp2/Audible/AudibleTag.cs 98.69% 1 Missing and 1 partial ⚠️
...ests/TagLibSharp2.Tests/Mp4/Mp4AudibleAtomTests.cs 97.46% 0 Missing and 2 partials ⚠️
src/TagLibSharp2/Core/MediaFile.cs 90.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@               Coverage Diff                @@
##           fix/mp4-gnre     #145      +/-   ##
================================================
+ Coverage         93.17%   93.21%   +0.03%     
================================================
  Files               291      299       +8     
  Lines             58063    58888     +825     
  Branches           5566     5642      +76     
================================================
+ Hits              54102    54892     +790     
- Misses             2292     2350      +58     
+ Partials           1669     1646      -23     

☔ 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 changed the base branch from main to fix/mp4-gnre November 21, 2026 19:25
@decriptor
decriptor force-pushed the feat/audible branch 2 times, most recently from 9c8aad4 to faca4e6 Compare November 21, 2026 21:31
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at faca4e6.

The last review round (at 9c8aad4) found only two non-blocking items, and both are fixed here: the history is folded so every commit builds and passes, and the PR body is current.

What was checked:

  • Scope: the diff on fix: Read MP4 gnre and keep unedited ilst atoms #133 holds only Audible code: the .aa format, the 8 .aax atoms, and the save layout refresh.
  • .aa files: checked against public format notes. Edits keep the TOC, header sizes and cover position consistent, the audio bytes are unchanged, an unchanged save is byte-identical, and ExifTool and ffprobe read the new values. Playback in Audible's own apps can't be verified, and the README, CHANGELOG and XML docs say so.
  • .aax files: the 8 Audible atoms round-trip in iTunes ilst and in both QuickTime keyed-meta placements (udta/meta and moov/meta). ExifTool reads each one by its Audible name, and edits leave one item per code.
  • Robustness: a late cancel after the commit no longer fails a successful save, and saving under another spelling of the source path works. About 72k fuzzed inputs caused 0 exceptions, and every bound in the reader and save planner has a test that fails when the bound is reverted.
  • Builds and tests: Release build has 0 warnings; tests pass on net8.0 and net10.0 (4844 discovered, 15 env-gated skips); format and pack are clean. The env-gated .aa/.aax tests pass on 5 real files plus a synthetic .aax. Each intermediate commit was checked, including the folded b97971c.
  • Merge order: fix: Read MP4 gnre and keep unedited ilst atoms #133 → this PR. CI will run once this PR targets main.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 21, 2026
There is no published specification for .aa. The container layout follows the prose description on MultimediaWiki and was checked byte by byte on three real files and against ffprobe.

AudibleFile reads the header and table of contents, the text dictionary (AudibleTag), the cover chunk, and the duration (audio chunk size in bits over the bit rate the codec key names). A save rewrites only the dictionary: every later table-of-contents offset, the whole-file entry, the declared file size, and the cover's image position move by the change in its size, and every other byte, including the encrypted audio, is copied unchanged. An unchanged save is byte-identical. SetValue refuses the keys the player needs to decrypt the audio and Clear keeps them.

MediaFile detects .aa by the magic at offset 4 or by extension, and maps .aax to MP4.
Audible .aax files are MPEG-4 with brand 'aax '. Mp4Tag and Mp4File gain Narrator (©nrt), ShortTitle (@sti), ParentTitle (@pti), ParentShortTitle (@pst), ParentProductId (@ppi), ProductId (prID), ReleaseDate (rldt), and ProductVersion (VERS). The '@' codes are a literal 0x40. The names match what ExifTool reports for each code.

The eight codes join Mp4AtomMapping's tag atoms, so they are read from a file, replaced rather than duplicated on a set, and written through a udta-namespace key in an mdta meta. CDEK, CDET, AACR, and GUID stay unmapped and are carried through a save.

An 'aavd' sample entry, which keeps AAC in the mp4a layout with encrypted samples, now reports AAC.
…ring

A save updated the cached table of contents only when its path equalled SourcePath ordinally. A save through another spelling of the source path (dir/./x.aa, another case on a case-insensitive file system) rewrote the source but kept the old layout, so the next save failed. After a save, the source's own header and TOC are now read back. When they match what was written, that layout is adopted. A source that another writer replaced meanwhile is still refused.
Each test feeds an input that only one bound stops: a chunk or the whole-file entry moved or grown past 32 bits, a declared size that leaves 32 bits, a dictionary over the cap, a cover chunk inside the TOC, a cover position inside its own header, and a source replaced by another writer. The overflow check is now a single offset-plus-size bound; neither value can go below zero.
… test

The edited-save check compared every byte after the dictionary, so it failed on a complete .aa whose cover position correctly moved with the cover chunk. It now expects that one field to move by the size change.
The README, the package README, the CHANGELOG, the AudibleFile remarks, and the migration guide now say that edited .aa files were checked with ffprobe, ffmpeg, and ExifTool but not with Audible's own apps, which may check a digest the file stores, and advise keeping a copy. The package description and tags name Audible, the package README lists Matroska and Audible, and the migration guide notes where TagLib# maps .aa keys differently.
The read-back of the source's header ran after the atomic rename and used the caller's token, so a cancel that landed after the commit threw from SaveToFileAsync although the new file was on disk, and the stale layout made the next save fail. The read-back now ignores the token, and any failure while reading back, sync or async, only skips the refresh.
@decriptor
decriptor merged commit c13b8d4 into fix/mp4-gnre Nov 22, 2026
@decriptor
decriptor deleted the feat/audible branch November 22, 2026 01:46
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 Audible .aa and .aax metadata

1 participant