Skip to content

fix: Read MP4 gnre and keep unedited ilst atoms - #133

Merged
decriptor merged 38 commits into
mainfrom
fix/mp4-gnre
Nov 22, 2026
Merged

decriptor merged 38 commits into
mainfrom
fix/mp4-gnre

Conversation

@decriptor

@decriptor decriptor commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

MP4 genre, legacy aliases, QuickTime keyed metadata, unedited ilst atoms, and cover type codes, plus Audible .aa/.aax support (merged in from #145).

Genre reads ©gen, then gnre. gnre is a 1-based ID3v1 code: 25 is Soundtrack, 99 is Easy Listening, and 74 is Acid Punk. A setter removes each atom its getter reads, so readers that list them all (ffprobe joins them with ;) show only the new value. The aliases are gnre (Genre), ©cpy (Copyright), ©com (Composer) and ©swr (EncoderSettings) from QuickTime user data, the 3GPP names titl, albm and dscp (Title, Album, Description) as ExifTool reads them inside ilst, and ©st3 (Subtitle), which ffprobe and ExifTool both read as the subtitle. The getter reads the main atom first. ©aut, ©inf, ©des and grup are not aliases (Apple names author and information apart from artist and comment; only one reader folds the others), and they are kept. 3GPP's own titl/albm/dscp FullBoxes directly under udta are not read.

QuickTime metadata whose meta handler is mdta is read from its keys atom, in moov/udta/meta (where ffmpeg's -movflags use_metadata_tags writes it) and in moov/meta (where QuickTime and Apple devices write it). The handler and each key's namespace are checked first, as QTFF says.

  • Mapped names: Apple's com.apple.quicktime.* keys that have a property (checked against AVFoundation's full quickTimeMetadataKey list: title, displayname, artist, album, comment, composer, copyright, description, encodedby, genre, publisher, year, software, keywords, artwork); ffmpeg's names (including date, composer, album_artist, encoder, encoded_by, the sort fields, category, track and disc as n/m, and the flags); and a udta-namespace key's atom. A text key reads only UTF-8 values.
  • Every other mdta name outside com.apple.quicktime.* is a freeform field: com.apple.iTunes (org.musicbrainz for the MusicBrainz names), and another mean is written as mean:name, so SetFreeformTag/GetFreeformTag round-trip by mean and name. Such a mean reads back only if it is made of letters, digits, ., - and _ with at least one dot (such as org.example); any other mean comes back as part of the name. Unmapped com.apple.quicktime.* keys (make, model, location, creationdate) are kept as they are.
  • Every item that names a field is kept as read: keyed items, an iTunes atom a lenient writer such as mutagen added beside them, and items whose value the reader rejects (a vinyl track A1, UTF-16 text, no data, empty artwork). Which value is read: in udta/meta the iTunes atom wins (the newer edit, and what TagLib#, mutagen and AVFoundation's common title show there); in moov/meta the keyed item wins (AVFoundation ignores iTunes atoms there). An unedited save writes every item back as it was, in order. Setting the field replaces all of them with one keyed item at the field's key index, where the first one was, so no iTunes atom is written into an mdta meta. A field with no key gets one named the way the file names its keys.
  • A moov/meta with an mdta handler beside udta/meta is merged in and wins for the fields it declares (QTFF: metadata takes precedence over user data that declares the same information; AVFoundation's commonMetadata agrees). A set writes the new value to both metas, so ffprobe, ExifTool, mutagen, TagLib# and AVFoundation all show it. Assigning a tag or copying one in from another file replaces only the mapped fields, in every meta: make, model, location, creation date, any other unmapped key and unknown iTunes atoms such as orch (and a store purchase's apID/purd/cnID/stik) stay. Clear() and Tag = null remove all metadata of every meta, mapped and unmapped, keys included, and a damaged keys atom (so ffmpeg opens the result). They also remove the iTunes gapless info (iTunSMPB), so in a file without an edit list players play the encoder priming and padding, as after an ExifTool or mutagen strip. Both were checked with ExifTool and AVFoundation on udta-only, moov-only, both, udta-mdta and iTunes-moov files. Copied into an iTunes ilst, an iTunes tag brings its unknown atoms; a keyed meta takes none, and a keyed tag's key-index items stay behind. A moov/meta with any other handler (an iTunes ilst) is not QuickTime metadata and is not read; a set of a field and an assigned tag drop its copies of mapped fields (©nam, covr, ----), and Clear() and Tag = null remove it all. udta keeps its place in moov on a save, so mutagen still finds it behind a moov/meta.
  • A damaged keys atom (an entry smaller than 8 bytes or past the end, or fewer entries than its count) maps nothing and is kept as it is until the tag is cleared (Clear() or Tag = null remove it). TagLib# and mutagen do not read keyed items.

A save keeps ilst children this library does not edit, and the meta's other children (hdlr, keys, free padding) as their original bytes; free, skip and wide padding anywhere in moov is also written back unchanged. Freeform ---- atoms keep their mean and name separately, so a name that contains : survives. Every atom the tag maps is read from its payload whatever the box parser's container list says; a matrix test derives each property's atom from its setter and checks that it is read and replaced. RemovePictures() removes only the covers (it used to clear every field). Preserved children are indexed by atom type, and freeform atoms (parsed or preserved) by mean and name, so reading stays linear in the number of ilst children of any kind. A test compares the CPU cost of one large read against several small reads of the same total size for eight shapes, so a quadratic read fails it in any build; a second test does the same for assign, copy, Clear() and Tag = null.

Parsed values keep their locale indicator when written back; new and edited values use 0 (every locale). In an iTunes ilst, a save writes known atoms first, then freeform atoms, covers, and preserved children, so the order of children can change.

A parsed cover keeps its type code. A new picture is identified from its bytes as JPEG (13), PNG (14), GIF (12), or BMP (27); if the bytes are not recognized, its MIME type decides, and 0 is written only when neither identifies the image.

Audible (from #145): AudibleFile and AudibleTag read and write the .aa text dictionary, cover and duration, and save dictionary edits with the encrypted audio, DRM keys and cover copied unchanged (not checked with Audible's own apps). .aax opens as MP4, and Mp4Tag/Mp4File gain the Audible atoms (narrator, short and parent titles, product IDs, release date) as properties. See the CHANGELOG and README.

Fixes #123

@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.26264% with 193 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.25%. Comparing base (577eaaf) to head (addbb86).
⚠️ Report is 38 commits behind head on main.

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 ⚠️
src/TagLibSharp2/Mp4/Mp4Tag.cs 93.26% 13 Missing and 14 partials ⚠️
src/TagLibSharp2/Mp4/Mp4File.cs 90.35% 8 Missing and 11 partials ⚠️
src/TagLibSharp2/Mp4/Mp4QuickTimeKeys.cs 93.65% 4 Missing and 8 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 ⚠️
... and 6 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #133      +/-   ##
==========================================
+ Coverage   93.06%   93.25%   +0.18%     
==========================================
  Files         349      364      +15     
  Lines       73008    76942    +3934     
  Branches     7810     8305     +495     
==========================================
+ Hits        67948    71754    +3806     
- Misses       2980     3057      +77     
- Partials     2080     2131      +51     

☔ 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 title fix: Read an MP4 gnre atom as an ID3v1 genre name fix: Read MP4 gnre and keep unedited ilst atoms Nov 21, 2026
decriptor added a commit that referenced this pull request Nov 21, 2026
The unknown-item, gnre, ©cpy, and QuickTime keys changes now come from the branch this one is stacked on (#133), so their changelog entries belong with that code and are to be added there. This branch documents only the Audible additions.
@decriptor
decriptor force-pushed the fix/mp4-gnre branch 4 times, most recently from 1fc0795 to 3cc876b Compare November 22, 2026 03:20
@decriptor
decriptor force-pushed the fix/mp4-gnre branch 3 times, most recently from a395253 to a774696 Compare November 22, 2026 07:27
A save rebuilt ilst from known container names, so atoms such as orch
were dropped. Preserve those children verbatim. A parsed cover keeps
its type indicator when the picture bytes are unchanged, so type 0 is
not rewritten as PNG.
Dropping one preserved ilst child scanned every box and allocated a
string per comparison, so a large ilst read was quadratic. Index the
boxes by their 4-byte type and drop that type in one pass.

Freeform mean and name are stored separately, so a colon in the name
is not treated as a delimiter and survives a title-only save. An empty
preserved twin is removed when that field is set. ©cpy is an alias of
cprt: cprt wins on read, and a write keeps only cprt. A title edit
replaces a malformed ©nam instead of leaving both. New covers are
sniffed, so BMP and GIF are not written as PNG, and picture rendering
goes through CreateImage.
Each parsed freeform scanned every freeform and every preserved freeform before it, so a crafted file of distinct freeform atoms took minutes to read. Freeforms and preserved freeform twins are now looked up by (mean, name).

The read-time test now compares an 8x larger file against a small one for six ilst shapes, so it fails on a quadratic read in any build configuration.
Each guard that keeps or drops a preserved ilst child, and each index Clear resets, now has a test that fails when the guard is removed.
A new picture whose bytes are not JPEG, PNG, GIF or BMP took type 0, which ffmpeg does not show as a cover. The MIME type now decides in that case, and 0 is used only when neither identifies the image.
Parsed values, including the ©cpy alias, freeform values and covers, were rewritten with locale 0, which widens a value meant for one country or language to every reader. The parsed locale indicator is now kept; new and edited values still use 0.
Wall time swung by 6x under machine load. The test now compares one read of a 16n-child file with 16 reads of an n-child file in process CPU time, so a linear read stays near 1x and a quadratic one near 16x.
Since unedited ilst atoms are kept, an item of a meta whose handler is mdta survived beside the atom a setter writes, so ffprobe showed both values (title=T;rv-title). Title, Artist, Album, Comment, Year, Description, Publisher, Genre and Copyright now read the com.apple.quicktime key (or ffmpeg's bare name) as a fallback, and their setters drop it, as Genre already drops gnre and Copyright drops ©cpy.

Every mapped property now has a test that its setter replaces each item its getter reads.
…aliases

A meta whose handler is mdta types each ilst item by a key index (QTFF metadata item atom). Keyed items for mapped fields were kept beside the iTunes atom a setter wrote, so ffprobe showed old;new, and the iTunes atom itself is not a conforming item there.

The keys of an mdta meta are now read after checking the handler and each key's namespace. Apple's com.apple.quicktime keys, ffmpeg's use_metadata_tags names (including the sort fields, category, track, disc and flags) and the freeform names map to their properties, and udta-namespace keys to their atom. Fields are written back to their key index, new fields get a key named the way the file names its keys, and items are written in index order, so an unedited save is byte-identical. A tag in moov/meta, where QuickTime and Apple devices put it, is read and written there. A damaged keys atom (entry size below 8, past the end, or fewer entries than its count) maps nothing and is kept as it is.

Setting Title, Album, Description, Composer, EncoderSettings or Subtitle now also removes the alias readers fold into it: titl, albm, dscp (3GPP), ©com, ©swr (QuickTime user data) and ©st3, and the getters fall back to them. ©aut, ©inf, ©des and grup are not aliases and are kept.
ffmpeg writes EncodedBy and Publisher as these key names, so a set left the old keyed value beside the new one.
…is set

A file can name one field twice, for example title and com.apple.quicktime.title. The second item used to replace the first in memory, so an unedited save lost one value. The getter now reads the first, an unedited save keeps both, and setting the field leaves one.
RemovePictures cleared the whole tag; it now removes only the covers (covr, or the artwork key of an mdta meta).

A mapped atom whose code is missing from the box parser's container list was kept as opaque bytes, so its property read null. Every atom the tag maps is now read from its payload whatever that list says, and a matrix test derives each property's atom from its setter and checks that the atom is read and replaced along with a malformed twin.

An mdta text key reads only UTF-8 values, and com.apple.quicktime.displayname maps to Title.
…th metas

An mdta meta's items that name a field are now all kept as read: keyed items, an iTunes atom a lenient writer such as mutagen added beside them (which wins, as the newer edit), and items whose value the reader rejects (a vinyl track A1, UTF-16 text, no data, empty artwork). An unedited save writes every item back as it was, in order, so nothing is deleted or converted. Setting the field replaces all of them with one keyed item where the first one was.

Apple's com.apple.quicktime.composer and encodedby keys map to Composer and EncodedBy, checked against AVFoundation's full quickTimeMetadataKey list. Every other mdta name is a freeform field, and a mean other than the name's own is written as mean:name, so SetFreeformTag round-trips by mean and name.

A moov/meta beside udta/meta now supplies the fields udta/meta lacks and loses a field's items when that field is set.

The titl/albm/dscp aliases are cited as ExifTool's ilst names; 3GPP's udta FullBoxes are not read. The changelog states exactly what an unedited save and a set do.
A free padding box inside meta (mutagen writes one) is a parsed container, so a save rebuilt it from whatever its zeros parsed as and changed its bytes. hdlr, keys and padding now go back unchanged.
QTFF says that when user data and metadata declare the same information, the metadata takes precedence. A moov/meta beside udta/meta is now merged in with that precedence: its fields are read from it, an unedited save keeps both metas, and a set writes the new value to moov/meta (keyed, with a new key named the way that meta names its keys) and drops the udta/meta copy. Fields only udta/meta has are written there as before.
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.
…ding bytes

In moov/meta a keyed item now wins over an iTunes atom beside it, as in AVFoundation, which ignores iTunes atoms there; in udta/meta the iTunes atom (the newer, lenient edit) still wins. A moov/meta beside udta/meta keeps winning for the fields it declares.

free, skip and wide boxes anywhere in the file are written back as their own bytes instead of being rebuilt from what their padding parses as, which changed a byte on every save.

New tests pin three guards that had none: Clear removing the second meta's items, unmapped moov/meta items (make, location) kept beside udta/meta, and a malformed ---- in an mdta meta keeping its mean and name; plus two iTunes atoms in an mdta meta (the last wins). The changelog and SetFreeformTag's remarks state that unmapped com.apple.quicktime keys are kept opaque and which means round-trip through an mdta key.
A set of a field read from moov/meta now writes the new value to moov/meta and to udta/meta, so TagLib#, mutagen and ffprobe's title see it as well as AVFoundation and ExifTool. A tag assigned in place of the one read is written as plain values and removes moov/meta's fields (its other items stay), so a re-read shows the assigned values; a tag copied from another file carries every value it reported. A moov/meta whose handler is not mdta is not QuickTime metadata and is kept as it is: every common reader reads udta/meta there. Fixes the changelog sentence about unmapped Apple keys and the RenderMovieKeys summary.
udta was always rebuilt at the end of moov. Behind a moov/meta, mutagen (which stops at a meta it cannot parse) then saw no tag at all. The rebuilt udta now takes the old one's place.
…or set to null

Assigning a tag, copying one in from another file, Tag = null and Clear()
now replace only the fields the tag maps. The file's tag is read again,
cleared and given the assigned values, so Apple's make, model, location
and creation date, any other unmapped key and unknown iTunes atoms stay
in every meta layout. Clear() keeps those items too.

A copied iTunes tag brings its unknown atoms, replacing the target's atom
of the same type; a keyed tag's key-index items stay behind. An iTunes
moov/meta's copies of mapped fields are dropped by a set, Clear() and
Tag = null alike, so null and Clear() agree.

A matrix test covers every layout (udta only, moov only, both, udta mdta,
iTunes moov/meta) against set, assign, copy, null and Clear, and a CPU
scaling test keeps replacing the tag linear in its ilst children.
Clear() and Tag = null remove every item of every meta, mapped or not:
unknown iTunes atoms such as an iTunes Store purchase's apID, purd, cnID
and stik, and Apple's make, model, location and creation date keys with
their keys. Only an assigned or copied tag keeps the items the tag does
not map, through an internal step that clears the mapped fields alone.

Pin the rules the last change left open: an iTunes tag copied into a
keyed file brings no iTunes atom, an iTunes moov/meta's covr and ----
copies are dropped by a set of their field and by an assigned tag, and
an assigned tag drops a target's unreadable field atom.
A keys atom the tag could not read was written back unchanged after
Clear() and Tag = null, so ffmpeg still refused files whose first key
size is 0 or 4. Once the tag is cleared, no item is left that could use
it, so a save drops it, in udta/meta and in moov/meta.

The Clear remarks and the changelog now say that Clear also removes the
iTunes gapless info (iTunSMPB), so players that rely on it play the
encoder priming and padding of a file without an edit list.
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at addbb86.

This branch also carries the Audible .aa/.aax work (#145, approved at f3a6078).

What was checked:

  • Round 8 (a395253): 0 blocking findings and 2 minors. Both are fixed at a774696, verified directly:
    • Clear and Tag = null now drop a keys atom the tag could not read, so ffmpeg opens the damaged A-ks0/A-ks4 files after a clear. An unedited save, or a set without Clear, still writes it back unchanged. A mutant that never drops it turns DamagedKeys_AreRemovedByClearAndNull red.
    • The Clear remarks and CHANGELOG now say Clear also removes the iTunes gapless info (iTunSMPB), as ExifTool and mutagen strips do.
  • Rebase onto 577eaaf: CHANGELOG-only. Outside CHANGELOG, the diff from a774696 to addbb86 equals main's own delta. No main CHANGELOG line is missing, and there are no new duplicates.
  • Earlier rounds, all findings fixed and pinned:
    • The rule: Clear and null remove all metadata (unknown iTunes atoms such as the purchase account and IDs, Apple make/model/GPS/creation date and their keys). Assign and copy replace the mapped fields and keep unmapped items.
    • Matrix: 5 meta layouts × {set, assign, copy, null, clear}, checked with ffprobe, ExifTool, mutagen and AVFoundation on real files.
    • Precedence: moov/meta wins over udta/meta only for mdta metas. In moov/meta the keyed item wins; in udta/meta the iTunes atom wins.
    • Padding: free/skip/wide padding is written back as stored.
    • Detection: across 605 corpus files plus variants, only the Audible .aa rows change. .aa is Audible under every extension, and ADTS stays AAC with or without an ID3v2 prefix.
  • Gates: Release build with 0 warnings. net8.0 and net10.0: 5825 passed / 34 skipped. Format clean. Env-gated AA/AAX/MP4/Matroska/MPEG-PS runs pass. CI 8/8 green. 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 f1ecb88 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.

[Bug]: MP4 genre ignores the gnre atom

1 participant