Skip to content

feat: Read and write an arbitrary field on any tag - #139

Merged
decriptor merged 1 commit into
mainfrom
feat/custom-fields
Nov 22, 2026
Merged

decriptor merged 1 commit into
mainfrom
feat/custom-fields

Conversation

@decriptor

@decriptor decriptor commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

One commit on main (de3ac07), after #136, #144, #151, #133, #152, #147 and #141 merged.

Description

Adds one API on the base Tag to read, write, and remove a named field, with several values where the format allows them. A caller no longer has to cast to the concrete tag:

public virtual bool SupportsCustomFields { get; }
public virtual IReadOnlyList<string> GetCustomField (string name);
public virtual bool SetCustomField (string name, params string[] values);
public virtual bool RemoveCustomField (string name);

Each format stores the field where it keeps named fields:

Tag Storage Name matching Several values
Vorbis comment (FLAC, Ogg Vorbis/Opus/FLAC) NAME=value field case-insensitive, written upper case; ASCII 0x20–0x7D without = one field per value
APEv2 (APE, WavPack, Musepack) text item case-insensitive; 2–255 chars 0x20–0x7E, not ID3/TAG/OggS/MP+ NUL-separated in one item
ID3v2 (MP3, WAV, AIFF, DSF, DFF) TXXX, description = name case-insensitive, as GetUserText/SetUserText match NUL-separated in one frame
MP4 ---- with mean com.apple.iTunes, name = name; data type 1 (UTF-8) or 0 (implicit, read as GetFreeformTag reads it) exact one data atom per value
ASF Extended Content Description attribute (or the Content Description field for its five names) case-insensitive, as the mapped properties match first value there, the rest as file-level Metadata Library records (the layout Windows writes)
Matroska file-level SimpleTag at the item level (the level Comment and Genre use) exact one SimpleTag per value
RIFF INFO subchunk with that FOURCC four chars 0x20–0x7E, case-insensitive as GetField matches one value only
ID3v1 none: SupportsCustomFields is false, every call is a no-op

CombinedTag (MP3, raw AAC, AVI with an ID3v2 chunk, MPEG program streams), FlacTag, and the AIFF view (AiffFile.Tag) forward all four members. A combined view writes the values into every tag that can store them and removes the name from a tag that cannot (a RIFF INFO list holds one value under a four-character name), so every tag holds the new values or not the name and every reader shows the new values or nothing; when no tag can store them it returns false and changes nothing. A test holds every concrete Tag type that is not a listed leaf of the shared TagTypeClassification (from #136) to the four members, so a view of any shape is checked; it flags all eleven of #136's dummy view shapes. CombinedTag and FlacTag read the first tag that holds the name and write every tag that supports custom fields, as the property setters already do. ID3v1 is left as it is.

Motivation and Context

TagLib# 2.3 offers GetField/SetField/RemoveField on concrete tags. Here each format had its own method, and ASF and Matroska had no public way to reach an unmapped name.

Closes #112

Naming

GetField/SetField are taken: RiffInfoTag.GetField(string fourCC) returns string?, and an inherited GetField returning a list would collide with it. GetValue/SetValue are taken on VorbisComment and ApeTag with single-value semantics. *CustomField reads naturally beside SetUserTextFrame, SetFreeformTag, and GetValues, and says what it holds: a field the mapped properties do not name.

Design decisions

  • Return values, not exceptions. SetCustomField returns false and leaves the tag unchanged (tested by comparing rendered bytes) when the format cannot store the name or the values. The only exception is ArgumentNullException for a null name.
  • Null and empty values are skipped. When no values remain, the field is removed. A value containing U+0000 is refused in every format, because ID3v2 and APE use it to separate values and RIFF INFO uses it to end a string.
  • Names a mapped property uses are stored natively, not refused. The custom field writes where the property reads, so it never makes a duplicate. A property that reads more than that one place can still show something else: on Matroska the name is written at the item level, which is the album level (50) on a file with only album tags, so TITLE there sets Album, and Title prefers the segment title (documented and tested). Tests cover Vorbis TITLE, APE Title, ID3 TXXX:REPLAYGAIN_TRACK_GAIN, MP4 CONDUCTOR, ASF WM/AlbumTitle and WM/TrackNumber (DWORD read as decimal), Matroska COMMENT, and RIFF INAM. On ID3v2 a name is always a TXXX description: "TITLE" never touches TIT2. On MP4 it is always a freeform atom: it never touches ©nam.
  • ASF Content Description names. Title, Author, Copyright, Description, and Rating are the Content Description Object's fields (§3.10). The Windows Media Format SDK exposes them under those attribute names, so they route there instead of creating a shadow attribute. The first value goes there and the others to the Metadata Library Object, as Windows stores a multi-valued Author.
  • Picture storage names are refused: Vorbis METADATA_BLOCK_PICTURE, APE Cover Art*, and ASF WM/Picture. Use Pictures for those. Without this, Vorbis rendering would silently drop the field, because it regenerates METADATA_BLOCK_PICTURE from the picture list.
  • ID3v2.3. A v2.4 tag writes UTF-8. A v2.3 or older tag writes UTF-16 with a BOM, because v2.3 §3.3 defines only ISO-8859-1 and UCS-2 (the library's other setters write UTF-8 even in v2.3; I did not change those here). v2.3 has no multi-value text, so values are still NUL-separated, each with its own BOM (§3.3: "Unicode strings must begin with the Unicode BOM"). mutagen reads both values; ffprobe, exiftool, and mediainfo show the first. On read, every UTF-16 string's own BOM is skipped (mutagen's default layout) by one shared splitter used by text frames, TXXX, and TIPL/TMCL/IPLS; it is the decoder fix: Drop a terminating NUL from ID3 text #136's DecodeUtf16BomText calls too, so it keeps fix: Drop a terminating NUL from ID3 text #136's rules: a lone last byte is dropped, the 00 00 pairs after the last string are terminators rather than an empty value, and a string without a BOM uses the frame's first BOM. In TIPL/TMCL/IPLS a lone byte right after a terminator still starts an empty last string, so the role before it keeps an empty person, as fix: Drop a terminating NUL from ID3 text #136 reads it. For text frames and TXXX, one code path serves every target framework and decodes into pooled buffers, so a read allocates no more than base on netstandard2.0, netstandard2.1, net8.0 and net10.0 (measured: 64/72/136/72/2464 B for the reviewer's five frames on each). The TIPL/TMCL/IPLS splitter decodes each string with Encoding.GetString, which on netstandard2.0 copies the span first, as base does. A frame read from a file records where its BOMs were (one BOM, one per non-empty string, or one per string including empty ones) and how many terminators ended it, and renders back with both, so an empty last value and the terminators survive an unchanged save. A string whose text starts with U+FEFF or U+FFFE always gets its own BOM, so a reread keeps that char. A frame built in code keeps one BOM, as before; only a TXXX that SetCustomField writes in v2.3 gets a BOM per value.
  • ID3 description matching is case-insensitive, the same rule as GetUserText/SetUserText and the mapped properties. With two rules on one frame type, SetCustomField("foo") beside SetUserText("FOO") would write a second TXXX. With one rule, a frame written by either API is found, replaced, and removed by the other, and no duplicate is created; a test pins this. When a frame is replaced it takes the caller's spelling. The spec allows one TXXX per description and does not say whether case matters, so folding case also keeps one frame per name when other tools wrote it in a different case.
  • MP4 has no mean:name syntax. The name is always under com.apple.iTunes, so a name may contain : ("a:b" is a name). For other means, Mp4File.GetFreeformTag/SetFreeformTag remain.
  • ASF Metadata Library. The Metadata Object and Metadata Library Object (§4.7, §4.8, inside the Header Extension Object §3.4) are now read. GetCustomField returns their file-level records for the name (any language), and so do Performers (Author), AlbumArtists, Composers, and Genres, which now read every value and write values 2..n back to the library. SetCustomField, RemoveCustomField, a mapped setter given a new value, and Clear drop the old library values, so a removed field is gone from the file. The ASF setters use fix: Drop a terminating NUL from ID3 text #136's Tag.IsWriteBack, with no second rule: writing back the exact value a property read is a no-op, so a read-modify-write keeps every value (a matrix over all 77 AsfTag properties on a synthesized WMA pins it, a local run over 16 real WMA files agrees, and a layout matrix over every number property and IsCompilation, with values in the Extended Content Description, the Metadata Object, and the Metadata Library, pins write-back, clear, and replace on each); null always clears, a stored value the getter cannot read included (the DWORD year mutagen writes, a WORD track, a DWORD WM/IsCompilation), so Year = null removes it as base did, and IsCompilation = false clears a true stored in any object; and CopyTo always replaces, so a copy into ASF drops the target's Metadata Library values. "" is the value read only when no value of the attribute holds text. The R128 dB setters follow the same rule. A title, artist, copyright, comment, or rating write (mapped property or custom field) also replaces the same-named Extended Content Description descriptor ffmpeg writes beside the Content Description field, so mutagen and ffprobe stop showing the old value (an ffmpeg WMA's Artist = "V2" left mutagen reading Author ['V2', 'old'] and ffprobe artist=old); a non-empty field hides that descriptor on read and an empty one reads it. Records about one stream are kept. The Header Extension Object is rebuilt only when its records change, so other saves keep its bytes. If either object cannot be parsed (truncated, duplicated, or behind a child that runs off the end), custom writes return false instead of leaving values behind.
  • ASF single-value getters (string, number, and IsCompilation) return the first non-empty value of the attribute, from the Content Description or Extended Content Description and then the Metadata and Metadata Library Objects, the rule fix: Drop a terminating NUL from ID3 text #136 gives the ID3v2, APE, and Vorbis Comment getters. An attribute mutagen wrote as ['', 'A2'] reads A2, and writing A2 back keeps both values; mutagen's WM/TrackNumber = ['', '7'] reads Track = 7, and Track = Track keeps both.
  • Matroska RemoveCustomField removes the name at every file level the getter can climb to, so a broader value does not show through afterwards. SetCustomField writes at the item level and shadows broader levels, as the format defines. Chapter, track, edition, and attachment targets are never read or changed.
  • FlacTag creates a VORBIS_COMMENT block only when a field is actually stored, so a refused name does not add an empty block.

Bugs fixed along the way (the same save paths)

  • A WAV or AIFF ID3 chunk that holds only a TXXX (or any frame outside the seven base fields) is written on save. Main (fix: Return an AIFF annotation as the comment #135) made Id3v2Tag.IsEmpty false for any frame, which is the gate WAV and AIFF use, so this PR no longer adds its own gate: IsEmpty now reads FrameLists, the same array Clear reads, so a frame list added later counts without a second edit. A test over every frame kind writes a WAV and an AIFF holding only that frame.
  • MP4 (fix: Read MP4 gnre and keep unedited ilst atoms #133 keys freeform fields by mean and name, so a colon in either round-trips; tests pin it). The custom-field members use that model, so a field goes where the freeform properties go: a keyed item in a QuickTime mdta meta, a ---- atom in an iTunes ilst. A remove drops every item the name was read from (in an mdta meta its keys entry stays, as for any field a set removes there), Clear removes them all, and a copy from another tag keeps them. A custom field and a chapter list set before one save both survive, with the tag in udta/meta or moov/meta (feat: Read and write MP4 chapters #147).
  • AVI INFO (feat: Read and write AVI metadata #141) custom fields take any text and are saved under the file's CSET rules: an untouched value keeps its bytes, a declared code page is kept when the value fits, and otherwise the list becomes UTF-8 under CSET 65001. WAV INFO stays Latin-1 (text outside it is refused).
  • APEv2 key rules are one function shared by item parsing, main's non-copying item measure (feat: Read and write raw AAC files #144), the Create methods and SetCustomField, so a field SetCustomField accepts renders as an item the tag placement accepts.
  • Clear removes custom fields in every format (docs/IMPLEMENTATION-GUIDE.md rule 7), pinned for each.
  • Id3v2Tag.Clear and IsEmpty read one array of the fifteen frame lists, pinned by a test over every frame kind.

Out of scope

  • Tag.CopyTo does not copy custom fields. That needs name enumeration, which this issue does not ask for.
  • No enumeration API (list every custom name).
  • A first ASF value over 64 KB is refused (the Extended Content Description's 16-bit lengths); values 2..n have no such limit. Pictures still ignores WM/Picture records in the Metadata Library.

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)

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

Spec references

Testing

Gates (local, macOS):

  • dotnet build -c Release: 0 warnings, 0 errors (netstandard2.0, netstandard2.1, net8.0, net10.0)
  • dotnet test -c Release on main de3ac07 plus this commit: net8.0 7066 passed, 55 skipped; net10.0 7066 passed, 55 skipped. The skips are env-gated real-file tests; with the env vars set to real samples, 7112 pass and 9 skip (samples I do not have: MPEG video, foobar2000 MP4, invalid AAC, a complete AAX, and two kit depth cases).
  • dotnet format --verify-no-changes: clean
  • PublicApi snapshot updated (only the four new members on Tag and its overrides)

Unit tests:

  • Core/CustomFieldTests.cs: a matrix over Vorbis, APE, ID3v2.4, ID3v2.3, MP4, ASF, Matroska, and RIFF INFO. Each case checks:

    • several values, and one value, read back after render and parse;
    • set replaces earlier values;
    • null and empty values are skipped, and no values removes the field;
    • a value with NUL, an empty name, or a name with NUL is refused and the rendered bytes are unchanged;
    • remove returns true and then false;
    • a null name throws;
    • other fields are untouched.

    Per-format name rules, picture names, and collisions with mapped properties are tested separately, as are ID3v1, CombinedTag, and FlacTag. A TXXX written by SetUserText("FOO") is found, replaced, and removed through GetCustomField/SetCustomField/RemoveCustomField in other cases, and the tag never holds two frames; that test goes red with ordinal matching.

  • Core/CustomFieldFileRoundTripTests.cs: a custom field set through IMediaFile.Tag survives render and reopen for FLAC, MP3 (ID3v2.4 and ID3v2.3), Ogg Vorbis, Opus, Ogg FLAC, Monkey's Audio, WavPack, Musepack, MP4, ASF, WAV (ID3 and INFO), AIFF, DSF, DFF, and raw AAC (ID3v2 and APEv2). Each container also has a remove-then-reopen test. An ID3 tag holding only a custom field survives in WAV, AIFF, DSF, and DFF; this goes red for WAV and AIFF with the old gate. A FLAC file with a custom field re-saves byte-identically.

  • Matroska/MatroskaCustomFieldTests.cs: item-level write, a broader level showing through, remove clearing both levels, chapter tags left alone, and a file without Tags.

  • I reverted guards (FlacTag lazy creation, Vorbis picture-name refusal, AIFF view forwarding, the ASF Content Description twin match in remove and in replace, the APE measure's character check) and each turned its tests red; the WAV/AIFF gate is now main's IsEmpty.

Real files (generated with ffmpeg from lavfi, plus TagLib# sample.ape and Turning Lime.mkv). Each file was written through MediaFile.Read → Tag.SetCustomField("TAGLIBSHARP2_CUSTOM", "first", "second") → SaveToFile, then read by other tools:

File mutagen ffprobe exiftool mediainfo ffmpeg -f null payload (-c copy streamhash)
FLAC first, second first;second first / second first / second clean identical
MP3 ID3v2.4 first, second first first first clean identical
MP3 ID3v2.3 first, second first first first clean identical
M4A first, second first first, second first / second clean identical
Ogg Vorbis first, second first;second first / second first / second clean identical
Opus first, second first;second first / second first / second clean identical
WMA first, second second¹ (no unknown ASF names) first / second clean identical
MKV (lavfi, and Turning Lime.mkv) n/a second¹ first / second second¹ clean identical
APE (sample.ape) first, second first firstsecond² (no APE tags shown) clean decoded MD5 identical³
WavPack first, second first firstsecond² (no APE tags shown) clean identical
AIFF (ID3) first, second first first first clean identical
WAV (ID3) first, second first first first clean identical
WAV (INFO, IXYZ=only) n/a only (not listed) only clean identical

¹ That tool keeps one value per repeated key. ² exiftool prints the NUL-separated APE value without a separator. ³ Every byte before the APE tag is identical. The ffmpeg copy hash differs because its last APE packet runs into the tag, and the library writes the tag without its optional header. An unchanged save of the original does the same, so this predates this PR.

  • An unchanged re-save of each output file above is byte-identical (all 14).
  • The same set/save/get sweep passed on TaglibSharpSamples matroska test1–test8 (except test4, which ffmpeg itself cannot read and the library reads without tags), the five FLAC samples there, and TagLib# sample.{ogg,opus,wma,m4a,mpc,wv,flac,mp3,wav}.
  • Core/CustomFieldIntegrationTests.cs is env-gated: TAGLIBSHARP2_TEST_{FLAC,MP3,M4A,OGG,APE,WV,WMA,MKV,WAV,AIFF}. I ran it locally with all ten set (and again with MP3 v2.4, Ogg Vorbis, the lavfi MKV, and WAV+ID3). 10/10 passed on net8.0 and net10.0.

Additional Notes

MediaFile.Read(path) returns a FlacFile/Mp3File whose SaveToFile(path) fails with "No source path available", while the other formats re-read their source. This predates this PR and is not changed here; the integration tests save with SaveToFile(path, originalBytes).

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.04633% with 139 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.29%. Comparing base (de3ac07) to head (f5a53b3).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ibSharp2.Tests/Core/CustomFieldIntegrationTests.cs 2.32% 42 Missing ⚠️
tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs 95.30% 16 Missing and 4 partials ⚠️
...sts/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs 96.12% 2 Missing and 9 partials ⚠️
src/TagLibSharp2/Aiff/AiffTag.cs 35.71% 6 Missing and 3 partials ⚠️
src/TagLibSharp2/Asf/AsfFile.cs 92.77% 3 Missing and 3 partials ⚠️
src/TagLibSharp2/Id3/Id3v2/Frames/Utf16Text.cs 95.55% 6 Missing ⚠️
src/TagLibSharp2/Asf/AsfTag.cs 97.75% 1 Missing and 4 partials ⚠️
tests/TagLibSharp2.Tests/Asf/AsfClearTests.cs 95.79% 0 Missing and 5 partials ⚠️
...Sharp2.Tests/Core/CustomFieldFileRoundTripTests.cs 98.21% 0 Missing and 5 partials ⚠️
src/TagLibSharp2/Asf/AsfMetadataRecord.cs 94.20% 1 Missing and 3 partials ⚠️
... and 14 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #139      +/-   ##
==========================================
+ Coverage   93.20%   93.29%   +0.08%     
==========================================
  Files         392      409      +17     
  Lines       83610    86202    +2592     
  Branches     9512     9886     +374     
==========================================
+ Hits        77931    80422    +2491     
- Misses       3356     3412      +56     
- Partials     2323     2368      +45     

☔ 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/id3-trailing-nul November 21, 2026 21:02
@decriptor
decriptor force-pushed the feat/custom-fields branch 2 times, most recently from 441d1dc to fc3f36c Compare November 22, 2026 01:46
@decriptor
decriptor force-pushed the fix/id3-trailing-nul branch from abe696c to 203bbbf Compare November 22, 2026 01:55
@decriptor
decriptor force-pushed the feat/custom-fields branch 2 times, most recently from e9f62bc to 86ff758 Compare November 22, 2026 02:16
@decriptor
decriptor force-pushed the fix/id3-trailing-nul branch from 203bbbf to 0477a14 Compare November 22, 2026 02:17
Base automatically changed from fix/id3-trailing-nul to main November 22, 2026 05:15
Tag.GetCustomField, SetCustomField, RemoveCustomField, and
SupportsCustomFields read, write, and remove a named field with one or
more values in the format's own storage: a Vorbis comment field, an
APE text item, an ID3v2 TXXX frame (case-insensitive, like
GetUserText), an MP4 ----:com.apple.iTunes freeform field in either
meta, an ASF attribute, a file-level Matroska SimpleTag, or a RIFF
INFO chunk. ID3v1 reports no support. Null and empty values are
skipped, U+0000 is refused, and picture storage names are refused.

Notable rules:
- ASF: the first value goes in the Content Description or Extended
  Content Description, the rest in the Metadata Library Object, as
  Windows writes them. A write or remove of a Content Description
  name also drops the same-named descriptor ffmpeg writes beside it
  (title, copyright, rating in lower case). Getters read the first
  non-empty value from every object; writing back the value read is a
  no-op, null clears.
- ID3v2 UTF-16: one decoder (Utf16Text) skips the BOM each string
  carries in ID3v2.3, the layout mutagen writes, and a frame read
  from a file renders back with its BOMs and terminators.
- List-to-single bridges store Tag.FirstNonEmpty.
- CombinedTag (MP3, raw AAC), FlacTag, and the AIFF view forward the
  members; a test holds every non-leaf Tag type to them. WAV and AIFF
  write an ID3 chunk holding only a TXXX, through Id3v2Tag.IsEmpty,
  which now reads the one list of frame lists.
- AVI INFO takes any text under the CSET rules; WAV INFO stays
  Latin-1. APE key rules are one function shared with the item
  measure.

Closes #112
@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at f5a53b3. The PR is squashed to one commit, with a tree identical to the reviewed head 88484f5.

What was checked:

  • Round 7 (55a0466) found 1 major and 1 minor. Both are fixed at 88484f5; I verified this directly.
    • CombinedTag.SetCustomField writes every tag that supports custom fields, and removes the name from any tag that refuses the values. Afterwards every tag either holds the new values or doesn't hold the name. When no tag can store the values, it returns false and nothing changes.
    • The new matrix View_SetRemoveClear_LeavesNoTagWithAnOldValue covers every combined view: MP3, AAC, AVI (INFO+ID32), MPEG-PS, FLAC, AIFF and WAV, each with 1 and 2 values. Restoring the old behaviour turns it red, along with CombinedTag_TagThatRefusesTheValues_LosesItsOldValue.
    • The Tag.SetCustomField doc now says only WAV INFO refuses text outside ISO-8859-1.
  • Earlier rounds: all findings are fixed and pinned. Coverage includes:
  • Gates:
    • Release build: 0 warnings on 4 TFMs.
    • net8.0 and net10.0: 7066 passed / 55 skipped.
    • Format clean.
    • With the env-gated samples: 7112 passed.
    • CI 8/8 green, and 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 e1dc0ab 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 an arbitrary field on any tag

1 participant