diff --git a/CHANGELOG.md b/CHANGELOG.md index 44c8acc7..b165f706 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `Tag.GetCustomField`, `Tag.SetCustomField`, `Tag.RemoveCustomField`, and `Tag.SupportsCustomFields` read, + write, and remove a named field with one or more values on any tag (#112). The field lives in the format's + own storage: a Vorbis comment field, an APE text item, an ID3v2 `TXXX` frame, an MP4 `----:com.apple.iTunes` + freeform atom, an ASF attribute, a file-level Matroska `SimpleTag`, or a RIFF INFO chunk (Latin-1 in WAV; + any text in AVI, saved under the file's CSET rules). ID3v1 reports no support. `CombinedTag` (MP3, raw AAC, + AVI with an ID3v2 chunk, MPEG program streams), `FlacTag`, and the AIFF view (`AiffFile.Tag`) forward the + members. A combined view writes the values into every tag that can store them and removes the name from a + tag that cannot (RIFF INFO holds one value), so no tag keeps an older value. On ASF the first value goes to + the Content Description or Extended Content Description and the others to the Metadata Library Object, as + Windows writes them. `GetCustomField`, `Performers`, `AlbumArtists`, `Composers`, and `Genres` read every + value; `SetCustomField` and those four properties write them back the same way; a remove, a mapped setter + given a new value, and `Clear` drop the Metadata Library values too. ASF follows the write-back rule of + ID3v2, APE, and Vorbis Comments (`Tag.IsWriteBack`): writing back the exact value a mapped property read + changes nothing, `null` always clears, a stored value the getter cannot read included (the DWORD year + mutagen writes, say), and `CopyTo` always replaces. A single-value ASF getter returns the first non-empty + value of its attribute (a string, a number, or a BOOL), from the Content Description or Extended Content + Description and then the Metadata and Metadata Library Objects, as the ID3v2, APE, and Vorbis Comment + getters do, and `IsCompilation = false` clears a true stored in any of them. - `MatroskaFile.Tracks` lists the first 4096 known-size `TrackEntry` elements as `MatroskaTrack` objects, and `MatroskaFile.IsTrackListTruncated` tells when a file had more. Each track has `TrackNumber`, `TrackUid`, `TrackType`, `CodecId`, `IsDefault`, and `IsEnabled` (RFC 9559 §5.1.4.1). - `MatroskaTrack.IsEnabled` is written back on save. A stored `FlagEnabled` is rewritten in place. A missing one is added to the `TrackEntry`, taking the room from the `Void` right after `Tracks` when it has enough so no element moves; otherwise everything after `Tracks` moves once, with every SeekHead, Cues and Cluster `Position` value and CRC-32 updated, each widened when it no longer fits. Adding a FlagEnabled (minver 2) also makes the EBML header's `DocTypeVersion` at least 2: a stored lower value is raised, and an empty or missing one is written (RFC 9559 section 7); no Segment Position moves. A track the caller did not set keeps its bytes. - `AiffFile.Id3v2Tag`, and `AiffFile.Title`, `Artist`, `Comment` and `Copyright` @@ -94,10 +112,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska: a save keeps one copy of the Segment body at a time; a move no longer holds a second one. - **MP4**: A version 1 `mvhd` or `mdhd` whose 64-bit duration is past `TimeSpan.MaxValue` no longer throws out of `Mp4File.Read` or `Mp4AudioPropertiesParser.Parse`; the duration saturates. +- ID3v2 UTF-16 text with a byte order mark on each string (ID3v2.3 §3.3, mutagen's default) reads without a + U+FEFF at the start of every value after the first, in text frames, `TXXX`, and `TIPL`/`TMCL`/`IPLS`. One + decoder reads all of them on every target framework. A text or `TXXX` frame read from a file renders with the + BOMs and the trailing terminators it was read with, so an empty last value survives an unchanged save. A + `TXXX` that `SetCustomField` writes in an ID3v2.3 tag has a BOM before each value; a frame built in code keeps + one BOM, as before. +- Writing back the gain `R128TrackGainDb` or `R128AlbumGainDb` read keeps the stored text, so `-0512` is not + rewritten as `-512`. `null` still clears it, text the getter cannot parse included. +- An ASF title, artist, copyright, comment, or rating write replaces the same-named Extended Content Description + descriptor that ffmpeg writes beside the Content Description field, so other tools no longer show the old value. + An empty Content Description field reads that descriptor. ### Changed -- An APE artist, album artist, composer, or genre is the first name. It is not a comma-joined string. A Basic copy from APE into MP4, ASF, RIFF INFO, or ID3v1 keeps that first name. A copy into ID3v2 keeps the full list. +- An APE artist, album artist, composer, or genre is the first name. It is not a comma-joined string. A Basic copy from APE into MP4, ASF, RIFF INFO, or ID3v1 keeps that first name. A copy with the Extended options into ASF keeps every name, the first in the Content Description and the rest in the Metadata Library. A copy into ID3v2 keeps the full list. - A single-value ID3v2 or Vorbis Comment property, and an APE artist, album artist, composer, or genre, returns the first non-empty value, and an empty string only when every value is empty. Other APE text items still read every non-empty value joined with ", " (`A\0B` reads "A, B"). So do the public `Id3v2Tag.GetTextFrame`, `Id3v2Tag.GetUserText`, and `VorbisComment.GetValue`, and the ID3v2 comment and lyrics, which read the first non-empty frame without a description, then the first other one. ID3v2.4 §4.2 stores several strings as a NUL-separated list and Vorbis field names may repeat, so `"\0V2"` and `ARTIST=` + `ARTIST=V2` read `V2`. A value is kept as written: only an empty value is skipped, so `" \0B"` reads `" "`, as other readers show it. `Id3v2Tag.GetTextFrameValues` and the ID3v2 list properties no longer trim or drop blank NUL-separated values, so for NUL-separated values the single value and the first list entry agree. A value with `/` and no NUL is still split on `/` and trimmed, in any ID3v2 version, so `AC/DC` reads Artist `AC/DC` and Performers [`AC`, `DC`], as before. This replaces the earlier reading of a leading NUL as an empty first value, and it differs from mutagen and TagLib#, which return the empty first ID3v2 value; for a comment it matches what ffprobe and TagLib# show. Writing back the value read changes nothing, so a multi-value frame, item, or repeated field keeps every value. `= ""` clears: it removes the ID3v2 frame (for a comment or lyrics, every frame without a description) or the APE item, and leaves one empty Vorbis field. The comparison is ordinal, so a case-only edit still writes, and `null` clears like `= ""`. For an ID3v2 comment or lyrics, both remove only the frames without a description; a described comment or lyrics frame (such as `ID3v1 Comment`) is then still read, as before. This covers every ID3v2 string property (every text and TXXX frame, the year, the podcast feed URL, the MusicBrainz recording ID, the comment and the lyrics, and the movement number and total), every APE text property, and every Vorbis text field. - `CopyTo` reads every source value before it writes any. It replaces the target's list with the source value, even when that equals the target's first value. A list (performers, album artists, composers, genres, and the sort and role lists) that the target already holds is left as it is, and with `Extended` the artist and genre travel in those lists, so a `Basic` copy alone is what writes a single name over a list. When the source and target read from a common tag (a tag copied into itself, or a file's combined `Tag` copied into one of its own tags or into another view over them, as two reads of `Mp3File.Tag` are), the copy only adds values the target does not show. An empty source value still clears the field, as `= ""` does, so through a view it also clears what the view showed from another tag (an ID3v1 title, an AIFF `NAME` chunk). So `mp3.Id3v2Tag.CopyTo (mp3.Tag)` no longer rewrites the ID3v1 tag with values the combined view already shows from ID3v2. A fallback field of its own beside a value equal to the copied one stays: Vorbis `ORIGINALYEAR`, APE `Date`, and the ID3v2.3 `TDOR` beside `TORY`. Pictures are outside these rules: a non-empty source picture list always replaces the target's, as before. - A list copied into a tag that holds one name (MP4, ASF, RIFF INFO, ID3v1, or the base `Tag` list setters) stores its first non-empty entry, not an empty first entry. A copy of `ARTIST=` + `ARTIST=V2` into an MP4, WAV, or WMA file stores `V2`, as a `Basic` copy already did, instead of clearing the artist and genre. diff --git a/README.md b/README.md index 6109b492..2babe936 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison | **MusicBrainz IDs** | ✅ | ✅ | ✅ | ✅ | ✅² | ✅¹ | ✅¹ | ✅ | ✅⁹ | ✅¹ | ✅¹ | ✅⁸ | ✅⁸ | ✅⁸ | ✅¹ | | **Lyrics** | ✅ | ✅² | ✅² | ✅² | ✅² | ✅¹ | ✅¹ | ✅ | ✅⁹ | ✅¹ | ✅¹ | ✅⁸ | ✅⁸ | ✅⁸ | ✅¹ | | **Chapters** | ✅ | — | — | — | — | — | — | ✅¹¹ | — | — | — | — | — | — | — | +| **Custom fields** | ✅ | ✅ | ✅ | ✅ | ✅² | ✅¹² | ✅¹ | ✅¹³ | ✅⁹ | ✅¹ | ✅¹ | ✅⁸ | ✅⁸ | ✅⁸ | ✅¹ | | **Performer roles** | ✅ | ✅ | ✅ | ✅ | ✅² | ✅¹ | ✅¹ | — | ✅⁹ | ✅¹ | ✅¹ | ✅⁸ | ✅⁸ | ✅⁸ | ✅¹ | | **BWF broadcast metadata** | — | — | — | — | — | ✅ | — | — | — | — | — | — | — | — | — | | **Surround sound info** | — | — | — | — | — | ✅³ | — | ✅⁶ | — | ✅⁷ | ✅⁷ | — | — | — | — | @@ -59,6 +60,8 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison ⁹ Via ASF Extended Content Description ¹⁰ From the ADTS frame headers or the ADIF header. HE-AAC reports the AAC core sample rate. ¹¹ Nero `chpl` box and QuickTime chapter track, read and write (`Mp4File.Chapters`) +¹² Via ID3v2 `TXXX`, or a four-character RIFF INFO chunk when the file has no ID3v2 tag +¹³ Via ----:com.apple.iTunes freeform atoms ### Tag Format by Container @@ -157,6 +160,11 @@ Console.WriteLine($"AIFF: {aiff.AudioProperties?.SampleRate}Hz"); aiff.Id3v2Tag = new Id3v2Tag { Title = "Updated Title" }; aiff.SaveToFile("song.aiff"); +// Custom fields on any tag (Vorbis field, APE item, TXXX, MP4 freeform, ASF attribute, Matroska SimpleTag) +var tagged = MediaFile.Read("song.flac").Tag!; +tagged.SetCustomField("MY_APP_DATA", "first", "second"); +IReadOnlyList custom = tagged.GetCustomField("MY_APP_DATA"); + // Async support for high-throughput scenarios var asyncResult = await Mp4File.ReadFromFileAsync("song.m4a"); ``` diff --git a/docs/Cookbook.md b/docs/Cookbook.md index 73f358fe..9666dd04 100644 --- a/docs/Cookbook.md +++ b/docs/Cookbook.md @@ -84,6 +84,17 @@ if (result.IsSuccess) ### Read Custom Fields +Any tag, whatever the format, through the base `Tag`: + +```csharp +var tag = MediaFile.Read ("song.flac").Tag!; +if (tag.SupportsCustomFields) { + IReadOnlyList values = tag.GetCustomField ("MY_APP_DATA"); +} +``` + +Or through the format's own API: + ```csharp // ID3v2 - User-defined text (TXXX frames) var id3v2 = mp3.Id3v2Tag!; @@ -192,6 +203,20 @@ tag.R128AlbumGain = "256"; // +1 dB ### Write Custom Fields +Any tag, whatever the format. The field is stored where the format keeps named fields: a Vorbis comment, an +APE item, an ID3v2 `TXXX` frame, an MP4 `----:com.apple.iTunes:` atom, an ASF attribute, a Matroska +`SimpleTag`, or a RIFF INFO chunk (four-character names only). `SetCustomField` returns false and changes +nothing when the format cannot store the name or the values; ID3v1 stores none. + +```csharp +var tag = file.Tag!; +tag.SetCustomField ("MY_APP_DATA", "first", "second"); // several values +tag.SetCustomField ("CATALOG_ID", "ABC-12345"); +tag.RemoveCustomField ("OLD_FIELD"); +``` + +Or through the format's own API: + ```csharp // ID3v2 - User-defined text (TXXX frames) var id3v2 = mp3.Id3v2Tag!; diff --git a/docs/MIGRATION-FROM-TAGLIB.md b/docs/MIGRATION-FROM-TAGLIB.md index 1e0bf574..4e8c0c0c 100644 --- a/docs/MIGRATION-FROM-TAGLIB.md +++ b/docs/MIGRATION-FROM-TAGLIB.md @@ -364,6 +364,19 @@ string? gain = id3v2?.GetUserText("REPLAYGAIN_TRACK_GAIN"); id3v2?.SetUserText("REPLAYGAIN_TRACK_GAIN", "-6.5 dB"); ``` +### Custom Fields on Any Tag + +TagLib# 2.3 reads and writes a named field on a concrete tag with `GetField`, `SetField`, and `RemoveField`. +TagLibSharp2 has the same operations on the base `Tag`, so the caller does not need the concrete type. +`RiffInfoTag.GetField` already means "read one FOURCC", so the new members are named for what they hold: + +| TagLib# | TagLibSharp2 | +|---------|--------------| +| `GetField(name)` | `tag.GetCustomField(name)` (all values) | +| `SetField(name, values)` | `tag.SetCustomField(name, values)` (returns false if the format cannot store it) | +| `RemoveField(name)` | `tag.RemoveCustomField(name)` | +| — | `tag.SupportsCustomFields` (false for ID3v1) | + ## Binary Data Handling **TagLib#** uses `ByteVector`: diff --git a/src/TagLibSharp2/Aiff/AiffTag.cs b/src/TagLibSharp2/Aiff/AiffTag.cs index 8ebd017d..58950e19 100644 --- a/src/TagLibSharp2/Aiff/AiffTag.cs +++ b/src/TagLibSharp2/Aiff/AiffTag.cs @@ -499,6 +499,43 @@ public override BinaryData Render () => /// public override void Clear () => _file.ClearMappedFields (); + /// + /// Custom fields live in the file's ID3 tag, as TXXX frames; the native text chunks have fixed names. + public override bool SupportsCustomFields => true; + + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return Id3?.GetCustomField (name) ?? CustomFieldValues.None; + } + + /// + /// + /// Writes a TXXX frame in the file's ID3 tag. The tag is created only when the field is stored, so a + /// refused name or a write of no values does not add an ID3 chunk. + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (Id3 is { } existing) + return existing.SetCustomField (name, values); + + var created = new Id3v2Tag (); + if (!created.SetCustomField (name, values)) + return false; + if (!created.IsEmpty) + _file.Id3v2Tag = created; + return true; + } + + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return Id3?.RemoveCustomField (name) ?? false; + } + Id3v2Tag? Id3 => _file.Id3v2Tag; /// diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index fa5e57e8..bfeaed53 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -1001,6 +1001,62 @@ void SetOrRemoveProperty (string key, string? value, string? current, string? al /// public bool Remove (string key) => _items.Remove (key); + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// Reads a text or external locator item. Keys compare case-insensitively, and a zero byte separates + /// values (https://wiki.hydrogenaud.io/index.php?title=APE_key and + /// https://wiki.hydrogenaud.io/index.php?title=APE_Item_Value). A binary item has no text and returns + /// no values. + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldKey (name) || !_items.TryGetValue (name, out var item)) + return CustomFieldValues.None; + if (item.ItemType is not (ApeItemType.Text or ApeItemType.ExternalLocator)) + return CustomFieldValues.None; + + var values = new List (); + CustomFieldValues.AddSplit (System.Text.Encoding.UTF8.GetString (item.RawValue), values); + return values; + } + + /// + /// + /// Writes one UTF-8 text item with the values separated by a zero byte + /// (https://wiki.hydrogenaud.io/index.php?title=APE_Item_Value). The key replaces any item whose key + /// differs only in case, because APEv2 does not allow two such keys + /// (https://wiki.hydrogenaud.io/index.php?title=APE_key). + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldKey (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + + _items.Remove (name); + if (kept.Count > 0) + _items[name] = ApeTagItem.CreateText (name, string.Join ("\0", kept)); + return true; + } + + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return IsCustomFieldKey (name) && _items.Remove (name); + } + + /// + /// A valid APEv2 key that is not one of the Cover Art keys owns. + /// + static bool IsCustomFieldKey (string name) => + ApeTagItem.IsValidKey (name) && + !name.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase); + private void SetOrRemove (string key, string? value, string? alias = null) { if (alias is not null) diff --git a/src/TagLibSharp2/Ape/ApeTagItem.cs b/src/TagLibSharp2/Ape/ApeTagItem.cs index 4b9171bb..fd6e06ef 100644 --- a/src/TagLibSharp2/Ape/ApeTagItem.cs +++ b/src/TagLibSharp2/Ape/ApeTagItem.cs @@ -284,29 +284,20 @@ internal static bool TryMeasure (ReadOnlySpan head, long remaining, out lo keyLength = keyEnd - MinHeaderSize; - // Validate key length - if (keyLength < MinKeyLength) { - return $"APE item key too short: {keyLength} chars, minimum is {MinKeyLength}"; - } - - if (keyLength > MaxKeyLength) { - return $"APE item key too long: {keyLength} chars, maximum is {MaxKeyLength}"; - } - - // Validate key characters (ASCII 0x20-0x7E) + // The one copy of the key rules (KeyError). The key is widened into a stack buffer only when its + // length is in range, so measuring copies nothing to the heap. var keySpan = head.Slice (MinHeaderSize, keyLength); - foreach (var b in keySpan) { - if (b < 0x20 || b > 0x7E) { - return $"APE item key contains invalid character: 0x{b:X2}"; - } - } - - // Check for reserved keys (ASCII, case-insensitive) - foreach (var reserved in ReservedKeys) { - if (EqualsIgnoreCase (keySpan, reserved)) { - return $"APE item key '{reserved}' is reserved and cannot be used"; - } + string? keyError; + if (keyLength is >= MinKeyLength and <= MaxKeyLength) { + Span keyChars = stackalloc char[keyLength]; + for (var i = 0; i < keyLength; i++) + keyChars[i] = (char)keySpan[i]; + keyError = KeyError (keyLength, keyChars); + } else { + keyError = KeyError (keyLength, []); } + if (keyError is not null) + return keyError; // Value length is a uint32. Compare it with the bytes still left before any int add or Slice: // 0x80000000 and 0xFFFFFFF0 cast negative, and int.MaxValue overflows the end offset. @@ -320,23 +311,6 @@ internal static bool TryMeasure (ReadOnlySpan head, long remaining, out lo return null; } - static bool EqualsIgnoreCase (ReadOnlySpan key, string reserved) - { - if (key.Length != reserved.Length) - return false; - for (var i = 0; i < key.Length; i++) { - var a = key[i]; - var b = (byte)reserved[i]; - if (a is >= (byte)'a' and <= (byte)'z') - a -= 32; - if (b is >= (byte)'a' and <= (byte)'z') - b -= 32; - if (a != b) - return false; - } - return true; - } - /// /// Creates a text item. /// @@ -398,22 +372,45 @@ public byte[] Render () return data; } - private static void ValidateKey (string key) + /// + /// True when follows the APEv2 item key rules + /// (https://wiki.hydrogenaud.io/index.php?title=APE_key). + /// + internal static bool IsValidKey (string key) => KeyError (key.Length, key.AsSpan ()) is null; + + /// + /// The one copy of the APEv2 key rules, shared by , , the Create + /// methods, and : 2 to 255 characters from 0x20 to 0x7E, and not ID3, TAG, OggS, or + /// MP+ in any case (https://wiki.hydrogenaud.io/index.php?title=APE_key). + /// + /// The key's length; the characters are checked only when it is in range. + /// The key's characters, one per byte for a key read from a file. + /// Why the key is invalid, or null when it is valid. + static string? KeyError (int length, ReadOnlySpan key) { - if (key.Length < MinKeyLength) - throw new ArgumentException ($"Key too short: minimum is {MinKeyLength} characters", nameof (key)); + if (length < MinKeyLength) + return $"APE item key too short: {length} chars, minimum is {MinKeyLength}"; - if (key.Length > MaxKeyLength) - throw new ArgumentException ($"Key too long: maximum is {MaxKeyLength} characters", nameof (key)); + if (length > MaxKeyLength) + return $"APE item key too long: {length} chars, maximum is {MaxKeyLength}"; foreach (var c in key) { if (c < 0x20 || c > 0x7E) - throw new ArgumentException ($"Key contains invalid character: '{c}'", nameof (key)); + return $"APE item key contains invalid character: 0x{(int)c:X2}"; } foreach (var reserved in ReservedKeys) { - if (key.Equals (reserved, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException ($"Key '{key}' is reserved", nameof (key)); + if (key.Equals (reserved.AsSpan (), StringComparison.OrdinalIgnoreCase)) + return $"APE item key '{reserved}' is reserved and cannot be used"; } + + return null; + } + + private static void ValidateKey (string key) + { + var error = KeyError (key.Length, key.AsSpan ()); + if (error is not null) + throw new ArgumentException (error, nameof (key)); } } diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs index 94fed0ee..8e2adbc2 100644 --- a/src/TagLibSharp2/Asf/AsfFile.cs +++ b/src/TagLibSharp2/Asf/AsfFile.cs @@ -128,6 +128,9 @@ public static AsfFileReadResult Read (ReadOnlySpan data) AsfExtendedContentDescription? extendedDesc = null; AsfFileProperties? fileProps = null; AsfStreamProperties? streamProps = null; + List? metadata = null; + List? library = null; + var extensionUnreadable = false; for (uint i = 0; i < childCount && offset < data.Length - 24; i++) { // Read object GUID @@ -173,6 +176,8 @@ public static AsfFileReadResult Read (ReadOnlySpan data) var result = AsfStreamProperties.Parse (objectContent); if (result.IsSuccess && result.Value.IsAudio) streamProps = result.Value; + } else if (objectGuid == AsfGuids.HeaderExtensionObject) { + ReadHeaderExtension (objectContent, ref metadata, ref library, ref extensionUnreadable); } offset += contentSize; @@ -180,6 +185,7 @@ public static AsfFileReadResult Read (ReadOnlySpan data) // Create tag var tag = new AsfTag (contentDesc, extendedDesc); + tag.AttachHeaderExtension (metadata, library, extensionUnreadable); // Create audio properties var audioProps = CreateAudioProperties (fileProps, streamProps); @@ -189,6 +195,125 @@ public static AsfFileReadResult Read (ReadOnlySpan data) return AsfFileReadResult.Success (file); } + // Header Extension Object (ASF spec rev. 01.20.03 §3.4): Reserved Field 1 (GUID), Reserved Field 2 (WORD), + // Header Extension Data Size (DWORD), then child objects. + const int HeaderExtensionFixedSize = 16 + 2 + 4; + + // ASF_Reserved_1, the value of Reserved Field 1 (§3.4). + static readonly AsfGuid HeaderExtensionReserved1 = AsfGuid.Parse ( + new byte[] { 0x11, 0xD2, 0xD3, 0xAB, 0xBA, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 }).Value; + + /// + /// Reads the Metadata Object (§4.7) and Metadata Library Object (§4.8) out of a Header Extension Object. + /// A second copy of either, or one whose records run past it, makes the extension unreadable: the tag can + /// then not promise which values a name holds. + /// + static void ReadHeaderExtension (ReadOnlySpan content, ref List? metadata, + ref List? library, ref bool unreadable) + { + var children = HeaderExtensionChildren (content, out var complete); + if (!complete) + unreadable = true; + foreach (var (guid, body, _) in children) { + if (guid != AsfGuids.MetadataObject && guid != AsfGuids.MetadataLibraryObject) + continue; + + var isLibrary = guid == AsfGuids.MetadataLibraryObject; + if ((isLibrary ? library : metadata) is not null || + !AsfMetadataRecord.TryParseObject (body, out var records)) { + unreadable = true; + continue; + } + + if (isLibrary) + library = records; + else + metadata = records; + } + } + + /// + /// The child objects of a Header Extension Object's content: GUID, body after GUID and size, and the whole + /// object. A child that does not fit ends the walk, and is then false: a Metadata + /// Library Object could hide past it. + /// + static List<(AsfGuid Guid, byte[] Body, byte[] Whole)> HeaderExtensionChildren (ReadOnlySpan content, out bool complete) + { + var children = new List<(AsfGuid, byte[], byte[])> (); + complete = false; + if (content.Length < HeaderExtensionFixedSize) + return children; + + var dataSize = BinaryPrimitives.ReadUInt32LittleEndian (content.Slice (18)); + var data = content.Slice (HeaderExtensionFixedSize); + if (dataSize < (uint)data.Length) + data = data.Slice (0, (int)dataSize); + + var offset = 0; + while (data.Length - offset >= 24) { + var guid = AsfGuid.Parse (data.Slice (offset)); + var size = BinaryPrimitives.ReadUInt64LittleEndian (data.Slice (offset + 16)); + if (!guid.IsSuccess || size < 24 || size > (ulong)(data.Length - offset)) + break; + var whole = data.Slice (offset, (int)size); + children.Add ((guid.Value, whole.Slice (24).ToArray (), whole.ToArray ())); + offset += (int)size; + } + + complete = offset == data.Length; + return children; + } + + /// + /// Rebuilds a Header Extension Object with the tag's Metadata and Metadata Library records in place of the + /// old objects. Other children keep their bytes and order. Null builds a new + /// object holding only the records. + /// + static byte[] RenderHeaderExtension (byte[]? original, AsfTag tag) + { + var reserved1 = HeaderExtensionReserved1.Render ().ToArray (); + ushort reserved2 = 6; + var children = new List (); + var wroteMetadata = false; + var wroteLibrary = false; + if (original is not null && original.Length >= 24 + HeaderExtensionFixedSize) { + var content = original.AsSpan (24); + reserved1 = content.Slice (0, 16).ToArray (); + reserved2 = BinaryPrimitives.ReadUInt16LittleEndian (content.Slice (16)); + foreach (var (guid, _, whole) in HeaderExtensionChildren (content, out _)) { + if (guid == AsfGuids.MetadataObject) { + if (!wroteMetadata && tag.MetadataRecords is { } metadata) + children.Add (AsfMetadataRecord.RenderObject (AsfGuids.MetadataObject, metadata)); + wroteMetadata = true; + } else if (guid == AsfGuids.MetadataLibraryObject) { + if (!wroteLibrary && tag.LibraryRecords is { } library) + children.Add (AsfMetadataRecord.RenderObject (AsfGuids.MetadataLibraryObject, library)); + wroteLibrary = true; + } else { + children.Add (whole); + } + } + } + if (!wroteLibrary && tag.LibraryRecords is { Count: > 0 } added) + children.Add (AsfMetadataRecord.RenderObject (AsfGuids.MetadataLibraryObject, added)); + + var dataSize = 0; + foreach (var child in children) + dataSize += child.Length; + var result = new byte[24 + HeaderExtensionFixedSize + dataSize]; + AsfGuids.HeaderExtensionObject.Render ().Span.CopyTo (result); + BinaryPrimitives.WriteUInt64LittleEndian (result.AsSpan (16), (ulong)result.Length); + reserved1.CopyTo (result, 24); + BinaryPrimitives.WriteUInt16LittleEndian (result.AsSpan (40), reserved2); + BinaryPrimitives.WriteUInt32LittleEndian (result.AsSpan (42), (uint)dataSize); + var offset = 24 + HeaderExtensionFixedSize; + foreach (var child in children) { + child.CopyTo (result, offset); + offset += child.Length; + } + return result; + } + /// /// Reads the header object. The data object that follows is not copied. /// @@ -336,10 +461,20 @@ public byte[] Render (ReadOnlySpan originalData) // Build new header child objects var childObjects = new List (); - // Copy preserved objects (File Properties, Stream Properties, etc.) + // Copy preserved objects (File Properties, Stream Properties, etc.). The Header Extension Object is + // rebuilt only when a write changed its Metadata or Metadata Library records. + var wroteExtension = false; foreach (var obj in headerInfo.PreservedObjects) { + var isExtension = AsfGuid.Parse (obj).Value == AsfGuids.HeaderExtensionObject; + if (isExtension && Tag.HeaderExtensionChanged && !wroteExtension) { + childObjects.Add (RenderHeaderExtension (obj, Tag)); + wroteExtension = true; + continue; + } childObjects.Add (obj); } + if (!wroteExtension && Tag.HeaderExtensionChanged && Tag.LibraryRecords is { Count: > 0 }) + childObjects.Add (RenderHeaderExtension (null, Tag)); // Add Content Description if tag has content var contentDesc = Tag.ContentDescription; diff --git a/src/TagLibSharp2/Asf/AsfMetadataRecord.cs b/src/TagLibSharp2/Asf/AsfMetadataRecord.cs new file mode 100644 index 00000000..da3358bc --- /dev/null +++ b/src/TagLibSharp2/Asf/AsfMetadataRecord.cs @@ -0,0 +1,159 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Globalization; +using System.Text; + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Asf; + +/// +/// One Description Record of a Metadata Object or Metadata Library Object. +/// +/// +/// +/// Both objects use the same record layout (ASF spec rev. 01.20.03 §4.7 and §4.8): a WORD that is Reserved in the +/// Metadata Object and the Language List Index in the Metadata Library Object, then Stream Number (WORD), Name +/// Length (WORD), Data Type (WORD), Data Length (DWORD), the UTF-16LE name with its terminator, and the data. +/// Stream Number 0 means the whole file. +/// +/// +/// Data types: 0 Unicode string, 1 byte array, 2 BOOL (a WORD here, not the DWORD of §3.11), 3 DWORD, 4 QWORD, +/// 5 WORD, 6 GUID. +/// +/// +internal sealed class AsfMetadataRecord +{ + const int HeaderSize = 12; + + AsfMetadataRecord (ushort first, ushort stream, byte[] rawName, ushort type, byte[] data) + { + First = first; + Stream = stream; + RawName = rawName; + Type = type; + Data = data; + Name = TrimTerminator (Encoding.Unicode.GetString (rawName)); + } + + /// The Reserved WORD (Metadata Object) or Language List Index (Metadata Library Object). + public ushort First { get; } + + public ushort Stream { get; } + + /// The name bytes as stored, so an unchanged record renders the same bytes. + public byte[] RawName { get; } + + public ushort Type { get; } + + public byte[] Data { get; } + + public string Name { get; } + + /// True for a record about the whole file rather than one stream. + public bool IsFileLevel => Stream == 0; + + /// + /// The value as text: a Unicode string, or a WORD, DWORD, or QWORD in decimal. Null for BOOL, byte array, + /// GUID, and values shorter than their type. + /// + public string? Text => Type switch { + 0 => TrimTerminator (Encoding.Unicode.GetString (Data)), + 3 when Data.Length >= 4 => BinaryPrimitives.ReadUInt32LittleEndian (Data).ToString (CultureInfo.InvariantCulture), + 4 when Data.Length >= 8 => BinaryPrimitives.ReadUInt64LittleEndian (Data).ToString (CultureInfo.InvariantCulture), + 5 when Data.Length >= 2 => BinaryPrimitives.ReadUInt16LittleEndian (Data).ToString (CultureInfo.InvariantCulture), + _ => null + }; + + /// + /// The value as a BOOL, which the Metadata and Metadata Library Objects store as a WORD (ASF §4.7, §4.8); a + /// DWORD-sized BOOL reads too. Null for other types and for data shorter than a WORD. + /// + public bool? Bool => Type == 2 && Data.Length >= 2 ? Array.Exists (Data, b => b != 0) : null; + + /// The value as a number: a DWORD, or a Unicode string holding one. Null otherwise. + public uint? Number => Type switch { + 3 when Data.Length >= 4 => BinaryPrimitives.ReadUInt32LittleEndian (Data), + 0 => uint.TryParse (Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : null, + _ => null + }; + + /// A file-level Unicode string record in the default language. + public static AsfMetadataRecord CreateString (string name, string value) => + new (0, 0, Encoding.Unicode.GetBytes (name + "\0"), 0, Encoding.Unicode.GetBytes (value + "\0")); + + int Size => HeaderSize + RawName.Length + Data.Length; + + static string TrimTerminator (string text) + { + var end = text.Length; + while (end > 0 && text[end - 1] == '\0') + end--; + return text.Substring (0, end); + } + + /// + /// Parses the content of a Metadata Object or Metadata Library Object (after its GUID and size). + /// + /// False when a count or length runs past the object; nothing is returned then. + public static bool TryParseObject (ReadOnlySpan content, out List records) + { + records = []; + if (content.Length < 2) + return false; + + var count = BinaryPrimitives.ReadUInt16LittleEndian (content); + var offset = 2; + for (var i = 0; i < count; i++) { + if (content.Length - offset < HeaderSize) + return false; + var record = content.Slice (offset); + var nameLength = BinaryPrimitives.ReadUInt16LittleEndian (record.Slice (4)); + var dataLength = BinaryPrimitives.ReadUInt32LittleEndian (record.Slice (8)); + var available = record.Length - HeaderSize; + if (nameLength > available || dataLength > (uint)(available - nameLength)) + return false; + + records.Add (new AsfMetadataRecord ( + BinaryPrimitives.ReadUInt16LittleEndian (record), + BinaryPrimitives.ReadUInt16LittleEndian (record.Slice (2)), + record.Slice (HeaderSize, nameLength).ToArray (), + BinaryPrimitives.ReadUInt16LittleEndian (record.Slice (6)), + record.Slice (HeaderSize + nameLength, (int)dataLength).ToArray ())); + offset += HeaderSize + nameLength + (int)dataLength; + } + + return true; + } + + /// + /// Renders a whole Metadata Object or Metadata Library Object: GUID, size, record count, records. + /// + public static byte[] RenderObject (AsfGuid guid, IReadOnlyList records) + { + var size = 24 + 2; + foreach (var record in records) + size += record.Size; + + var result = new byte[size]; + guid.Render ().Span.CopyTo (result); + BinaryPrimitives.WriteUInt64LittleEndian (result.AsSpan (16), (ulong)size); + BinaryPrimitives.WriteUInt16LittleEndian (result.AsSpan (24), (ushort)records.Count); + var offset = 26; + foreach (var record in records) { + var span = result.AsSpan (offset); + BinaryPrimitives.WriteUInt16LittleEndian (span, record.First); + BinaryPrimitives.WriteUInt16LittleEndian (span.Slice (2), record.Stream); + BinaryPrimitives.WriteUInt16LittleEndian (span.Slice (4), (ushort)record.RawName.Length); + BinaryPrimitives.WriteUInt16LittleEndian (span.Slice (6), record.Type); + BinaryPrimitives.WriteUInt32LittleEndian (span.Slice (8), (uint)record.Data.Length); + record.RawName.CopyTo (result, offset + HeaderSize); + record.Data.CopyTo (result, offset + HeaderSize + record.RawName.Length); + offset += record.Size; + } + + return result; + } +} diff --git a/src/TagLibSharp2/Asf/AsfTag.cs b/src/TagLibSharp2/Asf/AsfTag.cs index c362adb2..645141ac 100644 --- a/src/TagLibSharp2/Asf/AsfTag.cs +++ b/src/TagLibSharp2/Asf/AsfTag.cs @@ -42,44 +42,34 @@ public AsfTag (AsfContentDescription? contentDescription, AsfExtendedContentDesc /// public override string? Title { - get => _contentDescription.Title; - set => _contentDescription = new AsfContentDescription ( - value ?? "", _contentDescription.Author, _contentDescription.Copyright, - _contentDescription.Description, _contentDescription.Rating); + get => ContentDescriptionText ("Title"); + set => SetContentDescriptionValue ("Title", value); } /// public override string? Artist { - get => _contentDescription.Author; - set => _contentDescription = new AsfContentDescription ( - _contentDescription.Title, value ?? "", _contentDescription.Copyright, - _contentDescription.Description, _contentDescription.Rating); + get => ContentDescriptionText ("Author"); + set => SetContentDescriptionValue ("Author", value); } /// public override string? Copyright { - get => _contentDescription.Copyright; - set => _contentDescription = new AsfContentDescription ( - _contentDescription.Title, _contentDescription.Author, value ?? "", - _contentDescription.Description, _contentDescription.Rating); + get => ContentDescriptionText ("Copyright"); + set => SetContentDescriptionValue ("Copyright", value); } /// public override string? Comment { - get => _contentDescription.Description; - set => _contentDescription = new AsfContentDescription ( - _contentDescription.Title, _contentDescription.Author, _contentDescription.Copyright, - value ?? "", _contentDescription.Rating); + get => ContentDescriptionText ("Description"); + set => SetContentDescriptionValue ("Description", value); } /// /// Gets or sets the rating field from Content Description. /// public string Rating { - get => _contentDescription.Rating; - set => _contentDescription = new AsfContentDescription ( - _contentDescription.Title, _contentDescription.Author, _contentDescription.Copyright, - _contentDescription.Description, value ?? ""); + get => ContentDescriptionText ("Rating"); + set => SetContentDescriptionValue ("Rating", value); } // ═══════════════════════════════════════════════════════════════ @@ -106,26 +96,8 @@ public override string? Genre { /// public override uint? Track { - get { - var desc = GetDescriptor ("WM/TrackNumber"); - if (desc is null) return null; - - if (desc.Type == AsfAttributeType.Dword) - return desc.DwordValue; - - // Try parsing string value - if (desc.StringValue is not null && - uint.TryParse (desc.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var track)) - return track; - - return null; - } - set { - if (value.HasValue) - SetDword ("WM/TrackNumber", value.Value); - else - RemoveDescriptor ("WM/TrackNumber"); - } + get => GetNumber ("WM/TrackNumber"); + set => SetNumber ("WM/TrackNumber", value); } /// @@ -150,7 +122,9 @@ public override string? Conductor { public override uint? DiscNumber { get => ParsePartOfSet ().disc; set { - var (_, count) = ParsePartOfSet (); + var (disc, count) = ParsePartOfSet (); + if (IsWriteBack (value, disc)) + return; SetPartOfSet (value, count); } } @@ -159,7 +133,9 @@ public override uint? DiscNumber { public override uint? TotalDiscs { get => ParsePartOfSet ().count; set { - var (disc, _) = ParsePartOfSet (); + var (disc, count) = ParsePartOfSet (); + if (IsWriteBack (value, count)) + return; SetPartOfSet (disc, value); } } @@ -171,25 +147,8 @@ public override uint? TotalDiscs { /// public override uint? BeatsPerMinute { - get { - var desc = GetDescriptor ("WM/BeatsPerMinute"); - if (desc is null) return null; - - if (desc.Type == AsfAttributeType.Dword) - return desc.DwordValue; - - if (desc.StringValue is not null && - uint.TryParse (desc.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var bpm)) - return bpm; - - return null; - } - set { - if (value.HasValue) - SetDword ("WM/BeatsPerMinute", value.Value); - else - RemoveDescriptor ("WM/BeatsPerMinute"); - } + get => GetNumber ("WM/BeatsPerMinute"); + set => SetNumber ("WM/BeatsPerMinute", value); } /// @@ -212,11 +171,15 @@ public override string? Isrc { /// public override bool IsCompilation { - get { - var desc = GetDescriptor ("WM/IsCompilation"); - return desc?.BoolValue == true; + get => FirstBool ("WM/IsCompilation") == true; + set { + // Writing back true, or false when every stored value is a BOOL false (or none is stored), is a no-op. + // False over any other value, a true the getter does not reach or a DWORD 1 say, is a clear, as is any + // value a copy writes. + if (!IsCopying && (value ? IsCompilation : OnlyFalseIsStored ("WM/IsCompilation"))) + return; + SetBool ("WM/IsCompilation", value); } - set => SetBool ("WM/IsCompilation", value); } /// @@ -315,25 +278,8 @@ public override string? CatalogNumber { /// public override uint? TotalTracks { - get { - var desc = GetDescriptor ("WM/TrackTotal"); - if (desc is null) return null; - - if (desc.Type == AsfAttributeType.Dword) - return desc.DwordValue; - - if (desc.StringValue is not null && - uint.TryParse (desc.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num)) - return num; - - return null; - } - set { - if (value.HasValue) - SetDword ("WM/TrackTotal", value.Value); - else - RemoveDescriptor ("WM/TrackTotal"); - } + get => GetNumber ("WM/TrackTotal"); + set => SetNumber ("WM/TrackTotal", value); } /// @@ -482,48 +428,14 @@ public override string? Movement { /// public override uint? MovementNumber { - get { - var desc = GetDescriptor ("WM/MovementNumber"); - if (desc is null) return null; - - if (desc.Type == AsfAttributeType.Dword) - return desc.DwordValue; - - if (desc.StringValue is not null && - uint.TryParse (desc.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num)) - return num; - - return null; - } - set { - if (value.HasValue) - SetDword ("WM/MovementNumber", value.Value); - else - RemoveDescriptor ("WM/MovementNumber"); - } + get => GetNumber ("WM/MovementNumber"); + set => SetNumber ("WM/MovementNumber", value); } /// public override uint? MovementTotal { - get { - var desc = GetDescriptor ("WM/MovementTotal"); - if (desc is null) return null; - - if (desc.Type == AsfAttributeType.Dword) - return desc.DwordValue; - - if (desc.StringValue is not null && - uint.TryParse (desc.StringValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num)) - return num; - - return null; - } - set { - if (value.HasValue) - SetDword ("WM/MovementTotal", value.Value); - else - RemoveDescriptor ("WM/MovementTotal"); - } + get => GetNumber ("WM/MovementTotal"); + set => SetNumber ("WM/MovementTotal", value); } // ═══════════════════════════════════════════════════════════════ @@ -560,6 +472,44 @@ public override string? ComposerSort { set => SetString ("WM/ComposerSortOrder", value); } + // ═══════════════════════════════════════════════════════════════ + // Multi-valued attributes (first value in CD/ECD, the rest in the Metadata Library) + // ═══════════════════════════════════════════════════════════════ + +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + /// + /// + /// Every Author value: the Content Description field and then its Metadata Library values, the + /// layout Windows writes for a multi-valued attribute + /// (https://mutagen-specs.readthedocs.io/en/latest/asf/index.html, "Multiple Values"). + /// + public override string[] Performers { + get => GetValues ("Author"); + set => SetValues ("Author", value, v => Artist = v); + } + + /// + /// Every WM/AlbumArtist value, from the Extended Content Description and the Metadata Library. + public override string[] AlbumArtists { + get => GetValues ("WM/AlbumArtist"); + set => SetValues ("WM/AlbumArtist", value, v => AlbumArtist = v); + } + + /// + /// Every WM/Composer value, from the Extended Content Description and the Metadata Library. + public override string[] Composers { + get => GetValues ("WM/Composer"); + set => SetValues ("WM/Composer", value, v => Composer = v); + } + + /// + /// Every WM/Genre value, from the Extended Content Description and the Metadata Library. + public override string[] Genres { + get => GetValues ("WM/Genre"); + set => SetValues ("WM/Genre", value, v => Genre = v); + } +#pragma warning restore CA1819 + // ═══════════════════════════════════════════════════════════════ // Pictures (WM/Picture) // ═══════════════════════════════════════════════════════════════ @@ -614,10 +564,15 @@ Track is null && _descriptors.Count == 0; /// + /// + /// Also removes the file-level records of the Metadata and Metadata Library objects, which hold the extra + /// values of multi-valued attributes. Records about one stream stay. + /// public override void Clear () { _contentDescription = new AsfContentDescription ("", "", "", "", ""); _descriptors.Clear (); + DropExtraValues (null); } /// @@ -645,22 +600,443 @@ public override BinaryData Render () public AsfExtendedContentDescription ExtendedContentDescription => new (_descriptors); // ═══════════════════════════════════════════════════════════════ - // Helper Methods + // Custom Fields // ═══════════════════════════════════════════════════════════════ - AsfDescriptor? GetDescriptor (string name) + // ASF spec rev. 01.20.03 §3.10 and §3.11: names and values carry 16-bit byte lengths, and + // strings are UTF-16LE with a two-byte terminator. + const int MaxLengthField = ushort.MaxValue; + + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// + /// Reads every Extended Content Description attribute named , compared + /// case-insensitively as the mapped properties compare them (ASF spec rev. 01.20.03 §3.11). A string + /// attribute is its text. A WORD, DWORD, or QWORD attribute is its decimal value. BOOL and binary + /// attributes have no text and are skipped. + /// + /// + /// Title, Author, Copyright, Description, and Rating are the Content + /// Description Object's fields (§3.10), the same ones the Windows Media Format SDK exposes under those + /// attribute names. + /// + /// + /// The file-level records with that name in the Metadata Object and the Metadata Library Object (§4.7 and + /// §4.8, inside the Header Extension Object §3.4) follow, in any language. Windows writes the first value of + /// a multi-valued attribute to the Content Description or Extended Content Description and the rest there + /// (https://mutagen-specs.readthedocs.io/en/latest/asf/index.html, "Multiple Values"). + /// + /// + public override IReadOnlyList GetCustomField (string name) { - for (int i = 0; i < _descriptors.Count; i++) { - if (string.Equals (_descriptors[i].Name, name, StringComparison.OrdinalIgnoreCase)) - return _descriptors[i]; + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name)) + return CustomFieldValues.None; + + var values = new List (); + // A Content Description field hides an Extended Content Description descriptor of its name, the copy ffmpeg + // also writes, unless the field is empty. + if (TryGetContentDescriptionField (name, out var fixedValue) && !string.IsNullOrEmpty (fixedValue)) { + values.Add (fixedValue); + AddExtraValues (name, values); + return values; + } + + foreach (var desc in _descriptors) { + if (!string.Equals (desc.Name, name, StringComparison.OrdinalIgnoreCase)) + continue; + var text = desc.Type switch { + AsfAttributeType.UnicodeString => desc.StringValue, + AsfAttributeType.Word => desc.WordValue?.ToString (CultureInfo.InvariantCulture), + AsfAttributeType.Dword => desc.DwordValue?.ToString (CultureInfo.InvariantCulture), + AsfAttributeType.Qword => desc.QwordValue?.ToString (CultureInfo.InvariantCulture), + _ => null + }; + if (!string.IsNullOrEmpty (text)) + values.Add (text!); + } + AddExtraValues (name, values); + return values; + } + + /// + /// + /// + /// Writes the first value as a Unicode string attribute in the Extended Content Description Object (ASF spec + /// rev. 01.20.03 §3.11), at the position of the first attribute it replaces, or in the Content Description + /// field (§3.10) for its five names. The other values become file-level records of the Metadata Library + /// Object (§4.8), the layout Windows writes; a Header Extension Object (§3.4) is added when the file has + /// none. Every earlier value of the name is removed from all four places. + /// + /// + /// Returns false when the Metadata or Metadata Library Object in the file could not be parsed, because a + /// value stored there would survive the write. + /// + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + foreach (var value in kept) { + if (Utf16Length (value) > MaxLengthField) + return false; + } + + if (_extensionUnreadable || ExtraRecordCount () + kept.Count > ushort.MaxValue) + return false; + + if (TryGetContentDescriptionField (name, out _)) { + ReplaceContentDescriptionField (name, kept.Count == 0 ? "" : kept[0]); + } else { + var at = _descriptors.FindIndex (d => string.Equals (d.Name, name, StringComparison.OrdinalIgnoreCase)); + RemoveDescriptor (name); + if (kept.Count > 0) + _descriptors.Insert (at < 0 ? _descriptors.Count : at, AsfDescriptor.CreateString (name, kept[0])); + } + + if (kept.Count > 1) { + _library ??= []; + for (var i = 1; i < kept.Count; i++) + _library.Add (AsfMetadataRecord.CreateString (name, kept[i])); + HeaderExtensionChanged = true; + } + return true; + } + + /// + /// + /// Removes the name from the Content Description or Extended Content Description and its file-level + /// records from the Metadata and Metadata Library objects. Returns false, and changes nothing, when one of + /// those objects could not be parsed. + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name) || _extensionUnreadable) + return false; + + var before = _descriptors.Count; + if (TryGetContentDescriptionField (name, out var fixedValue)) { + var dropped = DropExtraValues (name); + RemoveDescriptorOnly (name); + SetContentDescriptionField (name, ""); + return !string.IsNullOrEmpty (fixedValue) || dropped || _descriptors.Count != before; + } + + var droppedExtra = DropExtraValues (name); + RemoveDescriptorOnly (name); + return _descriptors.Count != before || droppedExtra; + } + + // ═══════════════════════════════════════════════════════════════ + // Metadata Object and Metadata Library Object (Header Extension) + // ═══════════════════════════════════════════════════════════════ + + List? _metadata; + List? _library; + bool _extensionUnreadable; + + /// + /// Records of the Metadata Object (§4.7), or null when the file has none or it could not be parsed. + /// + internal IReadOnlyList? MetadataRecords => _metadata; + + /// + /// Records of the Metadata Library Object (§4.8), or null when the file has none or it could not be parsed. + /// + internal IReadOnlyList? LibraryRecords => _library; + + /// + /// True after a write changed the records, so the Header Extension Object must be rebuilt on save. + /// An unchanged tag keeps the object's bytes. + /// + internal bool HeaderExtensionChanged { get; private set; } + + /// + /// Attaches the records read from the file's Header Extension Object. + /// + /// Metadata Object records, or null when absent. + /// Metadata Library Object records, or null when absent. + /// True when one of the objects was present but could not be parsed. + internal void AttachHeaderExtension (List? metadata, List? library, bool unreadable) + { + _metadata = unreadable ? null : metadata; + _library = unreadable ? null : library; + _extensionUnreadable = unreadable; + HeaderExtensionChanged = false; + } + + int ExtraRecordCount () => (_library?.Count ?? 0); + + void AddExtraValues (string name, List values) + { + foreach (var records in new[] { _metadata, _library }) { + if (records is null) + continue; + foreach (var record in records) { + if (!record.IsFileLevel || !string.Equals (record.Name, name, StringComparison.OrdinalIgnoreCase)) + continue; + var text = record.Text; + if (!string.IsNullOrEmpty (text)) + values.Add (text!); + } + } + } + + /// + /// Removes the file-level records named , or every file-level record when it is null. + /// + bool DropExtraValues (string? name) + { + var removed = 0; + foreach (var records in new[] { _metadata, _library }) { + removed += records?.RemoveAll (r => r.IsFileLevel && + (name is null || string.Equals (r.Name, name, StringComparison.OrdinalIgnoreCase))) ?? 0; + } + if (removed > 0) + HeaderExtensionChanged = true; + return removed > 0; + } + + /// + /// Sets a Content Description field and removes the other values stored under its name, in the Extended Content + /// Description (the copy ffmpeg writes) and the Metadata Library, so the name holds one value afterwards. + /// + void ReplaceContentDescriptionField (string name, string value) + { + DropExtraValues (name); + RemoveDescriptorOnly (name); + SetContentDescriptionField (name, value); + } + + /// + /// The mapped setter of a Content Description field: a no-op when the field already holds the value, so a + /// write-back keeps the attribute's other values in the Metadata Library. + /// + void SetContentDescriptionValue (string name, string? value) + { + if (IsStringWriteBack (value, ContentDescriptionText (name), name)) + return; + ReplaceContentDescriptionField (name, value ?? ""); + } + + /// + /// for a mapped string attribute: the value the property read, + /// never null, and never during a copy. "" counts as the value read only when no value of the attribute holds + /// text, so "" over Metadata Library values is a clear. + /// + bool IsStringWriteBack (string? value, string? current, string name) => + IsWriteBack (value, current) && (value!.Length > 0 || GetCustomField (name).Count == 0); + + /// + /// A mapped number attribute: its first non-empty DWORD or string value, from its Extended Content Description + /// descriptors and then its file-level Metadata and Metadata Library records (ASF §4.7, §4.8), as + /// reads a string. A string must hold a number; a WORD or QWORD is not read. + /// + uint? GetNumber (string name) + { + foreach (var desc in _descriptors) { + if (!string.Equals (desc.Name, name, StringComparison.OrdinalIgnoreCase)) + continue; + if (desc.Type == AsfAttributeType.Dword) + return desc.DwordValue; + if (desc.Type == AsfAttributeType.UnicodeString && !string.IsNullOrEmpty (desc.StringValue)) + return ParseNumber (desc.StringValue); + } + foreach (var record in FileLevelRecords (name)) { + if (record.Type == 3 || record.Type == 0 && !string.IsNullOrEmpty (record.Text)) + return record.Number; } return null; } - string? GetString (string name) => GetDescriptor (name)?.StringValue; + static uint? ParseNumber (string? text) => + uint.TryParse (text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : null; + + /// + /// A mapped BOOL attribute: its first BOOL value, from the Extended Content Description and then the file-level + /// Metadata and Metadata Library records. Null when it stores no BOOL. + /// + bool? FirstBool (string name) + { + foreach (var desc in _descriptors) { + if (desc.Type == AsfAttributeType.Bool && desc.BoolValue is { } value && + string.Equals (desc.Name, name, StringComparison.OrdinalIgnoreCase)) + return value; + } + foreach (var record in FileLevelRecords (name)) { + if (record.Bool is { } value) + return value; + } + return null; + } + + /// True when every value of the attribute, in any object, is a BOOL false, or none is stored. + bool OnlyFalseIsStored (string name) + { + foreach (var desc in _descriptors) { + if (string.Equals (desc.Name, name, StringComparison.OrdinalIgnoreCase) && desc.BoolValue != false) + return false; + } + foreach (var record in FileLevelRecords (name)) { + if (record.Bool != false) + return false; + } + return true; + } + + /// The file-level Metadata and then Metadata Library records of an attribute, in file order. + IEnumerable FileLevelRecords (string name) + { + foreach (var records in new[] { _metadata, _library }) { + if (records is null) + continue; + foreach (var record in records) { + if (record.IsFileLevel && string.Equals (record.Name, name, StringComparison.OrdinalIgnoreCase)) + yield return record; + } + } + } + /// + /// Writes a mapped number attribute as a DWORD. Writing back the number the property read is a no-op + /// (); null always clears whatever is stored. + /// + void SetNumber (string name, uint? value) + { + if (IsWriteBack (value, GetNumber (name))) + return; + if (value.HasValue) + SetDword (name, value.Value); + else + RemoveDescriptor (name); + } + + /// + /// The array view of a multi-valued attribute: the Content Description or Extended Content Description value + /// followed by its Metadata Library values, the same values reads. + /// + string[] GetValues (string name) => [.. GetCustomField (name)]; + + /// + /// Writes a multi-valued attribute: the first value where Windows keeps it and the others in the Metadata + /// Library. Writing the values the array already reads is a no-op. When the values cannot be stored that way + /// (an unreadable Header Extension, or a value too long), only the first value is written, as before. + /// + void SetValues (string name, string[]? values, Action setFirst) + { + var incoming = new List (); + foreach (var v in values ?? []) { + if (!string.IsNullOrEmpty (v)) + incoming.Add (v); + } + if (!IsCopying && GetCustomField (name).SequenceEqual (incoming, StringComparer.Ordinal)) + return; + if (!SetCustomField (name, [.. incoming])) + setFirst (FirstNonEmpty (values)); + } + + /// + /// A name that fits its 16-bit length field and is not WM/Picture, which owns. + /// + static bool IsCustomFieldName (string name) => + CustomFieldValues.IsUsableName (name) && + Utf16Length (name) <= MaxLengthField && + !string.Equals (name, AsfPicture.AttributeName, StringComparison.OrdinalIgnoreCase); + + /// + /// Bytes of UTF-16LE text plus its two-byte terminator. + /// + static long Utf16Length (string text) => ((long)text.Length + 1) * 2; + + bool TryGetContentDescriptionField (string name, out string value) + { + if (string.Equals (name, "Title", StringComparison.OrdinalIgnoreCase)) + value = _contentDescription.Title; + else if (string.Equals (name, "Author", StringComparison.OrdinalIgnoreCase)) + value = _contentDescription.Author; + else if (string.Equals (name, "Copyright", StringComparison.OrdinalIgnoreCase)) + value = _contentDescription.Copyright; + else if (string.Equals (name, "Description", StringComparison.OrdinalIgnoreCase)) + value = _contentDescription.Description; + else if (string.Equals (name, "Rating", StringComparison.OrdinalIgnoreCase)) + value = _contentDescription.Rating; + else { + value = ""; + return false; + } + return true; + } + + void SetContentDescriptionField (string name, string value) + { + var cd = _contentDescription; + _contentDescription = name.ToUpperInvariant () switch { + "TITLE" => new AsfContentDescription (value, cd.Author, cd.Copyright, cd.Description, cd.Rating), + "AUTHOR" => new AsfContentDescription (cd.Title, value, cd.Copyright, cd.Description, cd.Rating), + "COPYRIGHT" => new AsfContentDescription (cd.Title, cd.Author, value, cd.Description, cd.Rating), + "DESCRIPTION" => new AsfContentDescription (cd.Title, cd.Author, cd.Copyright, value, cd.Rating), + _ => new AsfContentDescription (cd.Title, cd.Author, cd.Copyright, cd.Description, value) + }; + } + + // ═══════════════════════════════════════════════════════════════ + // Helper Methods + // ═══════════════════════════════════════════════════════════════ + + /// + /// The value a mapped string property reads: the first non-empty string value of the attribute, from its + /// Extended Content Description descriptors and then its file-level Metadata and Metadata Library records, + /// as the ID3v2, APE, and Vorbis Comment getters read the first non-empty value. "" when every string + /// value is empty, and null when the attribute holds no string. + /// + string? GetString (string name) + { + string? empty = null; + foreach (var desc in _descriptors) { + if (desc.Type != AsfAttributeType.UnicodeString || + !string.Equals (desc.Name, name, StringComparison.OrdinalIgnoreCase)) + continue; + var text = desc.StringValue; + if (!string.IsNullOrEmpty (text)) + return text; + empty ??= text; + } + return FirstLibraryText (name) ?? empty; + } + + /// + /// A Content Description field as its property reads it: the field, or when it is empty, the first non-empty + /// string value of that name in the Extended Content Description and then the Metadata or Metadata Library + /// Object (). + /// + string ContentDescriptionText (string name) + { + TryGetContentDescriptionField (name, out var value); + return string.IsNullOrEmpty (value) ? GetString (name) ?? value : value; + } + + string? FirstLibraryText (string name) + { + foreach (var record in FileLevelRecords (name)) { + if (record.Type == 0 && record.Text is { Length: > 0 } text) + return text; + } + return null; + } + + /// + /// Writes a mapped string attribute. Writing back the value the property read is a no-op, so the attribute's + /// other values, in the Extended Content Description or the Metadata Library, stay; null always clears. + /// void SetString (string name, string? value) { + if (IsStringWriteBack (value, GetString (name), name)) + return; RemoveDescriptor (name); if (!string.IsNullOrEmpty (value)) _descriptors.Add (AsfDescriptor.CreateString (name, value!)); @@ -678,7 +1054,17 @@ void SetBool (string name, bool value) _descriptors.Add (AsfDescriptor.CreateBool (name, value)); } + /// + /// Removes every value of an attribute: its Extended Content Description descriptors and its file-level + /// Metadata and Metadata Library records. Every mapped setter goes through here. + /// void RemoveDescriptor (string name) + { + DropExtraValues (name); + RemoveDescriptorOnly (name); + } + + void RemoveDescriptorOnly (string name) { for (int i = _descriptors.Count - 1; i >= 0; i--) { if (string.Equals (_descriptors[i].Name, name, StringComparison.OrdinalIgnoreCase)) diff --git a/src/TagLibSharp2/Core/CombinedTag.cs b/src/TagLibSharp2/Core/CombinedTag.cs index 03bc347c..40878a22 100644 --- a/src/TagLibSharp2/Core/CombinedTag.cs +++ b/src/TagLibSharp2/Core/CombinedTag.cs @@ -619,6 +619,81 @@ public override IPicture[] Pictures { } #pragma warning restore CA1819 + /// + /// True when any underlying tag supports custom fields. + public override bool SupportsCustomFields { + get { + foreach (var tag in _tags) { + if (tag is { SupportsCustomFields: true }) + return true; + } + return false; + } + } + + /// + /// Returns the values of the first tag in priority order that holds any. + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + foreach (var tag in _tags) { + if (tag is null) + continue; + var values = tag.GetCustomField (name); + if (values.Count > 0) + return values; + } + return CustomFieldValues.None; + } + + /// + /// + /// + /// Writes every underlying tag that supports custom fields, as the property setters write every tag, and + /// writes the values only where they fit. A tag that cannot store them (a RIFF INFO chunk holds one value + /// under a four-character name, for example) does not keep an older value under the name: the name is + /// removed from it. So afterwards every tag either holds the new values or does not hold the name, and + /// , which reads the first tag that holds the name, returns the new values. + /// + /// + /// Returns true when at least one tag stored the values. When none could, it returns false and no tag + /// changes. A tag without custom fields, such as ID3v1, is left as it is. + /// + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + var stored = false; + List? refused = null; + foreach (var tag in _tags) { + if (tag is not { SupportsCustomFields: true }) + continue; + if (tag.SetCustomField (name, values)) + stored = true; + else + (refused ??= []).Add (tag); + } + + if (stored && refused is not null) { + foreach (var tag in refused) + tag.RemoveCustomField (name); + } + return stored; + } + + /// + /// Removes the field from every underlying tag. Returns true when any of them held it. + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + var removed = false; + foreach (var tag in _tags) { + if (tag is not null) + removed |= tag.RemoveCustomField (name); + } + return removed; + } + /// /// /// is a view over multiple tags and does not produce its diff --git a/src/TagLibSharp2/Core/CustomFieldValues.cs b/src/TagLibSharp2/Core/CustomFieldValues.cs new file mode 100644 index 00000000..62a212b4 --- /dev/null +++ b/src/TagLibSharp2/Core/CustomFieldValues.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// Shared argument rules for , , +/// and . +/// +internal static class CustomFieldValues +{ + /// + /// An empty result for a name the tag does not hold. + /// + public static IReadOnlyList None { get; } = Array.Empty (); + + /// + /// Throws when is null. Every other bad name is reported by the return value. + /// + public static void ThrowIfNull ([ValidatedNotNull] string name) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + Polyfills.ThrowIfNull (name, nameof (name)); +#else + ArgumentNullException.ThrowIfNull (name); +#endif + } + + /// + /// True when is not empty and has no U+0000. Every format needs at least that. + /// + public static bool IsUsableName (string name) => + name.Length > 0 && !HasNul (name); + + /// + /// Drops null and empty values and keeps the order of the rest. + /// + /// The caller's values. Null means none. + /// The values to store. Empty means the field is removed. + /// + /// False when a value contains U+0000. ID3v2 and APE use it to separate values and RIFF INFO uses it + /// to end the string, so no format could store that value as given. + /// + public static bool TryNormalize (string?[]? values, out List kept) + { + kept = new List (values?.Length ?? 0); + if (values is null) + return true; + + foreach (var value in values) { + if (string.IsNullOrEmpty (value)) + continue; + if (HasNul (value!)) { + kept.Clear (); + return false; + } + kept.Add (value!); + } + + return true; + } + + static bool HasNul (string text) + { + foreach (var c in text) { + if (c == '\0') + return true; + } + return false; + } + + /// + /// Splits a NUL-separated value list. Empty parts, including a trailing terminator, are not values. + /// + public static void AddSplit (string text, List into) + { + if (text.Length == 0) + return; + + foreach (var part in text.Split ('\0')) { + if (part.Length > 0) + into.Add (part); + } + } +} + +/// +/// Tells CA1062 that a helper throws when this argument is null. +/// +[AttributeUsage (AttributeTargets.Parameter)] +internal sealed class ValidatedNotNullAttribute : Attribute +{ +} diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 481cf560..d168fdb0 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -151,7 +151,7 @@ internal static bool IsWriteBack (uint? value, uint? current) => /// /// /// This returns the first performer. For multiple performers, use . - /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Format-specific limitations: /// /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). @@ -248,7 +248,7 @@ public virtual string[] Performers { /// /// /// This returns the first genre. For multiple genres, use . - /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Format-specific limitations: /// /// ID3v1: Single genre only, must match one of 192 predefined genres. Custom genres not supported. @@ -296,7 +296,7 @@ public virtual string[] Genres { /// /// /// This returns the first album artist. For multiple album artists, use . - /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? AlbumArtist { get => null; set { } } @@ -336,7 +336,7 @@ public virtual string[] AlbumArtists { /// /// /// This returns the first composer. For multiple composers, use . - /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. + /// In ID3v2, APE, Vorbis Comments, and ASF, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? Composer { get => null; set { } } @@ -836,6 +836,10 @@ public double? R128TrackGainDb { return q78 / 256.0; } set { + // Writing back the gain the getter read is a no-op. Null always clears, text the getter cannot parse + // included, and a copy always writes. + if (!IsCopying && value.HasValue && value == R128TrackGainDb) + return; R128TrackGain = value.HasValue ? ClampToQ78 (value.Value).ToString (CultureInfo.InvariantCulture) : null; @@ -863,6 +867,10 @@ public double? R128AlbumGainDb { return q78 / 256.0; } set { + // Writing back the gain the getter read is a no-op. Null always clears, text the getter cannot parse + // included, and a copy always writes. + if (!IsCopying && value.HasValue && value == R128AlbumGainDb) + return; R128AlbumGain = value.HasValue ? ClampToQ78 (value.Value).ToString (CultureInfo.InvariantCulture) : null; @@ -1133,6 +1141,132 @@ public virtual string? MusicBrainzReleaseArtistId { string.IsNullOrEmpty (Genre) && Track is null; + /// + /// Gets a value indicating whether this tag can store a field under a name the caller chooses. + /// + /// + /// + /// When this is false, returns no values and + /// and return false and change nothing. ID3v1 is such a tag: its + /// 128 bytes have no room for a name. + /// + /// + /// When this is true, the format still has its own rules for names and values, so + /// can return false for one name and true for another. + /// + /// + public virtual bool SupportsCustomFields => false; + + /// + /// Gets every value stored under a field name in this tag's native storage. + /// + /// The field name. How it is matched depends on the format (see remarks). + /// The values in file order. Empty when the tag holds no text under that name. + /// is null. + /// + /// + /// The name addresses the format's own key space, so a name that a mapped property also uses reads the + /// same data as that property. For example, "TITLE" on a Vorbis comment is the + /// field. + /// + /// + /// FormatWhere the field lives + /// Vorbis comment (FLAC, Ogg)A NAME=value field. Names are + /// case-insensitive. Each value is its own field. + /// APEv2A text item. Keys are case-insensitive. Values are + /// separated by U+0000. + /// ID3v2A TXXX frame whose description is the name. The + /// description is matched case-insensitively, as Id3v2Tag.GetUserText matches it. Values are + /// separated by U+0000. The name never addresses a standard frame such as TIT2. + /// MP4A freeform ---- atom with mean + /// com.apple.iTunes and the name as its name. Matched exactly. Each value is its own + /// data atom. + /// ASFAn Extended Content Description attribute, matched + /// case-insensitively; Title, Author, Copyright, Description, and + /// Rating are the Content Description fields. That holds the first value, and the others are + /// file-level records of the Metadata Library Object, as Windows writes them. + /// MatroskaA file-level SimpleTag at the level that + /// uses. Matched exactly. Each value is its own SimpleTag. + /// RIFF INFOA chunk whose four-character code is the name. One value. + /// + /// + /// A name the format keeps pictures under (see ) is not a custom field: it reads + /// no values and cannot be removed here. + /// + /// + public virtual IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return CustomFieldValues.None; + } + + /// + /// Replaces every value stored under a field name with . + /// + /// The field name. See for where each format stores it. + /// + /// The values in order. Null and empty values are skipped. When none remain, the field is removed. + /// + /// + /// True when the tag now holds exactly the remaining values under . + /// False when the tag cannot store them, and then the tag is unchanged. + /// + /// is null. + /// + /// The call returns false and stores nothing when: + /// + /// is false. + /// The name is empty or contains U+0000, or a value contains U+0000. + /// The name breaks the format's rules. Vorbis names are ASCII 0x20 to 0x7D without + /// =. APE keys are 2 to 255 ASCII characters from 0x20 to 0x7E and are not ID3, TAG, + /// OggS, or MP+. RIFF INFO names are four ASCII characters from 0x20 to 0x7E. + /// The name is where the format keeps pictures: METADATA_BLOCK_PICTURE in a + /// Vorbis comment, an APE key that starts with Cover Art, or ASF WM/Picture. Use + /// instead. + /// The format holds one value under the name and more were given (RIFF + /// INFO). + /// The value cannot be encoded: WAV RIFF INFO text outside ISO-8859-1 (AVI INFO takes any + /// text, and the save applies the file's CSET), or an ASF name or value longer than its 16-bit length + /// field. + /// The ASF file's Metadata or Metadata Library Object could not be parsed, so values + /// stored there would survive the write. + /// + /// + /// A name that a mapped property also uses is stored in the same place the property reads, not refused + /// and not duplicated. A property that parses its text (for example ) then reads the + /// new text the way it reads any other file. 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) when the file has only album tags, so "TITLE" there sets , and + /// prefers the segment title over a TITLE tag below the track level. + /// + /// + /// ID3v2.3 has no multiple-value text. The values are still separated by U+0000 there, as this library + /// writes every multiple-value frame; a reader that follows ID3v2.3 strictly shows only the first. + /// + /// + /// A file's Tag that combines several tags (MP3, raw AAC, AVI with an ID3v2 chunk, MPEG program + /// streams) writes the values into every tag that can store them and removes the name from a tag that + /// cannot, so no tag keeps an older value; it returns false, changing nothing, only when no tag can. + /// + /// + public virtual bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + return false; + } + + /// + /// Removes every value stored under a field name. + /// + /// The field name. See for how each format matches it. + /// True when the tag held a value under and no longer does. + /// is null. + public virtual bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return false; + } + /// /// Serializes the tag to its binary representation. /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs index f7072f5c..18b9c03c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs @@ -296,6 +296,12 @@ public BinaryData RenderContent () static List ParseNullSeparatedStrings (ReadOnlySpan data, TextEncodingType encoding) { + if (encoding == TextEncodingType.Utf16WithBom) { + // The shared splitter: each string's own BOM, the frame's first BOM for a string without one, and a + // final terminator or lone byte that ends the last string rather than adding one. + return Utf16Text.DecodeStrings (data); + } + var result = new List (); var terminatorSize = GetTerminatorSize (encoding); var current = 0; @@ -352,33 +358,11 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), - TextEncodingType.Utf16WithBom => DecodeUtf16WithBom (data), TextEncodingType.Utf16BE => System.Text.Encoding.BigEndianUnicode.GetString (data), _ => string.Empty }; } - static string DecodeUtf16WithBom (ReadOnlySpan data) - { - if (data.Length < 2) - return string.Empty; - - // Check BOM - var isLittleEndian = data[0] == 0xFF && data[1] == 0xFE; - var isBigEndian = data[0] == 0xFE && data[1] == 0xFF; - - if (!isLittleEndian && !isBigEndian) - return System.Text.Encoding.Unicode.GetString (data); // Default to LE if no BOM - - // Skip BOM and decode - var content = data.Slice (2); - var enc = isLittleEndian - ? System.Text.Encoding.Unicode - : System.Text.Encoding.BigEndianUnicode; - - return enc.GetString (content); - } - static BinaryData EncodeText (string text, TextEncodingType encoding) { return encoding switch { diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs index 552a8f6d..aaad333f 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -47,6 +47,13 @@ public TextFrame (string id, string text, TextEncodingType encoding = TextEncodi Encoding = encoding; } + /// + /// Where a UTF-16 text with several strings puts its BOMs. Set on read from the frame's own bytes, so an + /// unchanged frame renders the bytes it was read from; ID3v2.3 §3.3 (https://id3.org/id3v2.3.0) asks for a BOM + /// before every string. + /// + internal Utf16Layout Utf16Layout { get; set; } + /// /// Attempts to read a text frame from the provided data. /// @@ -66,9 +73,12 @@ public static TextFrameReadResult Read (string frameId, ReadOnlySpan data, var encoding = (TextEncodingType)encodingByte; var textData = data.Slice (1); - var text = DecodeText (textData, encoding); + var layout = Utf16Layout.OneBom; + var text = encoding == TextEncodingType.Utf16WithBom + ? Utf16Text.Decode (textData, out layout) + : DecodeText (textData, encoding); - var frame = new TextFrame (frameId, text, encoding); + var frame = new TextFrame (frameId, text, encoding) { Utf16Layout = layout }; return TextFrameReadResult.Success (frame, data.Length); } @@ -78,7 +88,9 @@ public static TextFrameReadResult Read (string frameId, ReadOnlySpan data, /// The frame content including encoding byte. public BinaryData RenderContent () { - var textBytes = EncodeText (Text, Encoding); + var textBytes = Encoding == TextEncodingType.Utf16WithBom + ? Utf16Text.Encode (Text, Utf16Layout) + : EncodeText (Text, Encoding); using var builder = new BinaryDataBuilder (1 + textBytes.Length); builder.Add ((byte)Encoding); @@ -143,7 +155,7 @@ static BinaryData EncodeText (string text, TextEncodingType encoding) return encoding switch { TextEncodingType.Latin1 => BinaryData.FromStringLatin1 (text), TextEncodingType.Utf8 => BinaryData.FromStringUtf8 (text), - TextEncodingType.Utf16WithBom => BinaryData.FromStringUtf16 (text, includeBom: true), + TextEncodingType.Utf16WithBom => Utf16Text.Encode (text, Utf16Layout.OneBom), TextEncodingType.Utf16BE => EncodeTextUtf16BE (text), _ => BinaryData.Empty }; diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs index dcf79d0c..51d7a216 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -51,6 +51,13 @@ public sealed class UserTextFrame /// public TextEncodingType Encoding { get; set; } + /// + /// Where a UTF-16 value with several strings puts its BOMs. Set on read from the frame's own bytes, so an + /// unchanged frame renders the bytes it was read from; ID3v2.3 §3.3 (https://id3.org/id3v2.3.0) asks for a BOM + /// before every string. + /// + internal Utf16Layout Utf16Layout { get; set; } + /// /// Initializes a new instance of the class. /// @@ -97,9 +104,12 @@ public static UserTextFrameReadResult Read (ReadOnlySpan data, Id3v2Versio var valueData = valueStart < contentData.Length ? contentData.Slice (valueStart) : ReadOnlySpan.Empty; - var value = DecodeText (valueData, encoding); + var layout = Utf16Layout.OneBom; + var value = encoding == TextEncodingType.Utf16WithBom + ? (valueData.IsEmpty ? string.Empty : Utf16Text.Decode (valueData, out layout)) + : DecodeText (valueData, encoding); - var frame = new UserTextFrame (description, value, encoding); + var frame = new UserTextFrame (description, value, encoding) { Utf16Layout = layout }; return UserTextFrameReadResult.Success (frame, data.Length); } @@ -111,7 +121,9 @@ public BinaryData RenderContent () { var descriptionBytes = EncodeText (Description, Encoding); var terminatorBytes = GetTerminatorBytes (Encoding); - var valueBytes = EncodeText (Value, Encoding); + var valueBytes = Encoding == TextEncodingType.Utf16WithBom + ? Utf16Text.Encode (Value, Utf16Layout) + : EncodeText (Value, Encoding); using var builder = new BinaryDataBuilder (1 + descriptionBytes.Length + terminatorBytes.Length + valueBytes.Length); builder.Add ((byte)Encoding); @@ -172,7 +184,7 @@ static BinaryData EncodeText (string text, TextEncodingType encoding) return encoding switch { TextEncodingType.Latin1 => BinaryData.FromStringLatin1 (text), TextEncodingType.Utf8 => BinaryData.FromStringUtf8 (text), - TextEncodingType.Utf16WithBom => BinaryData.FromStringUtf16 (text, includeBom: true), + TextEncodingType.Utf16WithBom => Utf16Text.Encode (text, Utf16Layout.OneBom), TextEncodingType.Utf16BE => new BinaryData (System.Text.Encoding.BigEndianUnicode.GetBytes (text)), _ => BinaryData.Empty }; diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/Utf16Text.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/Utf16Text.cs new file mode 100644 index 00000000..e4f0e0af --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/Utf16Text.cs @@ -0,0 +1,343 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers; +using System.Text; + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Id3.Id3v2.Frames; + +/// +/// Where a UTF-16 value with several strings puts the byte order marks of its later strings. +/// +internal enum Utf16BomPlacement : byte +{ + /// One BOM at the start of the value only. + OneBom, + + /// A BOM before every non-empty string. An empty string has none. + BomOnNonEmpty, + + /// A BOM before every string, empty ones included (ID3v2.3 §3.3, and the layout mutagen writes). + BomOnEvery, +} + +/// +/// The bytes of a UTF-16 value that its text does not hold: where its BOMs are, and how many terminators end it. +/// A frame read from a file keeps its layout, so an unchanged frame renders the bytes it was read from. +/// +internal readonly struct Utf16Layout : IEquatable +{ + // Two bytes, so a frame that holds a layout is no larger than one that held a placement alone. + readonly byte _terminators; + + public Utf16Layout (Utf16BomPlacement boms, int terminators) + { + Boms = boms; + _terminators = (byte)Math.Min (terminators, byte.MaxValue); + } + + public Utf16BomPlacement Boms { get; } + + /// The 00 00 pairs after the last string, up to 255. They are not text. + public int Terminators => _terminators; + + public static Utf16Layout OneBom => default; + + public static Utf16Layout BomOnNonEmpty => new (Utf16BomPlacement.BomOnNonEmpty, 0); + + public static Utf16Layout BomOnEvery => new (Utf16BomPlacement.BomOnEvery, 0); + + public bool Equals (Utf16Layout other) => Boms == other.Boms && Terminators == other.Terminators; + + public override bool Equals (object? obj) => obj is Utf16Layout other && Equals (other); + + public override int GetHashCode () => ((int)Boms * 397) ^ Terminators; + + public static bool operator == (Utf16Layout left, Utf16Layout right) => left.Equals (right); + + public static bool operator != (Utf16Layout left, Utf16Layout right) => !left.Equals (right); +} + +/// +/// The one decoder for encoding $01, "UTF-16 encoded Unicode with BOM" (https://id3.org/id3v2.4.0-structure §4). +/// +/// +/// +/// A value with several strings separates them with 00 00 on an even offset. Each string may begin with its own +/// BOM: ID3v2.3 §3.3 says "Unicode strings must begin with the Unicode BOM" (https://id3.org/id3v2.3.0), and +/// ID3v2.4 §4 says all strings in a frame share one byte order. A BOM is never part of the text. A string without +/// one uses the frame's first BOM, wherever it is, or little-endian when the frame has none. +/// +/// +/// A lone byte at the end is not a code unit and is dropped, so it cannot take the last character with it. The +/// 00 00 pairs after the last string are terminators, not an empty value. In , a lone +/// byte right after a terminator still starts an empty last string. +/// +/// +/// runs one code path on every target framework, so the +/// tests that run it on net8.0 and net10.0 also cover the netstandard2.0 build. It decodes into pooled buffers; the +/// only allocation is the result. decodes each string with +/// Encoding.GetString, which on netstandard2.0 copies the span to an array first. +/// +/// +internal static class Utf16Text +{ + /// + /// Decodes every string and joins them with U+0000. + /// + public static string Decode (ReadOnlySpan data) => Decode (data, out _); + + /// + /// The encoded text. + /// Where the value puts its BOMs and how many terminators end it. + public static string Decode (ReadOnlySpan data, out Utf16Layout layout) + { + data = WithoutLoneByte (data); + var terminators = 0; + while (data.Length >= 2 && data[data.Length - 2] == 0 && data[data.Length - 1] == 0) { + data = data.Slice (0, data.Length - 2); + terminators++; + } + + if (data.IsEmpty) { + layout = new Utf16Layout (Utf16BomPlacement.OneBom, terminators); + return string.Empty; + } + + var stats = new LayoutStats (); + var text = DecodeJoined (data, ref stats); + layout = new Utf16Layout (stats.Placement, terminators); + return text; + } + + /// + /// Splits the value into its strings, each decoded as decodes it. + /// + /// + /// One entry per string. A final terminator ends the last string and adds no entry; an empty string between + /// two terminators is kept. Data shorter than two bytes is one empty string. + /// + public static List DecodeStrings (ReadOnlySpan data) + { + // A lone last byte is never text, but after a terminator it starts one more string, an empty one, so the + // role before it still pairs (as the TIPL reader of the trailing-NUL fix reads it). + var loneByte = (data.Length & 1) != 0; + data = WithoutLoneByte (data); + var strings = new List (); + var littleEndian = FrameIsLittleEndian (data); + var start = 0; + while (true) { + var end = NextTerminator (data, start); + var segment = end < 0 ? data.Slice (start) : data.Slice (start, end - start); + if (end >= 0 || !segment.IsEmpty || start == 0 || loneByte) + strings.Add (DecodeSegment (segment, littleEndian)); + if (end < 0) + return strings; + start = end + 2; + } + } + + /// + /// Encodes little-endian with a BOM at the start, BOMs on later strings as says, + /// and its terminators after the last string. + /// + /// The text; U+0000 separates strings. + /// Where to put the BOMs of later strings, and how many terminators to write. + public static BinaryData Encode (string text, Utf16Layout layout) + { + var terminators = layout.Terminators; + if (terminators == 0 && (!HasSeparator (text) || layout.Boms == Utf16BomPlacement.OneBom && !LaterStringStartsLikeBom (text))) + return BinaryData.FromStringUtf16 (text, includeBom: true); + + // A BOM for the first string, one for each later string that gets one, two bytes per char (a separator is + // one char, 00 00), and the terminators. + var boms = 1; + for (var i = 0; i < text.Length; i++) { + if (text[i] == '\0' && WantsBom (layout.Boms, text, i + 1)) + boms++; + } + + var bytes = new byte[(boms + text.Length + terminators) * 2]; + bytes[0] = 0xFF; + bytes[1] = 0xFE; + var at = 2; + for (var i = 0; i < text.Length; i++) { + var c = text[i]; + bytes[at++] = (byte)c; + bytes[at++] = (byte)(c >> 8); + if (c == '\0' && WantsBom (layout.Boms, text, i + 1)) { + bytes[at++] = 0xFF; + bytes[at++] = 0xFE; + } + } + // The rest of the array is already zero: the terminators. + return new BinaryData (bytes); + } + + /// + /// Whether the string that starts at gets a BOM. A string whose text begins with + /// U+FEFF or U+FFFE always gets one; without it, a reader takes that char for the string's BOM. + /// + static bool WantsBom (Utf16BomPlacement placement, string text, int start) + { + if (StartsLikeBom (text, start)) + return true; + var stringIsEmpty = start == text.Length || text[start] == '\0'; + return placement == Utf16BomPlacement.BomOnEvery || (!stringIsEmpty && placement == Utf16BomPlacement.BomOnNonEmpty); + } + + static bool StartsLikeBom (string text, int start) => + start < text.Length && text[start] is '\uFEFF' or '\uFFFE'; + + static bool LaterStringStartsLikeBom (string text) + { + for (var i = 0; i < text.Length; i++) { + if (text[i] == '\0' && StartsLikeBom (text, i + 1)) + return true; + } + return false; + } + + static bool HasSeparator (string text) + { + foreach (var c in text) { + if (c == '\0') + return true; + } + return false; + } + + /// + /// A lone byte at the end is not a UTF-16 code unit. Pairing it with the byte before would eat the last + /// character, so it is dropped. + /// + static ReadOnlySpan WithoutLoneByte (ReadOnlySpan data) => + (data.Length & 1) != 0 ? data.Slice (0, data.Length - 1) : data; + + /// + /// The offset of the next 00 00 at an even offset from the start of the value, or -1. + /// + static int NextTerminator (ReadOnlySpan data, int start) + { + for (var i = start; i + 1 < data.Length; i += 2) { + if (data[i] == 0 && data[i + 1] == 0) + return i; + } + return -1; + } + + static bool HasBom (ReadOnlySpan data) => + data.Length >= 2 && ((data[0] == 0xFF && data[1] == 0xFE) || (data[0] == 0xFE && data[1] == 0xFF)); + + /// + /// The byte order of the frame's first BOM at the start of any string, or little-endian when there is none. + /// + static bool FrameIsLittleEndian (ReadOnlySpan data) + { + var start = 0; + while (start + 1 < data.Length) { + if (HasBom (data.Slice (start))) + return data[start] == 0xFF; + var end = NextTerminator (data, start); + if (end < 0) + break; + start = end + 2; + } + return true; + } + + /// + /// Decodes every string of into one string, the strings separated by U+0000. + /// + static string DecodeJoined (ReadOnlySpan data, ref LayoutStats stats) + { + var frameLittleEndian = FrameIsLittleEndian (data); + + // Every byte pair is at most one char, and every separator is one char. + var bytes = ArrayPool.Shared.Rent (data.Length); + var chars = ArrayPool.Shared.Rent (data.Length / 2 + 1); + try { + data.CopyTo (bytes); + var length = 0; + var start = 0; + while (true) { + var end = NextTerminator (data, start); + var segmentLength = (end < 0 ? data.Length : end) - start; + var segment = data.Slice (start, segmentLength); + if (start > 0) + chars[length++] = '\0'; + stats.Count (start > 0, segment); + + var littleEndian = frameLittleEndian; + var offset = start; + if (HasBom (segment)) { + littleEndian = segment[0] == 0xFF; + offset += 2; + segmentLength -= 2; + } + if (segmentLength > 0) { + var encoding = littleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode; + length += encoding.GetChars (bytes, offset, segmentLength, chars, length); + } + + if (end < 0) + break; + start = end + 2; + } + return new string (chars, 0, length); + } finally { + ArrayPool.Shared.Return (chars); + ArrayPool.Shared.Return (bytes); + } + } + + static string DecodeSegment (ReadOnlySpan segment, bool frameLittleEndian) + { + var littleEndian = frameLittleEndian; + if (HasBom (segment)) { + littleEndian = segment[0] == 0xFF; + segment = segment.Slice (2); + } + if (segment.IsEmpty) + return string.Empty; + return (littleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode).GetString (segment); + } + + /// + /// Counts which strings after the first carry a BOM, to name the value's . + /// + struct LayoutStats + { + int _nonEmpty; + int _nonEmptyWithBom; + int _empty; + int _emptyWithBom; + + public void Count (bool later, ReadOnlySpan segment) + { + if (!later) + return; + var hasBom = HasBom (segment); + if (segment.Length > (hasBom ? 2 : 0)) { + _nonEmpty++; + if (hasBom) + _nonEmptyWithBom++; + } else { + _empty++; + if (hasBom) + _emptyWithBom++; + } + } + + public readonly Utf16BomPlacement Placement { + get { + var everyEmptyHasBom = _empty > 0 && _emptyWithBom == _empty; + if (_nonEmpty > 0 && _nonEmptyWithBom == _nonEmpty) + return everyEmptyHasBom ? Utf16BomPlacement.BomOnEvery : Utf16BomPlacement.BomOnNonEmpty; + return _nonEmpty == 0 && everyEmptyHasBom ? Utf16BomPlacement.BomOnEvery : Utf16BomPlacement.OneBom; + } + } + } +} diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs index 355bf695..dc927aa2 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -51,72 +51,8 @@ internal static ReadOnlySpan CutAtFirstNul (ReadOnlySpan data, TextE /// Decodes UTF-16 text. Each NUL-separated value may start with its own BOM. /// A value with no BOM uses the frame's first BOM, or little-endian when there is none. /// - internal static string DecodeUtf16BomText (ReadOnlySpan data) - { - data = TrimTrailingTerminator (data, TextEncodingType.Utf16WithBom); - if (data.IsEmpty) - return string.Empty; - - var littleEndian = FrameIsLittleEndian (data); - if (IndexOfUtf16Nul (data) < 0) - return DecodeOneUtf16Value (data, littleEndian); - - var parts = new List (); - var start = 0; - for (var i = 0; i + 1 < data.Length; i += 2) { - if (data[i] != 0 || data[i + 1] != 0) - continue; - - parts.Add (DecodeOneUtf16Value (data.Slice (start, i - start), littleEndian)); - start = i + 2; - } - - parts.Add (DecodeOneUtf16Value (data.Slice (start), littleEndian)); - return parts.Count == 1 ? parts[0] : string.Join ("\0", parts); - } - - static bool FrameIsLittleEndian (ReadOnlySpan data) - { - var start = 0; - while (start + 1 < data.Length) { - if (data[start] == 0xFF && data[start + 1] == 0xFE) - return true; - if (data[start] == 0xFE && data[start + 1] == 0xFF) - return false; - - var rel = IndexOfUtf16Nul (data.Slice (start)); - if (rel < 0) - break; - start += rel + 2; - } - - return true; - } - - static string DecodeOneUtf16Value (ReadOnlySpan data, bool fallbackLittleEndian) - { - if (data.IsEmpty) - return string.Empty; - - var littleEndian = fallbackLittleEndian; - if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE) { - littleEndian = true; - data = data.Slice (2); - } else if (data.Length >= 2 && data[0] == 0xFE && data[1] == 0xFF) { - littleEndian = false; - data = data.Slice (2); - } - - if (data.IsEmpty) - return string.Empty; - - var encoding = littleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode; -#if NETSTANDARD2_0 - return encoding.GetString (data.ToArray ()); -#else - return encoding.GetString (data); -#endif - } + /// The one UTF-16 decoder, , does the work. + internal static string DecodeUtf16BomText (ReadOnlySpan data) => Frames.Utf16Text.Decode (data); static int IndexOfUtf16Nul (ReadOnlySpan data) { diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 57e2b6d4..2bdc16e9 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -2080,41 +2080,21 @@ BinaryData RenderFrameHeader (string frameId, int contentSize) /// Empty means no frames of any kind are stored, including lyrics, ratings, /// pictures, and private frames. The base check only looks at the standard fields. /// - public override bool IsEmpty => - _frames.Count == 0 - && _pictures.Count == 0 - && _comments.Count == 0 - && _userTextFrames.Count == 0 - && _lyricsFrames.Count == 0 - && _uniqueFileIdFrames.Count == 0 - && _involvedPeopleFrames.Count == 0 - && _popularimeterFrames.Count == 0 - && _urlFrames.Count == 0 - && _userUrlFrames.Count == 0 - && _syncLyricsFrames.Count == 0 - && _generalObjectFrames.Count == 0 - && _privateFrames.Count == 0 - && _chapterFrames.Count == 0 - && _tableOfContentsFrames.Count == 0; + public override bool IsEmpty { + get { + foreach (var list in FrameLists) { + if (list.Count > 0) + return false; + } + return true; + } + } /// public override void Clear () { - _frames.Clear (); - _pictures.Clear (); - _comments.Clear (); - _userTextFrames.Clear (); - _lyricsFrames.Clear (); - _uniqueFileIdFrames.Clear (); - _involvedPeopleFrames.Clear (); - _popularimeterFrames.Clear (); - _urlFrames.Clear (); - _userUrlFrames.Clear (); - _syncLyricsFrames.Clear (); - _generalObjectFrames.Clear (); - _privateFrames.Clear (); - _chapterFrames.Clear (); - _tableOfContentsFrames.Clear (); + foreach (var list in FrameLists) + list.Clear (); InvalidatePerformersRoleCache (); } @@ -2277,6 +2257,84 @@ public void RemoveUserTextFrames (string description) string.Equals (f.Description, description, StringComparison.OrdinalIgnoreCase)); } + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// Reads every TXXX frame whose description matches ignoring case, the + /// same rule and the mapped properties use, so "MOOD" and "Mood" + /// are one field. The spec allows one TXXX per description (https://id3.org/id3v2.4.0-frames + /// §4.2.6). The value is split at U+0000, the ID3v2.4 separator for multiple strings + /// (https://id3.org/id3v2.4.0-structure §4). + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name)) + return CustomFieldValues.None; + + var values = new List (); + for (var i = 0; i < _userTextFrames.Count; i++) { + if (string.Equals (_userTextFrames[i].Description, name, StringComparison.OrdinalIgnoreCase)) + CustomFieldValues.AddSplit (_userTextFrames[i].Value, values); + } + return values; + } + + /// + /// + /// + /// Replaces every TXXX frame whose description matches ignoring case, as + /// does, by one frame with as its description, kept at the position of the first (https://id3.org/id3v2.4.0-frames §4.2.6). The values are joined with U+0000 + /// (https://id3.org/id3v2.4.0-structure §4). + /// + /// + /// An ID3v2.4 tag writes UTF-8. An older tag writes UTF-16 with a byte order mark, because ID3v2.3 + /// defines only ISO-8859-1 and UCS-2 text (https://id3.org/id3v2.3.0 §3.3). ID3v2.3 has no multiple-value + /// text: a reader that follows it strictly shows only the first value. + /// + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + + var at = _userTextFrames.FindIndex (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)); + _userTextFrames.RemoveAll (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)); + if (kept.Count == 0) + return true; + + var encoding = Version >= 4 ? TextEncodingType.Utf8 : TextEncodingType.Utf16WithBom; + // ID3v2.3 §3.3: every Unicode string begins with a BOM. + var frame = new UserTextFrame (name, string.Join ("\0", kept), encoding) { Utf16Layout = Utf16Layout.BomOnEvery }; + _userTextFrames.Insert (at < 0 ? _userTextFrames.Count : at, frame); + return true; + } + + /// + /// Removes every TXXX frame whose description matches ignoring case. + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name)) + return false; + return _userTextFrames.RemoveAll (f => string.Equals (f.Description, name, StringComparison.OrdinalIgnoreCase)) > 0; + } + + System.Collections.IList[]? _frameLists; + + /// + /// Every list of frames this tag holds, the one source and read. + /// A new frame list belongs here, or a container may drop a tag that holds only that kind of frame. + /// + System.Collections.IList[] FrameLists => _frameLists ??= [ + _frames, _pictures, _comments, _userTextFrames, _lyricsFrames, _uniqueFileIdFrames, + _involvedPeopleFrames, _popularimeterFrames, _urlFrames, _userUrlFrames, _syncLyricsFrames, + _generalObjectFrames, _privateFrames, _chapterFrames, _tableOfContentsFrames, + ]; + /// /// Gets the first lyrics with an empty description, or the first lyrics if none have empty description. /// diff --git a/src/TagLibSharp2/Matroska/MatroskaTag.cs b/src/TagLibSharp2/Matroska/MatroskaTag.cs index 8772fcef..e78eaedb 100644 --- a/src/TagLibSharp2/Matroska/MatroskaTag.cs +++ b/src/TagLibSharp2/Matroska/MatroskaTag.cs @@ -433,6 +433,67 @@ public override void Clear () /// Gets a value indicating whether was set or cleared since reading. internal bool PicturesChanged => _picturesChanged; + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// Reads the file-level SimpleTag elements whose TagName equals + /// exactly, the way reads COMMENT: the nearest level at or above the item + /// level that sets the name wins (RFC 9559 §5.1.8.1.1 and https://www.matroska.org/technical/tagging.html). + /// A tag with only TagBinary has no text and is skipped. + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return CustomFieldValues.IsUsableName (name) ? All (name) : CustomFieldValues.None; + } + + /// + /// + /// Writes one SimpleTag per value at the item level, the level and + /// write. Matroska allows a name to repeat (https://www.matroska.org/technical/tagging.html). + /// The same name at a broader level stays and is shadowed, as the format defines. The item level is the + /// most specific file-level target in the file, or 50 (album) when there is none, so on a file with + /// only album tags "TITLE" writes the album title; still prefers the segment + /// title there. + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + + if (kept.Count == 0) { + RemoveCustomField (name); + return true; + } + + SetItemValues (name, [.. kept]); + return true; + } + + /// + /// + /// Removes the name at every file level the getter can climb to, so a broader value does not show + /// through afterwards. + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name)) + return false; + + var item = ItemLevel; + var removed = false; + foreach (var block in _blocks) { + if (!block.IsFileLevel || block.Level < item) + continue; + removed |= block.Tags.RemoveAll (tag => tag.Name == name) > 0; + } + return removed; + } + internal void AddPicture (IPicture picture) => _pictures.Add (picture); /// diff --git a/src/TagLibSharp2/Mp4/Mp4Tag.cs b/src/TagLibSharp2/Mp4/Mp4Tag.cs index f2005b60..5ee8bca6 100644 --- a/src/TagLibSharp2/Mp4/Mp4Tag.cs +++ b/src/TagLibSharp2/Mp4/Mp4Tag.cs @@ -936,6 +936,71 @@ void RemoveAtom (string atomId) DropPreserved (atomId); } + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// Reads the freeform ---- field whose mean is com.apple.iTunes and whose name + /// equals exactly, in the iTunes ilst or a QuickTime mdta meta. Each + /// data atom of type 1 (UTF-8) or type 0 (implicit, read as UTF-8 as + /// reads it) is one value; other types are not text (Apple, QuickTime File Format, "Well-known types"). The name + /// is the whole name: "a:b" is a name with a colon, not a mean and a name. Use + /// for another mean. + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name) || FindFreeform (Mp4AtomMapping.AppleNamespace, name) is not { } field) + return CustomFieldValues.None; + + var values = new List (field.Atoms.Count); + foreach (var dataAtom in field.Atoms) { + if (dataAtom.TypeIndicator is not (Mp4AtomMapping.TypeBinary or Mp4AtomMapping.TypeUtf8)) + continue; + var text = dataAtom.ToUtf8String (); + if (!string.IsNullOrEmpty (text)) + values.Add (text!); + } + return values; + } + + /// + /// + /// Writes one freeform ---- field with mean com.apple.iTunes, name + /// , and one UTF-8 data atom per value, the layout iTunes uses for its own + /// com.apple.iTunes names. It goes where the tag's freeform properties go: the iTunes ilst, or the + /// keyed mdta meta the tag was read from, and replaces every item the name was read from. + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + + var dataAtoms = new List (kept.Count); + foreach (var value in kept) + dataAtoms.Add (new Mp4DataAtom (Mp4AtomMapping.TypeUtf8, BinaryData.FromStringUtf8 (value))); + SetFreeformAtoms (Mp4AtomMapping.AppleNamespace, name, dataAtoms); + return true; + } + + /// + /// Removes the field and every item it was read from, in either meta. + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!CustomFieldValues.IsUsableName (name)) + return false; + + const string mean = Mp4AtomMapping.AppleNamespace; + var held = FindFreeform (mean, name) is not null || + _preservedFreeformByKey.ContainsKey ((mean, name)) || + _sources.ContainsKey (FreeformId (mean, name)); + SetFreeformAtoms (mean, name, new List ()); + return held; + } + /// /// /// Removes all metadata the tag holds: every field, every item it was read from, and every item diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs index 02c2c439..abea160b 100644 --- a/src/TagLibSharp2/Riff/RiffInfoTag.cs +++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs @@ -268,6 +268,66 @@ public void SetField (string fourCC, string? value) } } + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// The name is the four-character code of an INFO subchunk, such as IENG or a code of your own. + /// Codes compare case-insensitively, as compares them. An INFO subchunk holds one + /// ZSTR (Microsoft RIFF specification, "INFO List Chunk"), so there is at most one value. + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsFourCC (name)) + return CustomFieldValues.None; + var value = GetField (name); + return string.IsNullOrEmpty (value) ? CustomFieldValues.None : [value!]; + } + + /// + /// + /// Returns false for a name that is not four ASCII characters from 0x20 to 0x7E (a FOURCC, Microsoft + /// RIFF specification, "Chunks") and for more than one value. A WAV INFO list is Latin-1, one byte per + /// character, so text outside ISO-8859-1 is refused there. An AVI INFO list takes any text, as the mapped + /// fields do: the save encodes it in the file's declared code page when every changed value fits, and + /// otherwise makes the list UTF-8 under a CSET of code page 65001 (see ). + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsFourCC (name) || !CustomFieldValues.TryNormalize (values, out var kept) || kept.Count > 1) + return false; + if (_stored is null && kept.Count == 1) { + foreach (var c in kept[0]) { + if (c > 0xFF) + return false; + } + } + + SetField (name, kept.Count == 0 ? null : kept[0]); + return true; + } + + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return IsFourCC (name) && _fields.Remove (name); + } + + static bool IsFourCC (string name) + { + if (name.Length != 4) + return false; + foreach (var c in name) { + if (c < 0x20 || c > 0x7E) + return false; + } + return true; + } + /// /// Gets all field identifiers present in this tag. /// diff --git a/src/TagLibSharp2/Xiph/FlacTag.cs b/src/TagLibSharp2/Xiph/FlacTag.cs index ce6e7bd8..7ef09c8c 100644 --- a/src/TagLibSharp2/Xiph/FlacTag.cs +++ b/src/TagLibSharp2/Xiph/FlacTag.cs @@ -505,6 +505,43 @@ public override string[]? PerformersRole { VorbisComment EnsureVorbisComment () => _file.VorbisComment ??= new VorbisComment ("TagLibSharp2"); + /// + public override bool SupportsCustomFields => true; + + /// + /// Reads the VORBIS_COMMENT block (RFC 9639 §8.6). + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return _file.VorbisComment?.GetCustomField (name) ?? CustomFieldValues.None; + } + + /// + /// + /// Writes the VORBIS_COMMENT block (RFC 9639 §8.6). The block is created only when the field is stored, + /// so a refused name does not add an empty block to the file. + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (_file.VorbisComment is { } existing) + return existing.SetCustomField (name, values); + + var created = new VorbisComment ("TagLibSharp2"); + if (!created.SetCustomField (name, values)) + return false; + if (created.Fields.Count > 0) + _file.VorbisComment = created; + return true; + } + + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + return _file.VorbisComment?.RemoveCustomField (name) ?? false; + } + /// #pragma warning disable CA1819 // Properties should not return arrays - Tag API contract public override IPicture[] Pictures { diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 8107a795..92105220 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -1066,6 +1066,78 @@ public void RemoveAll (string name) _fields.RemoveAll (f => f.Name == upperName); } + /// + public override bool SupportsCustomFields => true; + + /// + /// + /// Each value is one NAME=value field. Names compare case-insensitively and are written in upper + /// case (https://xiph.org/vorbis/doc/v-comment.html, "Field names"). + /// + public override IReadOnlyList GetCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name)) + return CustomFieldValues.None; + + var upperName = name.ToUpperInvariant (); + var values = new List (); + for (var i = 0; i < _fields.Count; i++) { + if (_fields[i].Name == upperName && _fields[i].Value.Length > 0) + values.Add (_fields[i].Value); + } + return values; + } + + /// + /// + /// The spec allows a name to repeat, so each value is written as its own field + /// (https://xiph.org/vorbis/doc/v-comment.html, "Field names"). The new fields take the place of the + /// first old one, so the order of other fields is kept. + /// + public override bool SetCustomField (string name, params string[] values) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) + return false; + + var upperName = name.ToUpperInvariant (); + var at = _fields.FindIndex (f => f.Name == upperName); + _fields.RemoveAll (f => f.Name == upperName); + if (at < 0) + at = _fields.Count; + for (var i = 0; i < kept.Count; i++) + _fields.Insert (at + i, new VorbisCommentField (upperName, kept[i])); + return true; + } + + /// + public override bool RemoveCustomField (string name) + { + CustomFieldValues.ThrowIfNull (name); + if (!IsCustomFieldName (name)) + return false; + + var upperName = name.ToUpperInvariant (); + return _fields.RemoveAll (f => f.Name == upperName) > 0; + } + + /// + /// A field name is ASCII 0x20 through 0x7D without '=' (https://xiph.org/vorbis/doc/v-comment.html). + /// METADATA_BLOCK_PICTURE is excluded because owns it + /// (https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE). + /// + static bool IsCustomFieldName (string name) + { + if (name.Length == 0) + return false; + foreach (var c in name) { + if (c < 0x20 || c > 0x7D || c == '=') + return false; + } + return !string.Equals (name, MetadataBlockPictureField, StringComparison.OrdinalIgnoreCase); + } + /// public override void Clear () { diff --git a/tests/TagLibSharp2.Tests/Aiff/AiffFileRoundTripTests.cs b/tests/TagLibSharp2.Tests/Aiff/AiffFileRoundTripTests.cs index d52df6d9..8a1a1eff 100644 --- a/tests/TagLibSharp2.Tests/Aiff/AiffFileRoundTripTests.cs +++ b/tests/TagLibSharp2.Tests/Aiff/AiffFileRoundTripTests.cs @@ -263,4 +263,15 @@ public void ReplayGain_SurvivesRoundTrip () Assert.AreEqual ("-7.25 dB", reloaded.Tag.ReplayGainAlbumGain); Assert.AreEqual ("1.0", reloaded.Tag.ReplayGainAlbumPeak); } + + [TestMethod] + public void Id3TagWithOnlyAlbumArtist_IsWritten () + { + Assert.IsTrue (AiffFile.TryRead (CreateMinimalAiff (), out var file)); + file!.Id3v2Tag = new Id3v2Tag { AlbumArtist = "Various" }; + + Assert.IsTrue (AiffFile.TryRead (file.Render (), out var reloaded)); + + Assert.AreEqual ("Various", reloaded!.Id3v2Tag?.AlbumArtist); + } } diff --git a/tests/TagLibSharp2.Tests/Ape/ApeKeyRulesTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeKeyRulesTests.cs new file mode 100644 index 00000000..ec70e3c3 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeKeyRulesTests.cs @@ -0,0 +1,103 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Ape; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// Every entry point applies the same APEv2 key rules (https://wiki.hydrogenaud.io/index.php?title=APE_key): +/// creating an item, parsing one, and the custom field API. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public class ApeKeyRulesTests +{ + [TestMethod] + [DataRow ("AB", true)] + [DataRow ("A", false)] + [DataRow ("", false)] + [DataRow ("Title", true)] + [DataRow ("ID3", false)] + [DataRow ("tag", false)] + [DataRow ("OGGS", false)] + [DataRow ("mp+", false)] + [DataRow ("ID3X", true)] + [DataRow ("Tab\tKey", false)] + [DataRow ("Tilde~", true)] + [DataRow ("Del\u007F", false)] + [DataRow ("Café", false)] + public void KeyRules_AgreeAcrossEntryPoints (string key, bool valid) + { + Assert.AreEqual (valid, ApeTagItem.IsValidKey (key)); + Assert.AreEqual (valid, TryCreate (key)); + Assert.AreEqual (valid, new ApeTag ().SetCustomField (key, "v")); + Assert.AreEqual (valid, ApeTagItem.Parse (RawItem (Encoding.Latin1.GetBytes (key))).IsSuccess); + Assert.AreEqual (valid, Measures (RawItem (Encoding.Latin1.GetBytes (key)))); + if (valid) + AssertCustomFieldRoundTrips (key); + } + + [TestMethod] + public void KeyRules_LengthBoundsAgreeAcrossEntryPoints () + { + foreach (var (length, valid) in new[] { (255, true), (256, false) }) { + var key = new string ('K', length); + Assert.AreEqual (valid, ApeTagItem.IsValidKey (key)); + Assert.AreEqual (valid, TryCreate (key)); + Assert.AreEqual (valid, ApeTagItem.Parse (RawItem (Encoding.ASCII.GetBytes (key))).IsSuccess); + Assert.AreEqual (valid, Measures (RawItem (Encoding.ASCII.GetBytes (key)))); + Assert.AreEqual (valid, new ApeTag ().SetCustomField (key, "v")); + if (valid) + AssertCustomFieldRoundTrips (key); + } + } + + /// The non-copying item check a tag placement uses, from its window only. + static bool Measures (byte[] item) => + ApeTagItem.TryMeasure (item.AsSpan (0, Math.Min (item.Length, ApeTagItem.MeasureWindow)), item.Length, out _); + + /// + /// A field SetCustomField accepts renders as an item that the measure and the tag parser accept, and reads back. + /// + static void AssertCustomFieldRoundTrips (string key) + { + var tag = new ApeTag (); + Assert.IsTrue (tag.SetCustomField (key, "v1", "v2")); + var rendered = tag.Render ().ToArray (); + + var parsed = ApeTag.Parse (rendered); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + CollectionAssert.AreEqual (V1V2, parsed.Tag!.GetCustomField (key).ToArray ()); + + // Render writes the one item and a 32-byte footer (APEv2 tag layout, no header). + var items = rendered.AsSpan (0, rendered.Length - 32); + Assert.IsTrue (ApeTagItem.TryMeasure (items[..Math.Min (items.Length, ApeTagItem.MeasureWindow)], items.Length, out var consumed), + $"the measure refuses the item SetCustomField wrote for '{key}'"); + Assert.AreEqual (items.Length, consumed); + } + + static readonly string[] V1V2 = ["v1", "v2"]; + + static bool TryCreate (string key) + { + try { + ApeTagItem.CreateText (key, "v"); + return true; + } catch (ArgumentException) { + return false; + } + } + + static byte[] RawItem (byte[] key) + { + var item = new byte[8 + key.Length + 1 + 1]; + BinaryPrimitives.WriteUInt32LittleEndian (item, 1); + key.CopyTo (item, 8); + item[^1] = (byte)'v'; + return item; + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfClearTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfClearTests.cs new file mode 100644 index 00000000..11d37bc1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfClearTests.cs @@ -0,0 +1,242 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Reflection; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mp4; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// Null always clears (the rule of Tag.IsWriteBack): only a write-back of the exact value read is a no-op. +/// A stored value the getter cannot read, such as the DWORD year mutagen writes for f['WM/Year'] = [2020], is +/// removed by = null, together with the attribute's Metadata Library values, as before the write-back rule. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfClearTests +{ + static readonly string[] EmptyFirstSecond = ["", "First", "Second"]; + static readonly string[] ContentDescriptionProperties = ["Title", "Artist", "Copyright", "Comment", "Rating"]; + + static IEnumerable ScalarProperties () => + typeof (AsfTag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0) + .Where (p => p.PropertyType == typeof (string) || p.PropertyType == typeof (uint?)) + .Where (p => !ContentDescriptionProperties.Contains (p.Name)) + .OrderBy (p => p.Name, StringComparer.Ordinal); + + public static IEnumerable ScalarNames => ScalarProperties ().Select (p => new object[] { p.Name }); + + /// The one Extended Content Description attribute a property writes, or null when it maps none. + static string? AttributeOf (PropertyInfo property) + { + var probe = new AsfTag (); + property.SetValue (probe, property.PropertyType == typeof (string) ? "-512" : (object)(uint?)3); + return probe.ExtendedContentDescription.Descriptors.Count == 1 + ? probe.ExtendedContentDescription.Descriptors[0].Name + : null; + } + + /// + /// A stored type the property's getter does not read: a DWORD for a string attribute and for the disc + /// "n/m" string, a WORD for a number attribute. + /// + static AsfDescriptor Unreadable (PropertyInfo property, string attribute) => + property.PropertyType == typeof (string) || attribute == "WM/PartOfSet" + ? AsfDescriptor.CreateDword (attribute, 2020) + : AsfDescriptor.CreateWord (attribute, 5); + + static byte[] File (AsfDescriptor? stored, string attribute, string? contentTitle = null) => + [.. AsfTestBuilder.CreateHeaderObject ([ + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfTestBuilder.CreateContentDescriptionObject (contentTitle, null), + AsfMetadataLibraryTests.HeaderExtension (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.Record (attribute, "second"))), + .. stored is null ? Array.Empty () : [AsfTestBuilder.CreateExtendedContentDescriptionObject (stored)], + ]), .. AsfTestBuilder.CreateDataObject (0)]; + + static AsfFile Read (byte[] data) + { + var result = AsfFile.Read (data); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.File!; + } + + [TestMethod] + [DynamicData (nameof (ScalarNames))] + public void NullOverAnUnreadableValue_ClearsItAndTheLibraryValues (string property) + { + var p = typeof (AsfTag).GetProperty (property)!; + var attribute = AttributeOf (p); + if (attribute is null) + return; // ASF maps no attribute for this property. + var original = File (Unreadable (p, attribute), attribute); + var file = Read (original); + // The getter cannot read the stored DWORD or WORD; it reads the library's string value, or nothing. + Assert.IsTrue (p.GetValue (file.Tag) is null or "" or "second", $"{property} should not read the {attribute} it cannot parse"); + Assert.AreEqual (2, file.Tag.GetCustomField (attribute).Count, "the fixture holds two values"); + + p.SetValue (file.Tag, null); + var again = Read (file.Render (original)).Tag; + + Assert.IsFalse (again.ExtendedContentDescription.Descriptors.Any (d => d.Name == attribute), $"{property} = null kept {attribute}"); + Assert.AreEqual (0, again.GetCustomField (attribute).Count, $"{property} = null kept a value of {attribute}"); + } + + [TestMethod] + public void NullOverAnUnreadableValue_CoversTheMappedAttributes () + { + var covered = ScalarProperties ().Where (p => AttributeOf (p) is not null).Select (p => p.Name).ToList (); + + foreach (var name in new[] { "Year", "Album", "Genre", "Track", "DiscNumber", "TotalDiscs", "BeatsPerMinute", "TotalTracks", "R128TrackGain" }) + CollectionAssert.Contains (covered, name); + } + + [TestMethod] + public void IsCompilationFalse_OverAnUnreadableValue_WritesFalse () + { + var original = File (AsfDescriptor.CreateDword ("WM/IsCompilation", 1), "WM/IsCompilation"); + var file = Read (original); + Assert.IsFalse (file.Tag.IsCompilation); + + file.Tag.IsCompilation = false; + var again = Read (file.Render (original)).Tag; + + var stored = again.ExtendedContentDescription.Descriptors.Single (d => d.Name == "WM/IsCompilation"); + Assert.AreEqual (AsfAttributeType.Bool, stored.Type); + Assert.IsFalse (stored.BoolValue); + Assert.AreEqual (0, again.GetCustomField ("WM/IsCompilation").Count); + } + + [TestMethod] + public void IsCompilationFalse_WhenNothingIsStored_WritesNothing () + { + var original = File (null, "Other"); + var untouched = Read (original).Render (original); + var file = Read (original); + + file.Tag.IsCompilation = false; + + CollectionAssert.AreEqual (untouched, file.Render (original)); + } + + [TestMethod] + [DataRow ("Title", "Title")] + [DataRow ("Artist", "Author")] + [DataRow ("Copyright", "Copyright")] + [DataRow ("Comment", "Description")] + [DataRow ("Rating", "Rating")] + public void NullOnAContentDescriptionField_ClearsItsLibraryValues (string property, string attribute) + { + var original = File (null, attribute); + var file = Read (original); + Assert.AreEqual (1, file.Tag.GetCustomField (attribute).Count); + + typeof (AsfTag).GetProperty (property)!.SetValue (file.Tag, null); + var again = Read (file.Render (original)).Tag; + + Assert.AreEqual (0, again.GetCustomField (attribute).Count); + } + + [TestMethod] + public void LibraryOnlyValue_IsTheFirstNonEmptyValue_AndEmptyIsAClear () + { + // A single-value getter reads the first non-empty value (the rule the ID3v2, APE, and Vorbis Comment + // getters follow), here the Metadata Library's, when the Extended Content Description holds none. + var original = File (null, "WM/AlbumTitle"); + var untouched = Read (original).Render (original); + var file = Read (original); + Assert.AreEqual ("second", file.Tag.Album); + + file.Tag.Album = file.Tag.Album; + CollectionAssert.AreEqual (untouched, file.Render (original), "a write-back changes nothing"); + + file.Tag.Album = ""; + Assert.AreEqual (0, Read (file.Render (original)).Tag.GetCustomField ("WM/AlbumTitle").Count, "\"\" over text is a clear"); + } + + [TestMethod] + public void EmptyFirstValue_ReadsTheFirstNonEmptyValue () + { + var original = File (AsfDescriptor.CreateString ("WM/AlbumTitle", ""), "WM/AlbumTitle", contentTitle: null); + var file = Read (original); + + Assert.AreEqual ("second", file.Tag.Album); + var withTitle = Read (File (null, "Title")); + Assert.AreEqual ("second", withTitle.Tag.Title, "an empty Content Description field falls through to the library"); + } + + [TestMethod] + [DataRow ("Performers", "Artist")] + [DataRow ("AlbumArtists", "AlbumArtist")] + [DataRow ("Composers", "Composer")] + [DataRow ("Genres", "Genre")] + public void ArraySetter_UnreadableLibrary_WritesTheFirstValueAndKeepsTheLibraryBytes (string arrayProperty, string scalarProperty) + { + // Count says two records, the object holds one and a half, so the tag cannot see every value there. + var library = AsfMetadataLibraryTests.Library ( + AsfMetadataLibraryTests.Record ("Other", "x"), AsfMetadataLibraryTests.Record ("Cut", "off")); + BinaryPrimitives.WriteUInt64LittleEndian (library.AsSpan (16), (ulong)(library.Length - 6)); + var truncated = library.AsSpan (0, library.Length - 6).ToArray (); + byte[] original = [.. AsfTestBuilder.CreateHeaderObject ( + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfMetadataLibraryTests.HeaderExtension (truncated)), .. AsfTestBuilder.CreateDataObject (0)]; + var file = Read (original); + + // The first non-empty entry (Tag.FirstNonEmpty), as every list-to-single setter stores. + typeof (AsfTag).GetProperty (arrayProperty)!.SetValue (file.Tag, EmptyFirstSecond); + var saved = file.Render (original); + + Assert.AreEqual ("First", typeof (AsfTag).GetProperty (scalarProperty)!.GetValue (Read (saved).Tag)); + Assert.IsTrue (saved.AsSpan ().IndexOf (truncated) >= 0, "the library the tag cannot parse is kept as it was"); + } + + public static IEnumerable R128Formats => [["vorbis"], ["ape"], ["id3v24"], ["id3v23"], ["mp4"], ["asf"]]; + + static Tag NewTag (string format) => format switch { + "vorbis" => new VorbisComment ("test"), + "ape" => new ApeTag (), + "id3v24" => new Id3v2Tag (Id3v2Version.V24), + "id3v23" => new Id3v2Tag (Id3v2Version.V23), + "mp4" => new Mp4Tag (), + _ => new AsfTag (), + }; + + [TestMethod] + [DynamicData (nameof (R128Formats))] + public void R128GainDbNull_ClearsTextItCannotParse (string format) + { + foreach (var text in new[] { "abc", "99999" }) { + var tag = NewTag (format); + tag.R128TrackGain = text; + tag.R128AlbumGain = text; + Assert.IsNull (tag.R128TrackGainDb); + + tag.R128TrackGainDb = null; + tag.R128AlbumGainDb = null; + + Assert.IsNull (tag.R128TrackGain, $"{format} {text}"); + Assert.IsNull (tag.R128AlbumGain, $"{format} {text}"); + } + } + + [TestMethod] + [DynamicData (nameof (R128Formats))] + public void R128GainDbWriteBack_KeepsTheStoredText (string format) + { + var tag = NewTag (format); + tag.R128TrackGain = "-0512"; + + tag.R128TrackGainDb = tag.R128TrackGainDb; + + Assert.AreEqual ("-0512", tag.R128TrackGain); + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfMappedWriteBackTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfMappedWriteBackTests.cs new file mode 100644 index 00000000..0de706fb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfMappedWriteBackTests.cs @@ -0,0 +1,160 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// Writing a mapped property's own value back changes nothing, on a file whose attributes also hold values +/// 2..n in the Metadata Library Object (the layout Windows writes; ASF spec rev. 01.20.03 §4.8 and +/// https://mutagen-specs.readthedocs.io/en/latest/asf/index.html "Multiple Values"). The array properties read +/// every value, so a read-modify-write of them keeps the file's values too. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfMappedWriteBackTests +{ + static readonly string[] ContentDescriptionNames = ["Title", "Author", "Copyright", "Description", "Rating"]; + static readonly string[] Xyz = ["x", "y", "z"]; + static readonly string[] Only = ["only"]; + static readonly string[] NewArtist = ["New"]; + static readonly string[] NewGenre = ["New genre"]; + static readonly string[] Nine = ["9"]; + + /// Every public mapped property of that can be read and written. + static IEnumerable MappedProperties () => + typeof (AsfTag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0) + .OrderBy (p => p.Name, StringComparer.Ordinal); + + public static IEnumerable PropertyNames => MappedProperties ().Select (p => new object[] { p.Name }); + + static object? Sample (PropertyInfo p) => p.Name is "R128TrackGain" or "R128AlbumGain" + // A Q7.8 integer, so the dB views read it and their write-back is a write-back. + ? "-512" + : p.PropertyType switch { + var t when t == typeof (string) => "v " + p.Name, + var t when t == typeof (uint?) => (uint?)7, + var t when t == typeof (bool) => true, + var t when t == typeof (string[]) => new[] { "first " + p.Name }, + var t when t == typeof (IPicture[]) => Array.Empty (), + // R128 gain in dB is a view over the R128 string properties, which get their own sample. + var t when t == typeof (double?) => null, + _ => throw new InvalidOperationException ($"no sample for {p.Name} ({p.PropertyType})") + }; + + /// + /// A WMA with every mapped property set, and a second value for every attribute in the Metadata Library. + /// + static (byte[] File, string[] Names) MultiValuedFile () + { + var tag = new AsfTag (); + foreach (var p in MappedProperties ()) { + if (Sample (p) is { } sample) + p.SetValue (tag, sample); + } + + var names = ContentDescriptionNames + .Where (n => tag.GetCustomField (n).Count > 0) + .Concat (tag.ExtendedContentDescription.Descriptors.Select (d => d.Name)) + .Distinct (StringComparer.OrdinalIgnoreCase) + .ToArray (); + var library = AsfMetadataLibraryTests.Library ([.. names.Select (n => AsfMetadataLibraryTests.Record (n, "second " + n))]); + var file = AsfTestBuilder.CreateHeaderObject ( + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfMetadataLibraryTests.Object (AsfGuids.ContentDescriptionObject, tag.RenderContentDescription ().ToArray ()), + AsfMetadataLibraryTests.HeaderExtension (library), + AsfMetadataLibraryTests.Object (AsfGuids.ExtendedContentDescriptionObject, tag.Render ().ToArray ())); + return ([.. file, .. AsfTestBuilder.CreateDataObject (0)], names); + } + + static AsfFile Read (byte[] data) + { + var result = AsfFile.Read (data); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.File!; + } + + [TestMethod] + [DynamicData (nameof (PropertyNames))] + public void UnchangedWriteBack_ChangesNothing (string property) + { + var (original, names) = MultiValuedFile (); + var untouched = Read (original).Render (original); + var p = typeof (AsfTag).GetProperty (property)!; + + var file = Read (original); + p.SetValue (file.Tag, p.GetValue (file.Tag)); + var saved = file.Render (original); + + var again = Read (saved).Tag; + foreach (var name in names) { + CollectionAssert.AreEqual ( + Read (untouched).Tag.GetCustomField (name).ToArray (), again.GetCustomField (name).ToArray (), + $"{property} = {property} changed {name}"); + } + CollectionAssert.AreEqual (untouched, saved, $"{property} = {property} changed the file"); + } + + [TestMethod] + public void Fixture_HoldsTwoValuesForEveryAttribute () + { + var (original, names) = MultiValuedFile (); + var tag = Read (original).Tag; + + Assert.IsTrue (names.Length > 40, $"only {names.Length} attributes"); + foreach (var name in names) { + // A BOOL attribute has no text, so only its library value reads back. + var values = tag.GetCustomField (name); + CollectionAssert.Contains (values.ToArray (), "second " + name); + Assert.AreEqual (name == "WM/IsCompilation" ? 1 : 2, values.Count, name); + } + } + + [TestMethod] + [DataRow ("Performers", "Author")] + [DataRow ("AlbumArtists", "WM/AlbumArtist")] + [DataRow ("Composers", "WM/Composer")] + [DataRow ("Genres", "WM/Genre")] + public void ArrayProperty_ReadsAndWritesEveryValue (string property, string attribute) + { + var (original, _) = MultiValuedFile (); + var p = typeof (AsfTag).GetProperty (property)!; + var file = Read (original); + + var values = (string[])p.GetValue (file.Tag)!; + CollectionAssert.AreEqual (file.Tag.GetCustomField (attribute).ToArray (), values); + Assert.AreEqual (2, values.Length); + + p.SetValue (file.Tag, Xyz); + var again = Read (file.Render (original)).Tag; + CollectionAssert.AreEqual (Xyz, (string[])p.GetValue (again)!); + CollectionAssert.AreEqual (Xyz, again.GetCustomField (attribute).ToArray ()); + + p.SetValue (again, Only); + CollectionAssert.AreEqual (Only, again.GetCustomField (attribute).ToArray ()); + p.SetValue (again, Array.Empty ()); + Assert.AreEqual (0, again.GetCustomField (attribute).Count); + } + + [TestMethod] + public void ChangedScalar_ReplacesEveryValue () + { + var (original, _) = MultiValuedFile (); + var file = Read (original); + + file.Tag.Artist = "New"; + file.Tag.Genre = "New genre"; + file.Tag.Track = 9; + var again = Read (file.Render (original)).Tag; + + CollectionAssert.AreEqual (NewArtist, again.Performers); + CollectionAssert.AreEqual (NewGenre, again.Genres); + CollectionAssert.AreEqual (Nine, again.GetCustomField ("WM/TrackNumber").ToArray ()); + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfMetadataLibraryTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfMetadataLibraryTests.cs new file mode 100644 index 00000000..5d97e50c --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfMetadataLibraryTests.cs @@ -0,0 +1,337 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Asf; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// Values 2..n of a multi-valued attribute live in the Metadata Library Object inside the Header Extension +/// Object (ASF spec rev. 01.20.03 §3.4 and §4.8; the layout Windows writes, as recorded at +/// https://mutagen-specs.readthedocs.io/en/latest/asf/index.html "Multiple Values"). Every custom field read +/// sees them, and every write or remove leaves the file holding exactly the values asked for. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfMetadataLibraryTests +{ + // ASF_Reserved_1, the fixed Reserved Field 1 of the Header Extension Object (§3.4). + internal static readonly byte[] Reserved1 = Guid.Parse ("ABD3D211-A9BA-11CF-8EE6-00C00C205365").ToByteArray (); + + /// One Metadata Library or Metadata record: first WORD, stream, name length, type, data length. + internal static byte[] Record (string name, string value, ushort stream = 0, ushort first = 0) => + RawRecord (name, 0, Encoding.Unicode.GetBytes (value + "\0"), stream, first); + + internal static byte[] RawRecord (string name, ushort type, byte[] data, ushort stream = 0, ushort first = 0) + { + var nameBytes = Encoding.Unicode.GetBytes (name + "\0"); + var record = new byte[12 + nameBytes.Length + data.Length]; + BinaryPrimitives.WriteUInt16LittleEndian (record, first); + BinaryPrimitives.WriteUInt16LittleEndian (record.AsSpan (2), stream); + BinaryPrimitives.WriteUInt16LittleEndian (record.AsSpan (4), (ushort)nameBytes.Length); + BinaryPrimitives.WriteUInt16LittleEndian (record.AsSpan (6), type); + BinaryPrimitives.WriteUInt32LittleEndian (record.AsSpan (8), (uint)data.Length); + nameBytes.CopyTo (record, 12); + data.CopyTo (record, 12 + nameBytes.Length); + return record; + } + + internal static byte[] Object (AsfGuid guid, byte[] content) + { + var result = new byte[24 + content.Length]; + guid.Render ().Span.CopyTo (result); + BinaryPrimitives.WriteUInt64LittleEndian (result.AsSpan (16), (ulong)result.Length); + content.CopyTo (result, 24); + return result; + } + + internal static byte[] RecordsObject (AsfGuid guid, params byte[][] records) + { + var body = new List (); + body.AddRange (BitConverter.GetBytes ((ushort)records.Length)); + foreach (var r in records) + body.AddRange (r); + return Object (guid, [.. body]); + } + + internal static byte[] Library (params byte[][] records) => RecordsObject (AsfGuids.MetadataLibraryObject, records); + + internal static byte[] Metadata (params byte[][] records) => RecordsObject (AsfGuids.MetadataObject, records); + + internal static byte[] HeaderExtension (params byte[][] children) + { + var data = children.SelectMany (c => c).ToArray (); + var content = new byte[16 + 2 + 4 + data.Length]; + Reserved1.CopyTo (content, 0); + BinaryPrimitives.WriteUInt16LittleEndian (content.AsSpan (16), 6); + BinaryPrimitives.WriteUInt32LittleEndian (content.AsSpan (18), (uint)data.Length); + data.CopyTo (content, 22); + return Object (AsfGuids.HeaderExtensionObject, content); + } + + static byte[] Wma (byte[]? headerExtension, params AsfDescriptor[] descriptors) + { + var children = new List { + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfTestBuilder.CreateContentDescriptionObject ("Song", "First author"), + }; + if (headerExtension is not null) + children.Add (headerExtension); + if (descriptors.Length > 0) + children.Add (AsfTestBuilder.CreateExtendedContentDescriptionObject (descriptors)); + return [.. AsfTestBuilder.CreateHeaderObject ([.. children]), .. AsfTestBuilder.CreateDataObject (0)]; + } + + static byte[] MultiValued () => Wma ( + HeaderExtension (Metadata (), Library (Record ("MyField", "second"), Record ("MyField", "third"))), + AsfDescriptor.CreateString ("MyField", "first")); + + static AsfFile Read (byte[] data) + { + var result = AsfFile.Read (data); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.File!; + } + + static bool Holds (byte[] file, string text) => + file.AsSpan ().IndexOf (Encoding.Unicode.GetBytes (text)) >= 0; + + static void AssertValues (IReadOnlyList actual, params string[] expected) => + CollectionAssert.AreEqual (expected, actual.ToArray ()); + + [TestMethod] + public void GetCustomField_ReadsTheValuesInTheMetadataLibrary () + { + var file = Read (MultiValued ()); + + AssertValues (file.Tag.GetCustomField ("MyField"), "first", "second", "third"); + AssertValues (file.Tag.GetCustomField ("myfield"), "first", "second", "third"); + } + + [TestMethod] + public void SetCustomField_ReplacesTheLibraryValues () + { + var original = MultiValued (); + var file = Read (original); + + Assert.IsTrue (file.Tag.SetCustomField ("MyField", "x")); + var saved = file.Render (original); + + AssertValues (Read (saved).Tag.GetCustomField ("MyField"), "x"); + Assert.IsFalse (Holds (saved, "second")); + Assert.IsFalse (Holds (saved, "third")); + } + + [TestMethod] + public void RemoveCustomField_RemovesTheLibraryValues () + { + var original = MultiValued (); + var file = Read (original); + + Assert.IsTrue (file.Tag.RemoveCustomField ("MyField")); + Assert.AreEqual (0, file.Tag.GetCustomField ("MyField").Count); + var saved = file.Render (original); + + Assert.AreEqual (0, Read (saved).Tag.GetCustomField ("MyField").Count); + Assert.IsFalse (Holds (saved, "MyField")); + } + + [TestMethod] + public void RemoveCustomField_ValueOnlyInTheLibrary_IsFoundAndRemoved () + { + var original = Wma (HeaderExtension (Library (Record ("OnlyHere", "v")))); + var file = Read (original); + + AssertValues (file.Tag.GetCustomField ("OnlyHere"), "v"); + Assert.IsTrue (file.Tag.RemoveCustomField ("OnlyHere")); + Assert.IsFalse (Holds (file.Render (original), "OnlyHere")); + } + + [TestMethod] + public void SetCustomField_SeveralValues_FirstInExtendedContentRestInLibrary () + { + var original = Wma (HeaderExtension (Metadata ())); + var file = Read (original); + + Assert.IsTrue (file.Tag.SetCustomField ("MyField", "a", "b", "c")); + var again = Read (file.Render (original)); + + AssertValues (again.Tag.GetCustomField ("MyField"), "a", "b", "c"); + Assert.AreEqual (1, again.Tag.ExtendedContentDescription.Descriptors.Count (d => d.Name == "MyField")); + } + + [TestMethod] + public void SetCustomField_SeveralValues_FileWithoutHeaderExtension_GetsOne () + { + var original = Wma (null); + var file = Read (original); + + Assert.IsTrue (file.Tag.SetCustomField ("MyField", "a", "b")); + var saved = file.Render (original); + var again = Read (saved); + + AssertValues (again.Tag.GetCustomField ("MyField"), "a", "b"); + Assert.AreEqual (1, again.Tag.ExtendedContentDescription.Descriptors.Count (d => d.Name == "MyField")); + Assert.IsTrue (saved.AsSpan ().IndexOf (Reserved1) >= 0, "a Header Extension Object was written"); + + // ASF spec rev. 01.20.03 §3.4: GUID, Object Size (QWORD), Reserved Field 1 (ASF_Reserved_1), + // Reserved Field 2 "should be set to 6", Header Extension Data Size = Object Size - 46. + var at = saved.AsSpan ().IndexOf (AsfGuids.HeaderExtensionObject.Render ().Span); + Assert.IsTrue (at > 0); + var objectSize = BinaryPrimitives.ReadUInt64LittleEndian (saved.AsSpan (at + 16)); + CollectionAssert.AreEqual (Reserved1, saved.AsSpan (at + 24, 16).ToArray ()); + Assert.AreEqual ((ushort)6, BinaryPrimitives.ReadUInt16LittleEndian (saved.AsSpan (at + 40))); + Assert.AreEqual (objectSize - 46, BinaryPrimitives.ReadUInt32LittleEndian (saved.AsSpan (at + 42))); + var library = saved.AsSpan (at + 46).IndexOf (AsfGuids.MetadataLibraryObject.Render ().Span); + Assert.AreEqual (0, library, "the Metadata Library Object is the extension's only child"); + } + + [TestMethod] + public void ContentDescriptionName_FirstValueInTheFixedFieldRestInLibrary () + { + var original = Wma (HeaderExtension (Library (Record ("Author", "Second author")))); + var file = Read (original); + AssertValues (file.Tag.GetCustomField ("Author"), "First author", "Second author"); + + Assert.IsTrue (file.Tag.SetCustomField ("Author", "A", "B")); + var again = Read (file.Render (original)); + + Assert.AreEqual ("A", again.Tag.Artist); + AssertValues (again.Tag.GetCustomField ("Author"), "A", "B"); + Assert.IsTrue (again.Tag.RemoveCustomField ("Author")); + Assert.AreEqual (0, again.Tag.GetCustomField ("Author").Count); + } + + [TestMethod] + public void MappedSetter_ReplacesTheLibraryValuesOfItsAttribute () + { + var original = Wma ( + HeaderExtension (Library (Record ("WM/AlbumTitle", "Old 2"))), + AsfDescriptor.CreateString ("WM/AlbumTitle", "Old 1")); + var file = Read (original); + + file.Tag.Album = "New"; + var saved = file.Render (original); + + AssertValues (Read (saved).Tag.GetCustomField ("WM/AlbumTitle"), "New"); + Assert.IsFalse (Holds (saved, "Old 2")); + } + + [TestMethod] + public void OtherRecords_AreKept () + { + byte[] other = Record ("Other", "kept"); + byte[] streamOne = Record ("MyField", "stream one", stream: 1); + byte[] language = Record ("MyField", "other language", first: 1); + byte[] metadataRecord = Record ("MyField", "metadata stream", stream: 1); + var original = Wma ( + HeaderExtension (Metadata (metadataRecord), Library (other, streamOne, Record ("MyField", "second"), language)), + AsfDescriptor.CreateString ("MyField", "first")); + var file = Read (original); + AssertValues (file.Tag.GetCustomField ("MyField"), "first", "second", "other language"); + + file.Tag.SetCustomField ("MyField", "x"); + var saved = file.Render (original); + + Assert.IsTrue (saved.AsSpan ().IndexOf (other) >= 0); + Assert.IsTrue (saved.AsSpan ().IndexOf (streamOne) >= 0, "a stream's record is not the file's"); + Assert.IsTrue (saved.AsSpan ().IndexOf (metadataRecord) >= 0, "a stream's record is not the file's"); + Assert.IsFalse (Holds (saved, "other language"), "every language of the file-level name is replaced"); + AssertValues (Read (saved).Tag.GetCustomField ("MyField"), "x"); + } + + [TestMethod] + public void NumericLibraryRecords_ReadAsDecimal () + { + var dword = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian (dword, 7); + var original = Wma (HeaderExtension (Library ( + RawRecord ("N", 3, dword), + RawRecord ("N", 5, [9, 0]), + RawRecord ("N", 4, [1, 0, 0, 0, 0, 0, 0, 0]), + RawRecord ("N", 2, [1, 0]), + RawRecord ("N", 1, [1, 2, 3])))); + + AssertValues (Read (original).Tag.GetCustomField ("N"), "7", "9", "1"); + } + + [TestMethod] + public void UnchangedSave_KeepsTheHeaderExtensionBytes () + { + var original = MultiValued (); + var extension = HeaderExtension (Metadata (), Library (Record ("MyField", "second"), Record ("MyField", "third"))); + var file = Read (original); + + file.Tag.Title = "Changed title"; + var saved = file.Render (original); + + Assert.IsTrue (saved.AsSpan ().IndexOf (extension) >= 0); + } + + [TestMethod] + public void MalformedLibrary_IsKeptAndIgnored () + { + // Count says two records, the object holds one and a half. + var library = Library (Record ("MyField", "second"), Record ("Cut", "off")); + BinaryPrimitives.WriteUInt64LittleEndian (library.AsSpan (16), (ulong)(library.Length - 6)); + var truncated = library.AsSpan (0, library.Length - 6).ToArray (); + var original = Wma (HeaderExtension (truncated), AsfDescriptor.CreateString ("MyField", "first")); + var file = Read (original); + + AssertValues (file.Tag.GetCustomField ("MyField"), "first"); + Assert.IsFalse (file.Tag.SetCustomField ("MyField", "x"), "values the tag cannot see would survive"); + Assert.IsFalse (file.Tag.RemoveCustomField ("MyField")); + Assert.IsTrue (file.Render (original).AsSpan ().IndexOf (truncated) >= 0); + } + + [TestMethod] + public void DuplicateOrShortLibrary_MakesTheExtensionUnreadable () + { + var twice = Wma (HeaderExtension (Library (Record ("A", "1")), Library (Record ("A", "2")))); + var empty = Wma (HeaderExtension (Object (AsfGuids.MetadataLibraryObject, []))); + var shortRecord = Wma (HeaderExtension (Object (AsfGuids.MetadataObject, [1, 0, 0, 0, 0]))); + + foreach (var original in new[] { twice, empty, shortRecord }) { + var file = Read (original); + Assert.IsFalse (file.Tag.SetCustomField ("A", "x")); + Assert.IsFalse (file.Tag.RemoveCustomField ("A")); + file.Tag.Title = "Still writable"; + var saved = file.Render (original); + Assert.AreEqual ("Still writable", Read (saved).Tag.Title); + } + } + + [TestMethod] + public void HeaderExtensionChildThatDoesNotFit_MakesTheExtensionUnreadable () + { + // A Metadata Library Object could hide past a child whose size runs off the end. + var library = Library (Record ("MyField", "second")); + var oversized = (byte[])library.Clone (); + BinaryPrimitives.WriteUInt64LittleEndian (oversized.AsSpan (16), 100_000); + var original = Wma (HeaderExtension (oversized, library), AsfDescriptor.CreateString ("MyField", "first")); + var file = Read (original); + + AssertValues (file.Tag.GetCustomField ("MyField"), "first"); + Assert.IsFalse (file.Tag.SetCustomField ("MyField", "x", "y")); + Assert.IsTrue (file.Render (original).AsSpan ().IndexOf (oversized) >= 0, "the extension is kept as it was"); + } + + [TestMethod] + public void Clear_RemovesFileLevelRecordsAndKeepsStreamRecords () + { + byte[] streamOne = Record ("IsVBR", "1", stream: 1); + var original = Wma (HeaderExtension (Library (Record ("MyField", "second"), streamOne)), + AsfDescriptor.CreateString ("MyField", "first")); + var file = Read (original); + + file.Tag.Clear (); + var saved = file.Render (original); + + Assert.AreEqual (0, Read (saved).Tag.GetCustomField ("MyField").Count); + Assert.IsTrue (saved.AsSpan ().IndexOf (streamOne) >= 0); + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs new file mode 100644 index 00000000..c5513b41 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfRecordLayoutTests.cs @@ -0,0 +1,498 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Reflection; +using System.Text; +using TagLibSharp2.Asf; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// The number and BOOL properties read an attribute the way the string properties do: the first non-empty value, +/// from the Extended Content Description and then the file-level Metadata and Metadata Library records (ASF §4.7, +/// §4.8). Over every layout a write-back of the value read changes nothing, null (or false) clears every record of +/// the attribute, and a new value replaces them all. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfRecordLayoutTests +{ + static readonly string[] Nine = ["9"]; + static readonly string[] Five = ["5"]; + + public static IEnumerable NumberProperties => [ + ["Track", "WM/TrackNumber"], + ["TotalTracks", "WM/TrackTotal"], + ["BeatsPerMinute", "WM/BeatsPerMinute"], + ["MovementNumber", "WM/MovementNumber"], + ["MovementTotal", "WM/MovementTotal"], + ]; + + /// Layouts that hold the number 7 where the getter can find it, as mutagen writes them. + public static IEnumerable NumberLayouts => [ + ["empty ECD string, Metadata string"], + ["empty ECD string, Library DWORD"], + ["Metadata DWORD only"], + ["Library string only"], + ["ECD DWORD, Library DWORD 8"], + ["empty Metadata string, Library DWORD"], + ]; + + public static IEnumerable NumberCells => + NumberProperties.SelectMany (p => NumberLayouts.Select (l => new object[] { p[0], p[1], l[0] })); + + static byte[] Dword (uint value) + { + var data = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian (data, value); + return data; + } + + /// A BOOL in the Metadata and Metadata Library Objects is a WORD (ASF §4.7, §4.8). + static byte[] RecordBool (bool value) => [value ? (byte)1 : (byte)0, 0]; + + static byte[] NumberFile (string attribute, string layout) => layout switch { + "empty ECD string, Metadata string" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.Record (attribute, "7")), + AsfDescriptor.CreateString (attribute, "")), + "empty ECD string, Library DWORD" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (attribute, 3, Dword (7))), + AsfDescriptor.CreateString (attribute, "")), + "Metadata DWORD only" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord (attribute, 3, Dword (7)))), + "Library string only" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.Record (attribute, "7"))), + "empty Metadata string, Library DWORD" => File ([ + .. AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.Record (attribute, "")), + .. AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (attribute, 3, Dword (7)))]), + "ECD DWORD, Library DWORD 8" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (attribute, 3, Dword (8))), + AsfDescriptor.CreateDword (attribute, 7)), + _ => throw new ArgumentOutOfRangeException (nameof (layout)) + }; + + static byte[] File (byte[] records, params AsfDescriptor[] descriptors) => + [.. AsfTestBuilder.CreateHeaderObject ([ + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfMetadataLibraryTests.HeaderExtension (records), + .. descriptors.Length == 0 ? Array.Empty () : [AsfTestBuilder.CreateExtendedContentDescriptionObject (descriptors)], + ]), .. AsfTestBuilder.CreateDataObject (0)]; + + static AsfFile Read (byte[] data) + { + var result = AsfFile.Read (data); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.File!; + } + + /// How many times the attribute's name appears in the file: once per stored value. + static int Occurrences (byte[] file, string attribute) + { + var name = Encoding.Unicode.GetBytes (attribute + "\0"); + var count = 0; + for (var i = 0; i + name.Length <= file.Length; i++) { + if (file.AsSpan (i, name.Length).SequenceEqual (name)) + count++; + } + return count; + } + + [TestMethod] + [DynamicData (nameof (NumberCells))] + public void Number_ReadsTheFirstNonEmptyValue_AndAWriteBackChangesNothing (string property, string attribute, string layout) + { + var p = typeof (AsfTag).GetProperty (property)!; + var original = NumberFile (attribute, layout); + var untouched = Read (original).Render (original); + var file = Read (original); + + Assert.AreEqual ((uint?)7, p.GetValue (file.Tag), $"{property} over {layout}"); + p.SetValue (file.Tag, p.GetValue (file.Tag)); + + CollectionAssert.AreEqual (untouched, file.Render (original), $"{property} = {property} over {layout} changed the file"); + } + + [TestMethod] + [DynamicData (nameof (NumberCells))] + public void Number_NullClearsEveryRecord (string property, string attribute, string layout) + { + var p = typeof (AsfTag).GetProperty (property)!; + var original = NumberFile (attribute, layout); + var file = Read (original); + + p.SetValue (file.Tag, null); + var saved = file.Render (original); + var again = Read (saved).Tag; + + Assert.IsNull (p.GetValue (again), $"{property} = null over {layout}"); + Assert.AreEqual (0, Occurrences (saved, attribute), $"{property} = null over {layout} kept a value"); + } + + [TestMethod] + [DynamicData (nameof (NumberCells))] + public void Number_NewValueReplacesEveryRecord (string property, string attribute, string layout) + { + var p = typeof (AsfTag).GetProperty (property)!; + var original = NumberFile (attribute, layout); + var file = Read (original); + + p.SetValue (file.Tag, (uint?)9); + var again = Read (file.Render (original)).Tag; + + Assert.AreEqual ((uint?)9, p.GetValue (again)); + CollectionAssert.AreEqual (Nine, again.GetCustomField (attribute).ToArray (), $"{property} = 9 over {layout}"); + } + + [TestMethod] + public void NumberProperties_CoverEveryNumberAttribute () + { + var listed = NumberProperties.Select (p => (string)p[0]).ToList (); + foreach (var p in typeof (AsfTag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.CanRead && p.CanWrite && p.PropertyType == typeof (uint?))) { + var probe = new AsfTag (); + p.SetValue (probe, (uint?)3); + var written = probe.ExtendedContentDescription.Descriptors; + if (written.Count == 1 && written[0].Type == AsfAttributeType.Dword) + CollectionAssert.Contains (listed, p.Name, $"{p.Name} writes a DWORD; add it to the layout matrix"); + } + } + + /// Layouts of WM/IsCompilation and what IsCompilation reads from each. + public static IEnumerable BoolLayouts => [ + ["Metadata true only", true], + ["Library true only", true], + ["empty ECD string, Metadata true", true], + ["ECD true, Library false", true], + ["Metadata false only", false], + ["ECD false, Library true", false], + ["Metadata DWORD 1 only", false], + ]; + + /// Layouts where the getter reads false but something else is stored, so false is a clear. + static readonly string[] FalseClears = ["ECD false, Library true", "Metadata DWORD 1 only"]; + + static byte[] BoolFile (string layout) + { + const string name = "WM/IsCompilation"; + return layout switch { + "Metadata true only" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (true)))), + "Library true only" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (true)))), + "empty ECD string, Metadata true" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (true))), + AsfDescriptor.CreateString (name, "")), + "ECD true, Library false" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (false))), + AsfDescriptor.CreateBool (name, true)), + "Metadata false only" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (false)))), + "Metadata DWORD 1 only" => File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord (name, 3, Dword (1)))), + "ECD false, Library true" => File (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.RawRecord (name, 2, RecordBool (true))), + AsfDescriptor.CreateBool (name, false)), + _ => throw new ArgumentOutOfRangeException (nameof (layout)) + }; + } + + [TestMethod] + [DynamicData (nameof (BoolLayouts))] + public void IsCompilation_ReadsTheFirstValue_AndAWriteBackChangesNothing (string layout, bool expected) + { + var original = BoolFile (layout); + var untouched = Read (original).Render (original); + var file = Read (original); + + Assert.AreEqual (expected, file.Tag.IsCompilation, layout); + if (FalseClears.Contains (layout)) + return; // False over a stored true or a DWORD is a clear (IsCompilation_FalseClearsEveryTrue). + file.Tag.IsCompilation = expected; + + CollectionAssert.AreEqual (untouched, file.Render (original), $"IsCompilation = {expected} over {layout} changed the file"); + } + + [TestMethod] + [DynamicData (nameof (BoolLayouts))] + public void IsCompilation_FalseClearsEveryTrue (string layout, bool expected) + { + _ = expected; + var original = BoolFile (layout); + var file = Read (original); + + file.Tag.IsCompilation = false; + var saved = file.Render (original); + var again = Read (saved).Tag; + + Assert.IsFalse (again.IsCompilation, layout); + if (layout == "Metadata false only") { + CollectionAssert.AreEqual (Read (original).Render (original), saved, "false over a stored false changes nothing"); + return; + } + // The one value left is the Extended Content Description BOOL false the setter writes. + Assert.AreEqual (1, Occurrences (saved, "WM/IsCompilation"), $"IsCompilation = false over {layout} kept a record"); + var stored = again.ExtendedContentDescription.Descriptors.Single (d => d.Name == "WM/IsCompilation"); + Assert.AreEqual (AsfAttributeType.Bool, stored.Type); + Assert.IsFalse (stored.BoolValue); + } + + [TestMethod] + [DynamicData (nameof (BoolLayouts))] + public void IsCompilation_TrueOverAFalseReplacesEveryRecord (string layout, bool expected) + { + var original = BoolFile (layout); + var file = Read (original); + if (expected) + return; // A write-back (IsCompilation_ReadsTheFirstValue_AndAWriteBackChangesNothing). + + file.Tag.IsCompilation = true; + var saved = file.Render (original); + var again = Read (saved).Tag; + + Assert.IsTrue (again.IsCompilation, layout); + Assert.AreEqual (1, Occurrences (saved, "WM/IsCompilation"), $"IsCompilation = true over {layout} kept a record"); + } + + [TestMethod] + public void IsCompilation_NullBoolRecord_IsNotTrue () + { + // A BOOL record too short to hold its WORD reads as no value. + var original = File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord ("WM/IsCompilation", 2, []))); + Assert.IsFalse (Read (original).Tag.IsCompilation); + } + + [TestMethod] + public void EmptyString_OverAnEmptyStringAndANumber_ClearsBoth () + { + // mutagen's WM/AlbumTitle = [Unicode '', DWORD 5]: Album reads "", yet "" is not the value read, because + // another value of the attribute is not empty. So "" is a clear. + var original = File (AsfMetadataLibraryTests.Metadata (AsfMetadataLibraryTests.RawRecord ("WM/AlbumTitle", 3, Dword (5))), + AsfDescriptor.CreateString ("WM/AlbumTitle", "")); + var file = Read (original); + Assert.AreEqual ("", file.Tag.Album); + CollectionAssert.AreEqual (Five, file.Tag.GetCustomField ("WM/AlbumTitle").ToArray (), "the DWORD is the one value with text"); + + file.Tag.Album = ""; + var saved = file.Render (original); + + Assert.AreEqual (0, Occurrences (saved, "WM/AlbumTitle"), "\"\" over [\"\", 5] kept a value"); + } + + public static IEnumerable ContentDescriptionFields => [ + ["Title", "Title"], + ["Artist", "Author"], + ["Copyright", "Copyright"], + ["Comment", "Description"], + ["Rating", "Rating"], + ]; + + /// + /// ffmpeg writes each Content Description field a second time as an Extended Content Description descriptor of the + /// same name, so mutagen reads Author as ['old', 'old'] and ffprobe shows the descriptor. + /// + static byte[] DuplicatedFile (string attribute, string? fieldValue, string descriptorValue) => + [.. AsfTestBuilder.CreateHeaderObject ([ + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfTestBuilder.CreateContentDescriptionObject ( + attribute == "Title" ? fieldValue : null, + attribute == "Author" ? fieldValue : null, + attribute == "Copyright" ? fieldValue : null, + attribute == "Description" ? fieldValue : null, + attribute == "Rating" ? fieldValue : null), + AsfTestBuilder.CreateExtendedContentDescriptionObject (AsfDescriptor.CreateString (FfmpegSpelling (attribute), descriptorValue)), + ]), .. AsfTestBuilder.CreateDataObject (0)]; + + /// + /// The name ffmpeg gives the descriptor copy: title, copyright, and rating in lower case, + /// Author and Description as the Content Description names them. Every call below uses the + /// documented name, so a match that minds case leaves three of the five copies behind. + /// + static string FfmpegSpelling (string attribute) => attribute switch { + "Title" => "title", + "Copyright" => "copyright", + "Rating" => "rating", + _ => attribute, + }; + + static readonly string[] Old = ["old"]; + static readonly string[] Only = ["only"]; + + [TestMethod] + [DynamicData (nameof (ContentDescriptionFields))] + public void ContentDescriptionField_WithItsDescriptorTwin_ReadsOnceAndAWriteBackChangesNothing (string property, string attribute) + { + var p = typeof (AsfTag).GetProperty (property)!; + var original = DuplicatedFile (attribute, "old", "old"); + var untouched = Read (original).Render (original); + var file = Read (original); + + Assert.AreEqual ("old", p.GetValue (file.Tag)); + CollectionAssert.AreEqual (Old, file.Tag.GetCustomField (attribute).ToArray ()); + p.SetValue (file.Tag, p.GetValue (file.Tag)); + + CollectionAssert.AreEqual (untouched, file.Render (original)); + } + + [TestMethod] + [DynamicData (nameof (ContentDescriptionFields))] + public void ContentDescriptionField_NewValue_ReplacesItsDescriptorTwin (string property, string attribute) + { + var p = typeof (AsfTag).GetProperty (property)!; + var original = DuplicatedFile (attribute, "old", "old"); + var file = Read (original); + + p.SetValue (file.Tag, "V2"); + var again = Read (file.Render (original)).Tag; + + Assert.AreEqual ("V2", p.GetValue (again)); + Assert.IsFalse (again.ExtendedContentDescription.Descriptors.Any (d => string.Equals (d.Name, attribute, StringComparison.OrdinalIgnoreCase)), $"{property} = V2 left the old {attribute} descriptor"); + } + + [TestMethod] + [DynamicData (nameof (ContentDescriptionFields))] + public void ContentDescriptionField_CustomFieldWriteAndRemove_ReplaceItsDescriptorTwin (string property, string attribute) + { + _ = property; + var original = DuplicatedFile (attribute, "old", "old"); + var file = Read (original); + Assert.IsTrue (file.Tag.SetCustomField (attribute, "a", "b")); + var set = Read (file.Render (original)).Tag; + Assert.IsFalse (set.ExtendedContentDescription.Descriptors.Any (d => string.Equals (d.Name, attribute, StringComparison.OrdinalIgnoreCase)), "SetCustomField left the descriptor"); + + file = Read (original); + Assert.IsTrue (file.Tag.RemoveCustomField (attribute)); + var removed = Read (file.Render (original)).Tag; + Assert.IsFalse (removed.ExtendedContentDescription.Descriptors.Any (d => string.Equals (d.Name, attribute, StringComparison.OrdinalIgnoreCase)), "RemoveCustomField left the descriptor"); + Assert.AreEqual (0, removed.GetCustomField (attribute).Count); + } + + [TestMethod] + [DynamicData (nameof (ContentDescriptionFields))] + public void ContentDescriptionField_EmptyField_ReadsItsDescriptorTwin (string property, string attribute) + { + var p = typeof (AsfTag).GetProperty (property)!; + var file = Read (DuplicatedFile (attribute, null, "only")); + + Assert.AreEqual ("only", p.GetValue (file.Tag)); + CollectionAssert.AreEqual (Only, file.Tag.GetCustomField (attribute).ToArray ()); + Assert.IsTrue (file.Tag.RemoveCustomField (attribute), "a descriptor-only value is removed"); + } + + /// + /// The file ffmpeg writes for -metadata artist=old -metadata title=T: the Content Description holds Title and + /// Author, and the Extended Content Description holds them again as Author and a lowercase title. + /// + static byte[] FfmpegFile () => + [.. AsfTestBuilder.CreateHeaderObject ([ + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfTestBuilder.CreateContentDescriptionObject ("T", "old"), + AsfTestBuilder.CreateExtendedContentDescriptionObject ( + AsfDescriptor.CreateString ("Author", "old"), AsfDescriptor.CreateString ("title", "T")), + ]), .. AsfTestBuilder.CreateDataObject (0)]; + + static readonly string[] NewN2 = ["new", "n2"]; + static readonly string[] New = ["new"]; + + static bool HasDescriptor (AsfTag tag, string name) => + tag.ExtendedContentDescription.Descriptors.Any (d => string.Equals (d.Name, name, StringComparison.OrdinalIgnoreCase)); + + /// Every write of Author or Title leaves no stale Extended Content Description copy behind. + [TestMethod] + [DataRow ("RemoveCustomField Author")] + [DataRow ("RemoveCustomField title")] + [DataRow ("SetCustomField Author")] + [DataRow ("Performers")] + [DataRow ("Artist")] + [DataRow ("Title")] + [DataRow ("CopyTo")] + public void FfmpegFile_EveryWrite_LeavesNoStaleDescriptor (string write) + { + var original = FfmpegFile (); + var file = Read (original); + var tag = file.Tag; + string attribute; + string[] expected; + switch (write) { + case "RemoveCustomField Author": + Assert.IsTrue (tag.RemoveCustomField ("Author")); + (attribute, expected) = ("Author", []); + break; + case "RemoveCustomField title": + Assert.IsTrue (tag.RemoveCustomField ("title"), "the Content Description name matches in any case"); + (attribute, expected) = ("Title", []); + break; + case "SetCustomField Author": + Assert.IsTrue (tag.SetCustomField ("Author", "new")); + (attribute, expected) = ("Author", New); + break; + case "Performers": + tag.Performers = NewN2; + (attribute, expected) = ("Author", NewN2); + break; + case "Artist": + tag.Artist = "new"; + (attribute, expected) = ("Author", New); + break; + case "Title": + tag.Title = "new"; + (attribute, expected) = ("Title", New); + break; + default: + var source = new VorbisComment ("source") { Artist = "new", Title = "new" }; + source.CopyTo (tag); + (attribute, expected) = ("Author", New); + break; + } + + var again = Read (file.Render (original)).Tag; + + Assert.IsFalse (HasDescriptor (again, attribute), $"{write} left the old {attribute} descriptor"); + CollectionAssert.AreEqual (expected, again.GetCustomField (attribute).ToArray (), write); + } + + [TestMethod] + public void FfmpegFile_WriteBack_ChangesNothing () + { + var original = FfmpegFile (); + var untouched = Read (original).Render (original); + var file = Read (original); + + Assert.AreEqual ("old", file.Tag.Artist); + CollectionAssert.AreEqual (Old, file.Tag.Performers); + file.Tag.Artist = file.Tag.Artist; + file.Tag.Title = file.Tag.Title; + file.Tag.Performers = file.Tag.Performers; + Assert.IsTrue (file.Tag.SetCustomField ("Author", [.. file.Tag.GetCustomField ("Author")])); + + // SetCustomField always rewrites, so compare what it leaves: one value, and the Title copy untouched. + var again = Read (file.Render (original)).Tag; + CollectionAssert.AreEqual (Old, again.GetCustomField ("Author").ToArray ()); + Assert.IsFalse (HasDescriptor (again, "Author")); + Assert.IsTrue (HasDescriptor (again, "title"), "a write of Author leaves the title copy alone"); + + var mapped = Read (original); + mapped.Tag.Artist = mapped.Tag.Artist; + mapped.Tag.Title = mapped.Tag.Title; + mapped.Tag.Performers = mapped.Tag.Performers; + CollectionAssert.AreEqual (untouched, mapped.Render (original), "a mapped write-back changes nothing"); + } + + /// + /// The twin of the Content Description case rule for every other name: ASF attribute names match in any case + /// (the library's rule since the Extended Content Description reader), so a set or remove by one spelling + /// replaces a descriptor and the file-level records stored under another. + /// + [TestMethod] + public void OtherName_SetAndRemove_MatchAnySpelling () + { + static byte[] Stored () => File ( + AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.Record ("wm/albumtitle", "lib")), + AsfDescriptor.CreateString ("WM/AlbumTitle", "old")); + + var file = Read (Stored ()); + Assert.IsTrue (file.Tag.SetCustomField ("wm/ALBUMTITLE", "new")); + var set = Read (file.Render (Stored ())).Tag; + CollectionAssert.AreEqual (New, set.GetCustomField ("WM/AlbumTitle").ToArray ()); + Assert.AreEqual (1, set.ExtendedContentDescription.Descriptors.Count (d => string.Equals (d.Name, "WM/AlbumTitle", StringComparison.OrdinalIgnoreCase))); + + file = Read (Stored ()); + Assert.IsTrue (file.Tag.RemoveCustomField ("WM/ALBUMTITLE")); + var removed = Read (file.Render (Stored ())).Tag; + Assert.AreEqual (0, removed.GetCustomField ("wm/albumtitle").Count); + Assert.IsFalse (HasDescriptor (removed, "WM/AlbumTitle")); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/CustomFieldFileRoundTripTests.cs b/tests/TagLibSharp2.Tests/Core/CustomFieldFileRoundTripTests.cs new file mode 100644 index 00000000..82531d86 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/CustomFieldFileRoundTripTests.cs @@ -0,0 +1,433 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aiff; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Dff; +using TagLibSharp2.Dsf; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mp4; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Musepack; +using TagLibSharp2.Ogg; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Asf; +using TagLibSharp2.WavPack; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A custom field set through survives a save and a reopen in every container. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Core")] +public class CustomFieldFileRoundTripTests +{ + const string Name = "MY_CUSTOM_FIELD"; + + /// One container: build a file, read it, render it with its changes. + sealed record Container ( + Func Build, + Func Read, + Func Render, + bool MultiValue = true, + string Name = Name); + + static readonly Dictionary Containers = new () { + ["Flac"] = new ( + () => TestBuilders.Flac.CreateWithVorbisComment ("t"), + d => FlacFile.Read (d).File!, + (f, o) => ((FlacFile)f).Render (o).ToArray ()), + ["Mp3"] = new ( + CreateMinimalMp3, + d => Mp3File.Read (d).File!, + (f, o) => ((Mp3File)f).Render (o).ToArray ()), + ["OggVorbis"] = new ( + () => TestBuilders.Ogg.CreateMinimalFile (), + d => OggVorbisFile.Read (d).File!, + (f, o) => ((OggVorbisFile)f).Render (o).ToArray ()), + ["Opus"] = new ( + () => TestBuilders.Opus.CreateMinimalFile (), + d => OggOpusFile.Read (d).File!, + (f, o) => ((OggOpusFile)f).Render (o).ToArray ()), + ["OggFlac"] = new ( + () => TestBuilders.OggFlac.CreateWithMetadata ("t"), + d => OggFlacFile.Read (d).File!, + (f, o) => ((OggFlacFile)f).Render (o)), + ["MonkeysAudio"] = new ( + () => TestBuilders.MonkeysAudio.CreateWithMetadata ("t"), + d => MonkeysAudioFile.Read (d).File!, + (f, o) => ((MonkeysAudioFile)f).Render (o)), + ["WavPack"] = new ( + () => TestBuilders.WavPack.CreateWithMetadata ("t"), + d => WavPackFile.Read (d).File!, + (f, o) => ((WavPackFile)f).Render (o)), + ["Musepack"] = new ( + () => TestBuilders.Musepack.CreateWithMetadata ("t"), + d => MusepackFile.Read (d).File!, + (f, o) => ((MusepackFile)f).Render (o)), + ["Mp4"] = new ( + () => TestBuilders.Mp4.CreateWithMetadata ("t"), + d => Mp4File.Read (d).File!, + (f, o) => ((Mp4File)f).Render (o).ToArray ()), + ["Asf"] = new ( + () => AsfTestBuilder.CreateMinimalWma ("t"), + d => AsfFile.Read (d).File!, + (f, o) => ((AsfFile)f).Render (o)), + ["WavId3"] = new ( + () => WithId3 (TestBuilders.Wav.CreateMinimal ()), + d => WavFile.Read (d).File!, + (f, o) => ((WavFile)f).Render ().ToArray ()), + ["WavInfo"] = new ( + () => WithInfo (TestBuilders.Wav.CreateMinimal ()), + d => WavFile.Read (d).File!, + (f, o) => ((WavFile)f).Render ().ToArray (), + MultiValue: false, + Name: "IXYZ"), + ["Aiff"] = new ( + () => TestBuilders.Aiff.CreateMinimal (), + d => WithTag (AiffFile.Read (d).File!), + (f, o) => ((AiffFile)f).Render ().ToArray ()), + ["AviInfo"] = new ( + () => { + var builder = new TagLibSharp2.Tests.Riff.AviTestBuilder (); + builder.Info.Add (("INAM", "t")); + return builder.Build (); + }, + d => AviFile.Read (d).File!, + (f, o) => ((AviFile)f).Render (o).ToArray (), + MultiValue: false, + Name: "IXYZ"), + ["AacId3"] = new ( + () => [.. TagLibSharp2.Tests.Aac.AacTestBuilder.Id3v2Bytes ("t"), .. TagLibSharp2.Tests.Aac.AacTestBuilder.Adts (4)], + d => TagLibSharp2.Aac.AacFile.Read (d).File!, + (f, o) => ((TagLibSharp2.Aac.AacFile)f).Render (o).ToArray ()), + ["AacApe"] = new ( + () => [.. TagLibSharp2.Tests.Aac.AacTestBuilder.Adts (4), .. TagLibSharp2.Tests.Aac.AacTestBuilder.ApeBytes ("t")], + d => TagLibSharp2.Aac.AacFile.Read (d).File!, + (f, o) => ((TagLibSharp2.Aac.AacFile)f).Render (o).ToArray ()), + ["Dsf"] = new ( + () => TestBuilders.Dsf.CreateWithMetadata ("t"), + d => DsfFile.Read (d).File!, + (f, o) => ((DsfFile)f).Render ().ToArray ()), + ["Dff"] = new ( + () => TestBuilders.Dff.CreateWithId3v2 ("t"), + d => DffFile.Read (d).File!, + (f, o) => ((DffFile)f).Render ().ToArray ()), + }; + + public static IEnumerable ContainerNames => Containers.Keys.Select (k => new object[] { k }); + + [TestMethod] + [DynamicData (nameof (ContainerNames))] + public void CustomField_SurvivesSaveAndReopen (string container) + { + var c = Containers[container]; + var original = c.Build (); + var file = c.Read (original); + var values = c.MultiValue ? new[] { "first", "second" } : ["only"]; + + Assert.IsNotNull (file.Tag, "the builder should give the file a tag"); + Assert.IsTrue (file.Tag.SupportsCustomFields); + Assert.IsTrue (file.Tag.SetCustomField (c.Name, values)); + + var reopened = c.Read (c.Render (file, original)); + + Assert.IsNotNull (reopened.Tag); + CollectionAssert.AreEqual (values, reopened.Tag.GetCustomField (c.Name).ToArray ()); + } + + [TestMethod] + [DynamicData (nameof (ContainerNames))] + public void CustomField_RemovedField_StaysRemovedAfterReopen (string container) + { + var c = Containers[container]; + var original = c.Build (); + var file = c.Read (original); + file.Tag!.SetCustomField (c.Name, "x"); + var saved = c.Render (file, original); + + var again = c.Read (saved); + Assert.IsTrue (again.Tag!.RemoveCustomField (c.Name)); + var reopened = c.Read (c.Render (again, saved)); + + Assert.AreEqual (0, reopened.Tag?.GetCustomField (c.Name).Count ?? 0); + } + + [TestMethod] + [DataRow ("WavId3")] + [DataRow ("Aiff")] + [DataRow ("Dsf")] + [DataRow ("Dff")] + public void Id3Container_TagWithOnlyACustomField_IsStillWritten (string container) + { + var c = Containers[container]; + var original = c.Build (); + var file = c.Read (original); + file.Tag!.Clear (); + file.Tag.SetCustomField (Name, "kept"); + + var reopened = c.Read (c.Render (file, original)); + + Assert.IsNotNull (reopened.Tag); + AssertValues (reopened.Tag.GetCustomField (Name), "kept"); + } + + [TestMethod] + public void Mp3_WithBothTags_CustomFieldGoesToId3v2Only () + { + var original = CreateMinimalMp3 (); + var file = Mp3File.Read (original).File!; + file.Id3v1Tag = new TagLibSharp2.Id3.Id3v1Tag { Title = "t" }; + + Assert.IsTrue (file.Tag!.SetCustomField (Name, "x")); + var reopened = Mp3File.Read (file.Render (original).Span).File!; + + AssertValues (reopened.Id3v2Tag!.GetCustomField (Name), "x"); + Assert.AreEqual ("t", reopened.Id3v1Tag!.Title); + } + + [TestMethod] + public void Mp3_Id3v23Tag_RoundTripsSeveralValues () + { + var original = CreateMinimalMp3 (version: 3); + var file = Mp3File.Read (original).File!; + Assert.AreEqual (3, file.Id3v2Tag!.Version); + + Assert.IsTrue (file.Tag!.SetCustomField (Name, "a", "b")); + var reopened = Mp3File.Read (file.Render (original).Span).File!; + + Assert.AreEqual (3, reopened.Id3v2Tag!.Version); + AssertValues (reopened.Tag!.GetCustomField (Name), "a", "b"); + } + + [TestMethod] + public void Flac_WithoutVorbisComment_RefusedNameAddsNoBlock () + { + var original = TestBuilders.Flac.CreateWithPicture (); + var file = FlacFile.Read (original).File!; + Assert.IsNull (file.VorbisComment); + + Assert.IsFalse (file.Tag!.SetCustomField ("A=B", "x")); + Assert.IsNull (file.VorbisComment); + Assert.IsTrue (file.Tag.SetCustomField ("GOOD", "x")); + Assert.IsNotNull (file.VorbisComment); + + var reopened = FlacFile.Read (file.Render (original).Span).File!; + AssertValues (reopened.Tag!.GetCustomField ("good"), "x"); + } + + [TestMethod] + public void Flac_UnchangedSave_IsByteIdenticalAfterCustomFieldRoundTrip () + { + var original = TestBuilders.Flac.CreateWithVorbisComment ("t"); + var file = FlacFile.Read (original).File!; + file.Tag!.SetCustomField (Name, "a", "b"); + var saved = file.Render (original).ToArray (); + + var again = FlacFile.Read (saved).File!; + var resaved = again.Render (saved).ToArray (); + + CollectionAssert.AreEqual (saved, resaved); + } + + static void AssertValues (IReadOnlyList actual, params string[] expected) => + CollectionAssert.AreEqual (expected, actual.ToArray ()); + + /// + /// Every file whose Tag is a view over tags of its own: the combined views (MP3, raw AAC, AVI with + /// an ID3v2 chunk, an MPEG program stream with an update tag) hold two or three tags that store custom + /// fields, and FLAC, AIFF, and WAV hold one. + /// + static readonly Dictionary Views = new () { + ["Mp3Id3v2Id3v1"] = new ( + () => { + var file = Mp3File.Read (CreateMinimalMp3 ()).File!; + file.Id3v1Tag = new TagLibSharp2.Id3.Id3v1Tag { Title = "t" }; + return file.Render (CreateMinimalMp3 ()).ToArray (); + }, + d => Mp3File.Read (d).File!, + (f, o) => ((Mp3File)f).Render (o).ToArray ()), + ["AacId3v2ApeId3v1"] = new ( + () => [.. TagLibSharp2.Tests.Aac.AacTestBuilder.Id3v2Bytes ("t"), .. TagLibSharp2.Tests.Aac.AacTestBuilder.Adts (4), + .. TagLibSharp2.Tests.Aac.AacTestBuilder.ApeBytes ("t"), .. TagLibSharp2.Tests.Aac.AacTestBuilder.Id3v1Bytes ("t")], + d => TagLibSharp2.Aac.AacFile.Read (d).File!, + (f, o) => ((TagLibSharp2.Aac.AacFile)f).Render (o).ToArray ()), + ["AviInfoId32"] = new ( + () => { + var builder = new TagLibSharp2.Tests.Riff.AviTestBuilder { Id3 = new Id3v2Tag { Title = "t" }.Render ().ToArray () }; + builder.Info.Add (("INAM", "t")); + return builder.Build (); + }, + d => AviFile.Read (d).File!, + (f, o) => ((AviFile)f).Render (o).ToArray ()), + ["MpegPsUpdateTag"] = new ( + () => [.. new Id3v2Tag (Id3v2Version.V24) { Title = "Front" }.Render ().ToArray (), + .. TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.ProgramStream (), + .. TagLibSharp2.Tests.Mpeg.MpegPsAppendedTagTests.UpdateTag ("Back")], + d => MpegPsFile.Read (d).File!, + (f, o) => ((MpegPsFile)f).Render (o).ToArray ()), + ["Flac"] = Containers["Flac"], + ["Aiff"] = Containers["Aiff"], + ["WavId3"] = Containers["WavId3"], + }; + + public static IEnumerable ViewCases => + Views.Keys.SelectMany (k => new[] { new object[] { k, 1 }, [k, 2] }); + + const string ViewName = "IXYZ"; // a FOURCC, an APE key, and a TXXX description alike + + /// The format tags the file's Tag reads (itself, when it is one) that store custom fields. + static List StoringLeaves (Tag view) => + [.. view.Leaves ().Where (t => TagTypeClassification.IsLeaf (t.GetType ()) && t.SupportsCustomFields)]; + + /// How many tags of each file store custom fields: ID3v1 stores none, and WAV's Tag is its ID3v2 tag. + static readonly Dictionary StoringTags = new () { + ["Mp3Id3v2Id3v1"] = 1, + ["AacId3v2ApeId3v1"] = 2, + ["AviInfoId32"] = 2, + ["MpegPsUpdateTag"] = 2, + ["Flac"] = 1, + ["Aiff"] = 1, + ["WavId3"] = 1, + }; + + /// Every tag holds exactly or not the name, and at least one holds them. + static void AssertNoStaleCopy (Tag view, string[] values, string step) + { + var leaves = StoringLeaves (view); + CollectionAssert.AreEqual (values, view.GetCustomField (ViewName).ToArray (), $"{step}: the view"); + foreach (var leaf in leaves) { + var held = leaf.GetCustomField (ViewName).ToArray (); + Assert.IsTrue (held.Length == 0 || held.SequenceEqual (values), + $"{step}: {leaf.GetType ().Name} holds [{string.Join (",", held)}]"); + } + if (values.Length > 0) + Assert.IsTrue (leaves.Any (l => l.GetCustomField (ViewName).SequenceEqual (values)), $"{step}: some tag holds the values"); + } + + [TestMethod] + [DynamicData (nameof (ViewCases))] + public void View_SetRemoveClear_LeavesNoTagWithAnOldValue (string container, int count) + { + var c = Views[container]; + var original = c.Build (); + var file = c.Read (original); + var view = file.Tag!; + var leaves = StoringLeaves (view); + Assert.AreEqual (StoringTags[container], leaves.Count, $"{container}: tags that store custom fields"); + + // Every tag starts with an old value, so a tag the set skips would show it. + foreach (var leaf in leaves) + Assert.IsTrue (leaf.SetCustomField (ViewName, "old"), leaf.GetType ().Name); + var withOld = c.Render (file, original); + file = c.Read (withOld); + + string[] values = count == 1 ? ["new"] : ["new", "second"]; + Assert.IsTrue (file.Tag!.SetCustomField (ViewName, values)); + AssertNoStaleCopy (file.Tag, values, "after the set"); + var saved = c.Render (file, withOld); + file = c.Read (saved); + AssertNoStaleCopy (file.Tag!, values, "after the set and a reopen"); + + Assert.IsTrue (file.Tag!.RemoveCustomField (ViewName)); + AssertNoStaleCopy (file.Tag, [], "after the remove"); + var removed = c.Render (file, saved); + AssertNoStaleCopy (c.Read (removed).Tag ?? new TagLibSharp2.Riff.RiffInfoTag (), [], "after the remove and a reopen"); + + file = c.Read (saved); + file.Tag!.Clear (); + var cleared = c.Read (c.Render (file, saved)).Tag; + Assert.AreEqual (0, cleared?.GetCustomField (ViewName).Count ?? 0, "after Clear"); + foreach (var leaf in cleared is null ? [] : StoringLeaves (cleared)) + Assert.AreEqual (0, leaf.GetCustomField (ViewName).Count, $"after Clear: {leaf.GetType ().Name}"); + } + + [TestMethod] + public void CombinedTag_TwoStoringTags_SetAndRemoveReachBoth () + { + // ID3v2 and APE both store any number of values: a set writes both and a remove clears both. + var id3 = new Id3v2Tag (Id3v2Version.V24); + var ape = new ApeTag (); + var view = new CombinedTag (id3, ape); + + Assert.IsTrue (view.SetCustomField ("My Field", "a", "b")); + CollectionAssert.AreEqual (AB, id3.GetCustomField ("My Field").ToArray ()); + CollectionAssert.AreEqual (AB, ape.GetCustomField ("My Field").ToArray ()); + + Assert.IsTrue (view.RemoveCustomField ("My Field")); + Assert.AreEqual (0, id3.GetCustomField ("My Field").Count); + Assert.AreEqual (0, ape.GetCustomField ("My Field").Count); + } + + [TestMethod] + public void CombinedTag_TagThatRefusesTheValues_LosesItsOldValue () + { + // RIFF INFO holds one value under a four-character name; ID3v2 holds any number. INFO comes first. + var info = new TagLibSharp2.Riff.RiffInfoTag (); + info.SetCustomField ("IENG", "E"); + var id3 = new Id3v2Tag (Id3v2Version.V24); + var view = new CombinedTag (info, id3); + + Assert.IsTrue (view.SetCustomField ("IENG", "a", "b")); + Assert.AreEqual (0, info.GetCustomField ("IENG").Count, "INFO cannot hold two values, so it keeps none"); + CollectionAssert.AreEqual (AB, id3.GetCustomField ("IENG").ToArray ()); + CollectionAssert.AreEqual (AB, view.GetCustomField ("IENG").ToArray ()); + + // One value fits both again. + Assert.IsTrue (view.SetCustomField ("IENG", "E2")); + Assert.AreEqual ("E2", info.GetField ("IENG")); + } + + [TestMethod] + public void CombinedTag_NoTagCanStoreTheValues_ReturnsFalseAndChangesNothing () + { + var info = new TagLibSharp2.Riff.RiffInfoTag (); + info.SetCustomField ("IENG", "E"); + var view = new CombinedTag (info, new TagLibSharp2.Id3.Id3v1Tag ()); + + Assert.IsFalse (view.SetCustomField ("IENG", "a", "b")); + Assert.AreEqual ("E", info.GetField ("IENG"), "a refused set leaves the old value where it was"); + } + + static readonly string[] AB = ["a", "b"]; + + static byte[] CreateMinimalMp3 () => CreateMinimalMp3 (4); + + static byte[] CreateMinimalMp3 (byte version) + { + using var builder = new BinaryDataBuilder (256); + builder.AddStringLatin1 ("ID3"); + builder.Add (version); + builder.Add (0x00); // revision + builder.Add (0x00); // flags + builder.Add (new byte[] { 0x00, 0x00, 0x00, 0x00 }); // empty tag + builder.Add (new byte[] { 0xFF, 0xFB, 0x90, 0x00 }); // MPEG-1 Layer III frame header + builder.AddZeros (413); + return builder.ToBinaryData ().ToArray (); + } + + static byte[] WithId3 (byte[] wav) + { + var file = WavFile.Read (wav).File!; + file.Id3v2Tag = new Id3v2Tag { Title = "t" }; + return file.Render ().ToArray (); + } + + static byte[] WithInfo (byte[] wav) + { + var file = WavFile.Read (wav).File!; + file.InfoTag = new RiffInfoTag { Title = "t" }; + return file.Render ().ToArray (); + } + + static AiffFile WithTag (AiffFile file) + { + file.Id3v2Tag ??= new Id3v2Tag { Title = "t" }; + return file; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/CustomFieldIntegrationTests.cs b/tests/TagLibSharp2.Tests/Core/CustomFieldIntegrationTests.cs new file mode 100644 index 00000000..38644a82 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/CustomFieldIntegrationTests.cs @@ -0,0 +1,96 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aiff; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Mp4; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Ogg; +using TagLibSharp2.Riff; +using TagLibSharp2.WavPack; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// Custom fields on real files. Each test is skipped unless its environment variable names a file. +/// +/// +/// Example: TAGLIBSHARP2_TEST_FLAC=/path/song.flac dotnet test --filter "FullyQualifiedName~CustomFieldIntegrationTests". +/// The file is copied to a temporary directory; the original is never written. +/// +[TestClass] +[TestCategory ("Integration")] +[TestCategory ("Manual")] +public class CustomFieldIntegrationTests : FileFormatTestBase +{ + const string Name = "TAGLIBSHARP2_CUSTOM"; + + [TestMethod] + [DataRow ("TAGLIBSHARP2_TEST_FLAC", "FLAC")] + [DataRow ("TAGLIBSHARP2_TEST_MP3", "MP3")] + [DataRow ("TAGLIBSHARP2_TEST_M4A", "M4A")] + [DataRow ("TAGLIBSHARP2_TEST_OGG", "Ogg Vorbis or Opus")] + [DataRow ("TAGLIBSHARP2_TEST_APE", "Monkey's Audio")] + [DataRow ("TAGLIBSHARP2_TEST_WV", "WavPack")] + [DataRow ("TAGLIBSHARP2_TEST_WMA", "WMA")] + [DataRow ("TAGLIBSHARP2_TEST_MKV", "Matroska")] + [DataRow ("TAGLIBSHARP2_TEST_WAV", "WAV")] + [DataRow ("TAGLIBSHARP2_TEST_AIFF", "AIFF")] + public void RealFile_CustomField_SurvivesSaveAndReopen (string envVar, string fileType) + { + var source = SkipIfNoTestFile (envVar, fileType); + var dir = Path.Combine (Path.GetTempPath (), "tls2-custom-" + Guid.NewGuid ().ToString ("N")); + Directory.CreateDirectory (dir); + var path = Path.Combine (dir, Path.GetFileName (source)); + File.Copy (source, path); + try { + var opened = MediaFile.Read (path); + Assert.IsTrue (opened.IsSuccess, opened.Error); + var tag = opened.Tag; + Assert.IsNotNull (tag, "the sample needs a tag to write into"); + Assert.IsTrue (tag.SupportsCustomFields); + + // RIFF INFO holds one value under a four-character code. + var name = tag is RiffInfoTag ? "IXYZ" : Name; + var values = tag is RiffInfoTag ? new[] { "only" } : ["first", "second"]; + var title = tag.Title; + Assert.IsTrue (tag.SetCustomField (name, values)); + Save (opened.File!, path); + + var reopened = MediaFile.Read (path); + Assert.IsTrue (reopened.IsSuccess, reopened.Error); + CollectionAssert.AreEqual (values, reopened.Tag!.GetCustomField (name).ToArray ()); + Assert.AreEqual (title, reopened.Tag.Title); + + Assert.IsTrue (reopened.Tag.RemoveCustomField (name)); + Save (reopened.File!, path); + Assert.AreEqual (0, MediaFile.Read (path).Tag!.GetCustomField (name).Count); + } finally { + Directory.Delete (dir, recursive: true); + } + } + + static void Save (object file, string path) + { + var original = File.ReadAllBytes (path); + var result = file switch { + FlacFile f => f.SaveToFile (path, original), + Mp3File f => f.SaveToFile (path, original), + Mp4File f => f.SaveToFile (path, original), + OggVorbisFile f => f.SaveToFile (path, original), + OggOpusFile f => f.SaveToFile (path, original), + MonkeysAudioFile f => f.SaveToFile (path, original), + WavPackFile f => f.SaveToFile (path, original), + AsfFile f => f.SaveToFile (path, original), + MatroskaFile f => f.SaveToFile (path, original), + WavFile f => f.SaveToFile (path), + AiffFile f => f.SaveToFile (path), + _ => throw new AssertFailedException ($"No save path for {file.GetType ().Name}") + }; + Assert.IsTrue (result.IsSuccess, result.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs new file mode 100644 index 00000000..0881417b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs @@ -0,0 +1,889 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using System.Text; +using TagLibSharp2.Ape; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Matroska; +using TagLibSharp2.Mp4; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Asf; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The custom field API on every : one name, its values, in the format's own storage. +/// +/// +/// Invariant: after SetCustomField (name, values) returns true, GetCustomField (name) on the tag +/// and on the tag parsed from its rendering returns exactly the non-empty values, in order. After it returns +/// false, the tag renders the same bytes as before. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Core")] +public class CustomFieldTests +{ + // Each entry: a fresh tag, and a function that renders and reparses it. + public static IEnumerable MultiValueTags => [ + ["Vorbis", "MY_FIELD"], + ["Ape", "My Field"], + ["Id3v24", "My Field"], + ["Id3v23", "My Field"], + ["Mp4", "My Field"], + ["Asf", "My/Field"], + ["Matroska", "MY_FIELD"], + ]; + + public static IEnumerable AllSupportingTags => [ + .. MultiValueTags, + ["RiffInfo", "IXYZ"], + ]; + + static Tag Create (string format) => format switch { + "Vorbis" => new VorbisComment ("test"), + "Ape" => new ApeTag (), + "Id3v24" => new Id3v2Tag (Id3v2Version.V24), + "Id3v23" => new Id3v2Tag (Id3v2Version.V23), + "Mp4" => new Mp4Tag (), + "Asf" => new AsfTag (), + "Matroska" => new MatroskaTag (), + "RiffInfo" => new RiffInfoTag (), + _ => throw new ArgumentOutOfRangeException (nameof (format)) + }; + + static Tag Reparse (Tag tag) => tag switch { + VorbisComment v => VorbisComment.Read (v.Render ().Span).Tag!, + ApeTag a => ApeTag.Parse (a.RenderWithOptions (includeHeader: true).Span).Tag!, + Id3v2Tag i => Id3v2Tag.Read (i.Render ().Span).Tag!, + Mp4Tag m => ReparseMp4 (m), + AsfTag a => ReparseAsf (a), + MatroskaTag m => ReparseMatroska (m), + RiffInfoTag r => r.IsEmpty ? new RiffInfoTag () : RiffInfoTag.Parse (r.Render ().Slice (8))!, + _ => throw new ArgumentOutOfRangeException (nameof (tag)) + }; + + static Mp4Tag ReparseMp4 (Mp4Tag tag) + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + file.Tag = tag; + var again = Mp4File.Read (file.Render (original).Span); + Assert.IsTrue (again.IsSuccess, again.Error); + // An empty ilst is not written, so the reopened file has no tag. + return again.File!.Tag ?? new Mp4Tag (); + } + + static AsfTag ReparseAsf (AsfTag tag) + { + // Values 2..n live in the Metadata Library Object, so go through a whole file. + var original = AsfTestBuilder.CreateMinimalWma (); + var file = AsfFile.Read (original).File!; + foreach (var name in new[] { "Title", "Author", "Copyright", "Description", "Rating" }) + file.Tag.SetCustomField (name, [.. tag.GetCustomField (name)]); + var names = tag.ExtendedContentDescription.Descriptors.Select (d => d.Name) + .Concat (tag.LibraryRecords?.Select (r => r.Name) ?? []) + .Distinct (StringComparer.OrdinalIgnoreCase); + foreach (var name in names) + file.Tag.SetCustomField (name, [.. tag.GetCustomField (name)]); + var again = AsfFile.Read (file.Render (original)); + Assert.IsTrue (again.IsSuccess, again.Error); + return again.File!.Tag; + } + + static MatroskaTag ReparseMatroska (MatroskaTag tag) + { + // The Tags element is the whole tag. Wrap it in a segment and read it back. + var ebml = MatroskaBytes.Master (0x1A45DFA3, MatroskaBytes.Element (0x4282, "matroska"u8)); + var segment = MatroskaBytes.Master (0x18538067, tag.Render ().ToArray ()); + var again = MatroskaFile.Read ([.. ebml, .. segment]); + Assert.IsTrue (again.IsSuccess, again.Error); + return again.File!.Tag; + } + + [TestMethod] + [DynamicData (nameof (MultiValueTags))] + public void SetCustomField_SeveralValues_ReadBackInOrderAfterRender (string format, string name) + { + var tag = Create (format); + + Assert.IsTrue (tag.SupportsCustomFields); + Assert.IsTrue (tag.SetCustomField (name, "one", "two", "three")); + + AssertValues (tag.GetCustomField (name), "one", "two", "three"); + AssertValues (Reparse (tag).GetCustomField (name), "one", "two", "three"); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_OneValue_ReadBackAfterRender (string format, string name) + { + var tag = Create (format); + + Assert.IsTrue (tag.SetCustomField (name, "café")); + + AssertValues (Reparse (tag).GetCustomField (name), "café"); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_ReplacesEarlierValues (string format, string name) + { + var tag = Create (format); + tag.SetCustomField (name, "old"); + + Assert.IsTrue (tag.SetCustomField (name, "new")); + + AssertValues (Reparse (tag).GetCustomField (name), "new"); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_NullAndEmptyValuesSkipped (string format, string name) + { + var tag = Create (format); + + Assert.IsTrue (tag.SetCustomField (name, null!, "", "kept", "")); + + AssertValues (tag.GetCustomField (name), "kept"); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_NoValues_RemovesTheField (string format, string name) + { + var tag = Create (format); + tag.SetCustomField (name, "x"); + + Assert.IsTrue (tag.SetCustomField (name)); + Assert.AreEqual (0, tag.GetCustomField (name).Count); + Assert.IsTrue (tag.SetCustomField (name, (string[])null!)); + Assert.AreEqual (0, Reparse (tag).GetCustomField (name).Count); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_ValueWithNul_RefusedAndTagUnchanged (string format, string name) + { + var tag = Create (format); + tag.SetCustomField (name, "before"); + var before = RenderOf (tag); + + Assert.IsFalse (tag.SetCustomField (name, "a\0b")); + + AssertValues (tag.GetCustomField (name), "before"); + CollectionAssert.AreEqual (before, RenderOf (tag)); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void CustomField_EmptyOrNulName_Refused (string format, string name) + { + _ = name; + var tag = Create (format); + var before = RenderOf (tag); + + Assert.IsFalse (tag.SetCustomField ("", "x")); + Assert.IsFalse (tag.SetCustomField ("AB\0C", "x")); + Assert.IsFalse (tag.RemoveCustomField ("")); + Assert.AreEqual (0, tag.GetCustomField ("").Count); + CollectionAssert.AreEqual (before, RenderOf (tag)); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void RemoveCustomField_ReportsWhetherAValueWasThere (string format, string name) + { + var tag = Create (format); + tag.SetCustomField (name, "x"); + + Assert.IsTrue (tag.RemoveCustomField (name)); + Assert.IsFalse (tag.RemoveCustomField (name)); + Assert.AreEqual (0, Reparse (tag).GetCustomField (name).Count); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void CustomField_NullName_Throws (string format, string name) + { + _ = name; + var tag = Create (format); + + Assert.ThrowsExactly (() => tag.GetCustomField (null!)); + Assert.ThrowsExactly (() => tag.SetCustomField (null!, "x")); + Assert.ThrowsExactly (() => tag.RemoveCustomField (null!)); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void SetCustomField_LeavesOtherFieldsAlone (string format, string name) + { + var tag = Create (format); + tag.Comment = "comment"; + + tag.SetCustomField (name, "x"); + tag.RemoveCustomField (name); + + Assert.AreEqual ("comment", Reparse (tag).Comment); + } + + static void AssertValues (IReadOnlyList actual, params string[] expected) => + CollectionAssert.AreEqual (expected, actual.ToArray ()); + + static byte[] RenderOf (Tag tag) => tag switch { + AsfTag a => [.. a.Render ().ToArray (), .. a.RenderContentDescription ().ToArray ()], + _ => tag.Render ().ToArray () + }; + + // ───────────────────────── Unsupported ───────────────────────── + + [TestMethod] + public void Id3v1_DoesNotSupportCustomFields () + { + var tag = new Id3v1Tag { Title = "t" }; + var before = tag.Render ().ToArray (); + + Assert.IsFalse (tag.SupportsCustomFields); + Assert.IsFalse (tag.SetCustomField ("MY_FIELD", "x")); + Assert.IsFalse (tag.RemoveCustomField ("MY_FIELD")); + Assert.AreEqual (0, tag.GetCustomField ("MY_FIELD").Count); + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + Assert.ThrowsExactly (() => tag.GetCustomField (null!)); + Assert.ThrowsExactly (() => tag.SetCustomField (null!)); + Assert.ThrowsExactly (() => tag.RemoveCustomField (null!)); + } + + // ───────────────────────── Vorbis ───────────────────────── + + [TestMethod] + public void Vorbis_NameIsCaseInsensitiveAndWrittenUpperCase () + { + var tag = new VorbisComment ("test"); + + tag.SetCustomField ("Mood", "calm"); + + AssertValues (tag.GetCustomField ("MOOD"), "calm"); + Assert.AreEqual ("MOOD", tag.Fields[0].Name); + Assert.IsTrue (tag.SetCustomField ("mood", "loud")); + Assert.AreEqual (1, tag.Fields.Count); + } + + [TestMethod] + public void Vorbis_EachValueIsItsOwnField () + { + var tag = new VorbisComment ("test"); + + tag.SetCustomField ("MY_FIELD", "a", "b"); + + var text = Encoding.UTF8.GetString (tag.Render ().ToArray ()); + StringAssert.Contains (text, "MY_FIELD=a"); + StringAssert.Contains (text, "MY_FIELD=b"); + } + + [TestMethod] + public void Vorbis_ReplacedValuesKeepTheirPosition () + { + var tag = new VorbisComment ("test"); + tag.AddField ("A", "1"); + tag.AddField ("MY_FIELD", "old"); + tag.AddField ("Z", "2"); + + tag.SetCustomField ("MY_FIELD", "x", "y"); + + AssertValues (tag.Fields.Select (f => f.Name).ToList (), "A", "MY_FIELD", "MY_FIELD", "Z"); + } + + [TestMethod] + [DataRow ("A=B")] + [DataRow ("TILDE~")] + [DataRow ("CAFÉ")] + [DataRow ("TAB\t")] + [DataRow ("METADATA_BLOCK_PICTURE")] + [DataRow ("metadata_block_picture")] + public void Vorbis_InvalidOrReservedName_Refused (string name) + { + var tag = new VorbisComment ("test"); + + Assert.IsFalse (tag.SetCustomField (name, "x")); + Assert.IsFalse (tag.RemoveCustomField (name)); + Assert.AreEqual (0, tag.Fields.Count); + } + + [TestMethod] + public void Vorbis_MappedName_IsTheMappedProperty () + { + var tag = new VorbisComment ("test") { Title = "Old" }; + + tag.SetCustomField ("title", "New"); + + Assert.AreEqual ("New", tag.Title); + tag.Title = "Again"; + AssertValues (tag.GetCustomField ("TITLE"), "Again"); + } + + [TestMethod] + public void Vorbis_PicturesUntouchedByCustomFields () + { + var tag = new VorbisComment ("test"); + tag.AddPicture (new FlacPicture ("image/png", PictureType.FrontCover, "", new BinaryData ([1, 2, 3]), 1, 1, 24, 0)); + + tag.SetCustomField ("MY_FIELD", "x"); + + Assert.AreEqual (1, Reparse (tag).Pictures.Length); + Assert.AreEqual (0, tag.GetCustomField ("METADATA_BLOCK_PICTURE").Count); + } + + // ───────────────────────── APE ───────────────────────── + + [TestMethod] + [DataRow ("A")] + [DataRow ("ID3")] + [DataRow ("tag")] + [DataRow ("OggS")] + [DataRow ("MP+")] + [DataRow ("Café")] + [DataRow ("Tab\tKey")] + [DataRow ("Cover Art (Front)")] + [DataRow ("cover art (custom)")] + public void Ape_InvalidOrReservedKey_Refused (string key) + { + var tag = new ApeTag (); + + Assert.IsFalse (tag.SetCustomField (key, "x")); + Assert.AreEqual (0, tag.ItemCount); + } + + [TestMethod] + public void Ape_KeyLengthBounds () + { + var tag = new ApeTag (); + + Assert.IsTrue (tag.SetCustomField ("AB", "x")); + Assert.IsTrue (tag.SetCustomField (new string ('K', 255), "x")); + Assert.IsFalse (tag.SetCustomField (new string ('K', 256), "x")); + Assert.AreEqual (2, tag.ItemCount); + } + + [TestMethod] + public void Ape_ValuesAreSeparatedByZeroInOneItem () + { + var tag = new ApeTag (); + + tag.SetCustomField ("My Field", "a", "b"); + + var rendered = tag.Render ().ToArray (); + var needle = "My Field\0a\0b"u8.ToArray (); + Assert.IsTrue (rendered.AsSpan ().IndexOf (needle) >= 0); + Assert.AreEqual (1, tag.ItemCount); + } + + [TestMethod] + public void Ape_KeyIsCaseInsensitive () + { + var tag = new ApeTag (); + tag.SetCustomField ("My Field", "old"); + + tag.SetCustomField ("MY FIELD", "new"); + + Assert.AreEqual (1, tag.ItemCount); + AssertValues (tag.GetCustomField ("my field"), "new"); + } + + [TestMethod] + public void Ape_MappedKey_IsTheMappedProperty () + { + var tag = new ApeTag { Title = "Old" }; + + tag.SetCustomField ("TITLE", "New"); + + Assert.AreEqual ("New", tag.Title); + Assert.AreEqual (1, tag.ItemCount); + } + + [TestMethod] + public void Ape_BinaryItem_HasNoText () + { + var tag = new ApeTag (); + tag.SetBinaryItem ("Blob", "x.bin", [1, 2, 3]); + + Assert.AreEqual (0, tag.GetCustomField ("Blob").Count); + } + + // ───────────────────────── ID3v2 ───────────────────────── + + [TestMethod] + public void Id3v2_DescriptionMatchesIgnoringCase () + { + var tag = new Id3v2Tag (); + + tag.SetCustomField ("Mood", "calm"); + tag.SetCustomField ("MOOD", "loud"); + + AssertValues (tag.GetCustomField ("mood"), "loud"); + Assert.AreEqual (1, tag.UserTextFrames.Count); + Assert.AreEqual ("MOOD", tag.UserTextFrames[0].Description); + } + + [TestMethod] + public void Id3v2_TxxxFromSetUserText_IsFoundReplacedAndRemovedInAnyCase () + { + var tag = new Id3v2Tag (); + tag.SetUserText ("FOO", "old"); + + AssertValues (tag.GetCustomField ("foo"), "old"); + + Assert.IsTrue (tag.SetCustomField ("foo", "new")); + Assert.AreEqual (1, tag.UserTextFrames.Count); + Assert.AreEqual ("new", tag.GetUserText ("FOO")); + + tag.SetUserText ("Foo", "again"); + Assert.AreEqual (1, tag.UserTextFrames.Count); + AssertValues (tag.GetCustomField ("FOO"), "again"); + + var reread = Id3v2Tag.Read (tag.Render ().Span).Tag!; + Assert.AreEqual (1, reread.UserTextFrames.Count); + Assert.IsTrue (reread.RemoveCustomField ("fOO")); + Assert.AreEqual (0, reread.UserTextFrames.Count); + Assert.IsNull (reread.GetUserText ("FOO")); + } + + [TestMethod] + public void Id3v2_StoresOneTxxxWithNulSeparatedValues () + { + var tag = new Id3v2Tag (Id3v2Version.V24); + + tag.SetCustomField ("My Field", "a", "b"); + + Assert.AreEqual (1, tag.UserTextFrames.Count); + Assert.AreEqual ("My Field", tag.UserTextFrames[0].Description); + Assert.AreEqual ("a\0b", tag.UserTextFrames[0].Value); + Assert.AreEqual (TextEncodingType.Utf8, tag.UserTextFrames[0].Encoding); + } + + [TestMethod] + public void Id3v23_WritesUtf16 () + { + var tag = new Id3v2Tag (Id3v2Version.V23); + + tag.SetCustomField ("My Field", "日本"); + + Assert.AreEqual (TextEncodingType.Utf16WithBom, tag.UserTextFrames[0].Encoding); + var again = Id3v2Tag.Read (tag.Render ().Span).Tag!; + Assert.AreEqual (3, again.Version); + AssertValues (again.GetCustomField ("My Field"), "日本"); + } + + [TestMethod] + public void Id3v2_DuplicateTxxxFrames_ReadTogetherAndReplacedByOne () + { + var tag = new Id3v2Tag (); + tag.AddUserTextFrame (new UserTextFrame ("Dup", "a")); + tag.AddUserTextFrame (new UserTextFrame ("Other", "o")); + tag.AddUserTextFrame (new UserTextFrame ("Dup", "b\0c")); + + AssertValues (tag.GetCustomField ("Dup"), "a", "b", "c"); + + tag.SetCustomField ("Dup", "z"); + AssertValues (tag.UserTextFrames.Select (f => f.Description).ToList (), "Dup", "Other"); + } + + [TestMethod] + public void Id3v2_TxxxThatAMappedPropertyUses_IsThatProperty () + { + var tag = new Id3v2Tag (); + + tag.SetCustomField ("REPLAYGAIN_TRACK_GAIN", "-6.5 dB"); + + Assert.AreEqual ("-6.5 dB", tag.ReplayGainTrackGain); + tag.ReplayGainTrackGain = "-1.0 dB"; + AssertValues (tag.GetCustomField ("REPLAYGAIN_TRACK_GAIN"), "-1.0 dB"); + } + + [TestMethod] + public void Id3v2_NameNeverAddressesAStandardFrame () + { + var tag = new Id3v2Tag { Title = "Song" }; + + tag.SetCustomField ("TITLE", "custom"); + tag.SetCustomField ("TIT2", "custom"); + + Assert.AreEqual ("Song", tag.Title); + Assert.AreEqual (2, tag.UserTextFrames.Count); + } + + [TestMethod] + [DynamicData (nameof (AllSupportingTags))] + public void Clear_RemovesEveryCustomField (string format, string name) + { + // docs/IMPLEMENTATION-GUIDE.md rule 7: Clear removes all tag metadata, mapped and unmapped. + var tag = Create (format); + Assert.IsTrue (tag.SetCustomField (name, "kept")); + var read = Reparse (tag); + Assert.AreEqual (1, read.GetCustomField (name).Count); + + read.Clear (); + + Assert.AreEqual (0, read.GetCustomField (name).Count, $"{format} Clear kept the field"); + Assert.AreEqual (0, Reparse (read).GetCustomField (name).Count, $"{format} Clear kept the field on render"); + } + + // ───────────────────────── MP4 ───────────────────────── + + [TestMethod] + public void Mp4_UsesTheITunesMeanAndOneDataAtomPerValue () + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + file.Tag = new Mp4Tag (); + + file.Tag.SetCustomField ("My Field", "a", "b"); + + Assert.AreEqual ("a", file.GetFreeformTag ("com.apple.iTunes", "My Field")); + // Two values read back from one freeform field: one data atom each. + AssertValues (Reparse (file.Tag).GetCustomField ("My Field"), "a", "b"); + } + + [TestMethod] + public void Mp4_MappedFreeformName_IsTheMappedProperty () + { + var tag = new Mp4Tag { Conductor = "Old" }; + + tag.SetCustomField ("CONDUCTOR", "New"); + + Assert.AreEqual ("New", tag.Conductor); + tag.Conductor = "Again"; + AssertValues (tag.GetCustomField ("CONDUCTOR"), "Again"); + } + + [TestMethod] + public void Mp4_NameWithColon_SurvivesRender () + { + var tag = new Mp4Tag (); + + tag.SetCustomField ("a:b:c", "x"); + + AssertValues (Reparse (tag).GetCustomField ("a:b:c"), "x"); + } + + [TestMethod] + public void Mp4_FreeformSetThroughTheFile_IsTheCustomField () + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + + file.SetFreeformTag ("com.apple.iTunes", "LABEL", "Acme"); + file.SetFreeformTag ("org.example", "LABEL", "Other"); + + AssertValues (file.Tag!.GetCustomField ("LABEL"), "Acme"); + Assert.AreEqual (0, file.Tag.GetCustomField ("label").Count); + } + + // ───────────────────────── ASF ───────────────────────── + + [TestMethod] + [DataRow ("Title")] + [DataRow ("AUTHOR")] + [DataRow ("Copyright")] + [DataRow ("Description")] + [DataRow ("Rating")] + public void Asf_ContentDescriptionName_IsTheFixedField (string name) + { + var tag = new AsfTag (); + + Assert.IsTrue (tag.SetCustomField (name, "value")); + + Assert.AreEqual (0, tag.ExtendedContentDescription.Descriptors.Count); + AssertValues (Reparse (tag).GetCustomField (name), "value"); + Assert.IsTrue (tag.SetCustomField (name, "a", "b")); + AssertValues (tag.GetCustomField (name), "a", "b"); + AssertValues (Reparse (tag).GetCustomField (name), "a", "b"); + Assert.IsTrue (tag.RemoveCustomField (name)); + Assert.AreEqual (0, tag.GetCustomField (name).Count); + } + + [TestMethod] + public void Asf_TitleName_IsTheTitleProperty () + { + var tag = new AsfTag (); + + tag.SetCustomField ("title", "Song"); + + Assert.AreEqual ("Song", tag.Title); + } + + [TestMethod] + public void Asf_MappedAttribute_IsTheMappedProperty () + { + var tag = new AsfTag { Album = "Old", Track = 5 }; + + tag.SetCustomField ("WM/AlbumTitle", "New"); + + Assert.AreEqual ("New", tag.Album); + AssertValues (tag.GetCustomField ("WM/TrackNumber"), "5"); + } + + [TestMethod] + public void Asf_FirstValueInExtendedContentRestInMetadataLibrary () + { + var tag = new AsfTag (); + + tag.SetCustomField ("My/Field", "a", "b", "c"); + + var names = tag.ExtendedContentDescription.Descriptors.Select (d => d.Name).ToList (); + AssertValues (names, "My/Field"); + AssertValues (tag.LibraryRecords!.Select (r => r.Text!).ToList (), "b", "c"); + AssertValues (tag.GetCustomField ("My/Field"), "a", "b", "c"); + } + + [TestMethod] + public void Asf_PictureAndOverlongValues_Refused () + { + var tag = new AsfTag (); + + Assert.IsFalse (tag.SetCustomField ("WM/Picture", "x")); + Assert.IsFalse (tag.SetCustomField ("Long", new string ('x', 32767))); + Assert.IsTrue (tag.SetCustomField ("Long", new string ('x', 32766))); + Assert.IsFalse (tag.SetCustomField (new string ('N', 32767), "x")); + Assert.AreEqual (1, tag.ExtendedContentDescription.Descriptors.Count); + } + + // ───────────────────────── Matroska ───────────────────────── + + [TestMethod] + public void Matroska_MappedName_IsTheMappedProperty () + { + var tag = new MatroskaTag { Comment = "Old" }; + + tag.SetCustomField ("COMMENT", "New"); + + Assert.AreEqual ("New", tag.Comment); + tag.Comment = "Again"; + AssertValues (tag.GetCustomField ("COMMENT"), "Again"); + } + + [TestMethod] + public void Matroska_NameMatchesExactly () + { + var tag = new MatroskaTag (); + + tag.SetCustomField ("MY_FIELD", "a"); + + Assert.AreEqual (0, tag.GetCustomField ("my_field").Count); + } + + // ───────────────────────── RIFF INFO ───────────────────────── + + [TestMethod] + [DataRow ("ABC")] + [DataRow ("ABCDE")] + [DataRow ("ABÉD")] + [DataRow ("AB\tD")] + public void RiffInfo_NameNotAFourCC_Refused (string name) + { + var tag = new RiffInfoTag (); + + Assert.IsFalse (tag.SetCustomField (name, "x")); + Assert.IsTrue (tag.IsEmpty); + } + + [TestMethod] + public void RiffInfo_OneValueOnlyAndLatin1Only () + { + var tag = new RiffInfoTag (); + + Assert.IsFalse (tag.SetCustomField ("IXYZ", "a", "b")); + Assert.IsFalse (tag.SetCustomField ("IXYZ", "日")); + Assert.IsTrue (tag.IsEmpty); + Assert.IsTrue (tag.SetCustomField ("IXYZ", "ÿ")); + } + + [TestMethod] + public void RiffInfo_MappedCode_IsTheMappedProperty () + { + var tag = new RiffInfoTag { Title = "Old" }; + + tag.SetCustomField ("INAM", "New"); + + Assert.AreEqual ("New", tag.Title); + AssertValues (tag.GetCustomField ("inam"), "New"); + } + + // ───────────────────────── Unified views ───────────────────────── + + [TestMethod] + public void CombinedTag_WritesEverySupportingTagAndSkipsId3v1 () + { + var v2 = new Id3v2Tag (); + var v1 = new Id3v1Tag { Title = "t" }; + var v1Before = v1.Render ().ToArray (); + var combined = new CombinedTag (v2, v1); + + Assert.IsTrue (combined.SupportsCustomFields); + Assert.IsTrue (combined.SetCustomField ("My Field", "a", "b")); + + AssertValues (v2.GetCustomField ("My Field"), "a", "b"); + AssertValues (combined.GetCustomField ("My Field"), "a", "b"); + CollectionAssert.AreEqual (v1Before, v1.Render ().ToArray ()); + Assert.IsTrue (combined.RemoveCustomField ("My Field")); + Assert.AreEqual (0, combined.GetCustomField ("My Field").Count); + } + + [TestMethod] + public void CombinedTag_ReadsTheFirstTagThatHoldsTheName () + { + var first = new ApeTag (); + var second = new ApeTag (); + second.SetCustomField ("Key", "from second"); + var combined = new CombinedTag (null, first, second); + + AssertValues (combined.GetCustomField ("Key"), "from second"); + first.SetCustomField ("Key", "from first"); + AssertValues (combined.GetCustomField ("Key"), "from first"); + } + + [TestMethod] + public void CombinedTag_OnlyId3v1_ReportsUnsupported () + { + var combined = new CombinedTag (null, new Id3v1Tag ()); + + Assert.IsFalse (combined.SupportsCustomFields); + Assert.IsFalse (combined.SetCustomField ("My Field", "x")); + Assert.IsFalse (combined.RemoveCustomField ("My Field")); + Assert.ThrowsExactly (() => combined.SetCustomField (null!, "x")); + Assert.ThrowsExactly (() => combined.GetCustomField (null!)); + Assert.ThrowsExactly (() => combined.RemoveCustomField (null!)); + } +} + +/// +/// Minimal EBML element writer for wrapping a rendered Tags element in a file. +/// +static class MatroskaBytes +{ + public static byte[] Master (ulong id, byte[] payload) => Element (id, payload); + + public static byte[] Element (ulong id, ReadOnlySpan payload) + { + var idBytes = new List (); + for (var shift = 24; shift >= 0; shift -= 8) { + var b = (byte)(id >> shift); + if (b != 0 || idBytes.Count > 0) + idBytes.Add (b); + } + + // An 8-byte size (0x01 marker) holds any test payload. + var size = new byte[8]; + size[0] = 0x01; + var length = (ulong)payload.Length; + for (var i = 7; i >= 1; i--) { + size[i] = (byte)length; + length >>= 8; + } + + return [.. idBytes, .. size, .. payload]; + } +} + +/// +/// Every concrete Tag type that is not a listed leaf () reads other tags, +/// and must forward the custom-field members, or a field written through MediaFile.Tag is refused. Using the +/// shared classification, a view of any shape is checked, whether or not it declares Leaves. +/// +[TestClass] +[TestCategory ("Unit")] +public class CustomFieldViewTests +{ + static readonly string[] CustomFieldMembers = ["SupportsCustomFields", "GetCustomField", "SetCustomField", "RemoveCustomField"]; + static readonly string[] OnlyRemove = ["RemoveCustomField"]; + + /// The custom-field members does not declare itself. + static List MissingMembers (Type type) => + [.. CustomFieldMembers.Where (member => !type.GetMember (member, BindingFlags.Instance | BindingFlags.Public) + .Any (m => m.DeclaringType == type))]; + + /// The types this check holds to the custom-field members: every concrete Tag type but a listed leaf. + static List NonLeafTypes (IEnumerable types) => [.. types.Where (t => !TagTypeClassification.IsLeaf (t))]; + + [TestMethod] + public void EveryViewType_ForwardsTheCustomFieldMembers () + { + var views = NonLeafTypes (TagTypeClassification.ConcreteTagTypes ()); + var missing = views.SelectMany (v => MissingMembers (v).Select (m => $"{v.FullName}.{m}")).ToList (); + + Assert.IsEmpty (missing, string.Join (", ", missing)); + CollectionAssert.AreEquivalent (TagTypeClassification.ViewTypes ().ToList (), views, "every non-leaf is a view that names its tags"); + foreach (var name in new[] { "CombinedTag", "FlacTag", "AiffTag" }) + Assert.IsTrue (views.Any (v => v.Name == name), $"{name} is a view"); + } + + [TestMethod] + public void ViewCheck_FlagsEveryGuardDummyShape () + { + // #136's eleven shapes of a view that does not name its tags; none forwards the custom-field members. + var dummies = typeof (GuardDummies).GetNestedTypes (BindingFlags.NonPublic) + .Where (t => !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)).ToList (); + + var checkedDummies = NonLeafTypes (dummies); + var missed = checkedDummies.Where (t => MissingMembers (t).Count == 0).Select (t => t.Name).ToList (); + + Assert.HasCount (11, dummies); + Assert.HasCount (11, checkedDummies); + Assert.IsEmpty (missed, string.Join (",", missed)); + } + + [TestMethod] + public void ViewCheck_FlagsAViewThatDoesNotForward () + { + Assert.IsTrue (TagTypeClassification.IsView (typeof (ForwardingDummies.Silent))); + CollectionAssert.AreEquivalent (CustomFieldMembers, MissingMembers (typeof (ForwardingDummies.Silent))); + CollectionAssert.AreEqual (OnlyRemove, MissingMembers (typeof (ForwardingDummies.Partial))); + Assert.IsEmpty (MissingMembers (typeof (ForwardingDummies.Forwarding))); + } +} + +/// Views over an inner tag: one forwards nothing, one forwards all but remove, one forwards everything. +static class ForwardingDummies +{ + internal abstract class DummyView : Tag + { + protected readonly Id3v2Tag Inner = new (Id3v2Version.V24); + public override TagTypes TagType => TagTypes.None; + public override string? Title { get; set; } + public override string? Artist { get; set; } + public override string? Album { get; set; } + public override string? Year { get; set; } + public override string? Comment { get; set; } + public override string? Genre { get; set; } + public override uint? Track { get; set; } + public override BinaryData Render () => BinaryData.Empty; + public override void Clear () { } + } + + internal sealed class Silent : DummyView + { + internal override IEnumerable Leaves () => [this, Inner]; + } + + internal sealed class Partial : DummyView + { + internal override IEnumerable Leaves () => [this, Inner]; + public override bool SupportsCustomFields => true; + public override IReadOnlyList GetCustomField (string name) => Inner.GetCustomField (name); + public override bool SetCustomField (string name, params string[] values) => Inner.SetCustomField (name, values); + } + + internal sealed class Forwarding : DummyView + { + internal override IEnumerable Leaves () => [this, Inner]; + public override bool SupportsCustomFields => true; + public override IReadOnlyList GetCustomField (string name) => Inner.GetCustomField (name); + public override bool SetCustomField (string name, params string[] values) => Inner.SetCustomField (name, values); + public override bool RemoveCustomField (string name) => Inner.RemoveCustomField (name); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index 5437f947..c7c306aa 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -4,9 +4,11 @@ using System.Reflection; using System.Text; using TagLibSharp2.Ape; +using TagLibSharp2.Asf; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Asf; using TagLibSharp2.Xiph; namespace TagLibSharp2.Tests.Core; @@ -66,11 +68,34 @@ static IEnumerable StringProperties () => tag.AddField (probe.Fields[0].Name, Stale); return VorbisComment.Read (tag.Render ().Span).Tag; } + case "asf": { + // ASF keeps values 2..n of an attribute in the Metadata Library (ASF spec rev. 01.20.03 §4.8), + // so the stale value goes there, as Windows and mutagen write it. + var probe = new AsfTag (); + property.SetValue (probe, "V1"); + if (!Equals (property.GetValue (probe), "V1")) + return null; + var name = probe.ExtendedContentDescription.Descriptors.Count == 1 + ? probe.ExtendedContentDescription.Descriptors[0].Name + : AsfContentDescriptionNames.FirstOrDefault (n => probe.GetCustomField (n) is ["V1"]); + if (name is null) + return null; + var file = AsfTestBuilder.CreateHeaderObject ( + AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), + AsfTestBuilder.CreateAudioStreamPropertiesObject (), + AsfMetadataLibraryTests.Object (AsfGuids.ContentDescriptionObject, probe.RenderContentDescription ().ToArray ()), + AsfMetadataLibraryTests.HeaderExtension (AsfMetadataLibraryTests.Library (AsfMetadataLibraryTests.Record (name, Stale))), + AsfMetadataLibraryTests.Object (AsfGuids.ExtendedContentDescriptionObject, probe.Render ().ToArray ())); + var tag = AsfFile.Read ([.. file, .. AsfTestBuilder.CreateDataObject (0)]).File!.Tag; + return tag.GetCustomField (name).Contains (Stale) ? tag : null; + } default: throw new ArgumentOutOfRangeException (nameof (format)); } } + static readonly string[] AsfContentDescriptionNames = ["Title", "Author", "Copyright", "Description", "Rating"]; + static string ApeKey (ApeTag tag) { // One item: value size (4, LE), flags (4), key (ASCII, NUL-terminated), value. @@ -99,20 +124,23 @@ static bool IsCopied (string sourceFormat, string targetFormat, PropertyInfo pro static bool RenderHolds (Tag tag, string text) { - var bytes = tag.Render ().ToArray (); - var needle = Encoding.UTF8.GetBytes (text); - for (var i = 0; i + needle.Length <= bytes.Length; i++) { - if (bytes.AsSpan (i, needle.Length).SequenceEqual (needle)) - return true; + if (tag is AsfTag asf) { + var unicode = Encoding.Unicode.GetBytes (text); + return asf.LibraryRecords?.Any (r => r.Text == text) == true || + ContainsBytes (asf.Render ().ToArray (), unicode) || + ContainsBytes (asf.RenderContentDescription ().ToArray (), unicode); } - return false; + return ContainsBytes (tag.Render ().ToArray (), Encoding.UTF8.GetBytes (text)); } + static bool ContainsBytes (byte[] haystack, byte[] needle) => haystack.AsSpan ().IndexOf (needle) >= 0; + [TestMethod] [DataRow ("id3v23")] [DataRow ("id3v24")] [DataRow ("ape")] [DataRow ("vorbis")] + [DataRow ("asf")] public void CopyAll_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) { var covered = new List (); @@ -145,6 +173,7 @@ public void CopyAll_SourceEqualsTargetFirstValue_ReplacesTheList (string targetF [DataRow ("id3v24")] [DataRow ("ape")] [DataRow ("vorbis")] + [DataRow ("asf")] public void CopyBasic_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) { var failures = new List (); diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs index 53110d97..3682432b 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs @@ -371,7 +371,7 @@ public void CopyTo_ApeToId3_KeepsEveryNameAndBasicKeepsTheFirst () } [TestMethod] - public void CopyTo_ApeToMp4AndAsf_KeepsOnlyTheFirstName () + public void CopyTo_ApeToMp4_KeepsOnlyTheFirstName () { var source = new ApeTag { Performers = ["A", "B"], @@ -391,18 +391,32 @@ public void CopyTo_ApeToMp4AndAsf_KeepsOnlyTheFirstName () Assert.HasCount (1, mp4.Composers); Assert.AreEqual ("Jazz", mp4.Genre); Assert.HasCount (1, mp4.Genres); + } + + [TestMethod] + public void CopyTo_ApeToAsf_KeepsEveryName () + { + // ASF holds a multi-valued attribute as Windows writes it: the first value in the Content Description or + // Extended Content Description, the rest in the Metadata Library (ASF spec rev. 01.20.03 §4.8). + var source = new ApeTag { + Performers = ["A", "B"], + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Genres = ["Jazz", "Soul"] + }; var asf = new AsfTag (); source.CopyTo (asf); + Assert.AreEqual ("A", asf.Artist); - Assert.HasCount (1, asf.Performers); - Assert.AreEqual ("A", asf.Performers[0]); + CollectionAssert.AreEqual (source.Performers, asf.Performers); Assert.AreEqual ("Ada", asf.AlbumArtist); - Assert.HasCount (1, asf.AlbumArtists); + CollectionAssert.AreEqual (source.AlbumArtists, asf.AlbumArtists); Assert.AreEqual ("Cara", asf.Composer); - Assert.HasCount (1, asf.Composers); + CollectionAssert.AreEqual (source.Composers, asf.Composers); Assert.AreEqual ("Jazz", asf.Genre); - Assert.HasCount (1, asf.Genres); + CollectionAssert.AreEqual (source.Genres, asf.Genres); + Assert.HasCount (2, asf.Genres); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameKindsTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameKindsTests.cs new file mode 100644 index 00000000..71e382d7 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameKindsTests.cs @@ -0,0 +1,102 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Riff; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Every kind of frame the tag holds counts as content: a WAV or AIFF save writes an ID3 chunk that holds only +/// that frame, and removes it. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3v2")] +public class Id3v2FrameKindsTests +{ + static readonly Dictionary> Kinds = new () { + ["TIT2"] = t => t.Title = "t", + ["APIC"] = t => t.AddPicture (new PictureFrame ("image/png", PictureType.FrontCover, "", [1, 2, 3])), + ["COMM"] = t => t.AddComment (new CommentFrame ("c")), + ["TXXX"] = t => t.AddUserTextFrame (new UserTextFrame ("d", "v")), + ["USLT"] = t => t.AddLyrics (new LyricsFrame ("l")), + ["UFID"] = t => t.AddUniqueFileId (new UniqueFileIdFrame ("http://example.org", "id")), + ["TIPL"] = t => { + var people = new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople); + people.Add ("producer", "p"); + t.AddInvolvedPeopleFrame (people); + }, + ["POPM"] = t => t.SetPopularimeter ("a@example.org", 128, 3), + ["WOAR"] = t => t.SetUrl ("WOAR", "http://example.org/artist"), + ["WXXX"] = t => t.SetUserUrl ("d", "http://example.org"), + ["SYLT"] = t => { + var sync = new SyncLyricsFrame (); + sync.AddSyncItem ("line", 1000); + t.AddSyncLyrics (sync); + }, + ["GEOB"] = t => t.AddGeneralObject (new GeneralObjectFrame ("application/octet-stream", "f.bin", "d", new BinaryData ([1, 2]))), + ["PRIV"] = t => t.AddPrivateFrame (new PrivateFrame ("owner", new BinaryData ([1, 2]))), + ["CHAP"] = t => t.AddChapter (new ChapterFrame ("ch1", 0, 1000)), + ["CTOC"] = t => { + var toc = new TableOfContentsFrame ("toc"); + toc.AddChildElement ("ch1"); + t.AddTableOfContents (toc); + }, + }; + + public static IEnumerable KindNames => Kinds.Keys.Select (k => new object[] { k }); + + static Id3v2Tag TagWithOnly (string kind) + { + var tag = new Id3v2Tag (); + Kinds[kind] (tag); + Assert.IsTrue (tag.Render ().Span.IndexOf (System.Text.Encoding.ASCII.GetBytes (kind)) >= 0, "the frame renders"); + return tag; + } + + [TestMethod] + [DynamicData (nameof (KindNames))] + public void Wav_TagWithOnlyThisFrame_IsWritten (string kind) + { + var tag = TagWithOnly (kind); + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal ()).File!; + wav.Id3v2Tag = tag; + + var reloaded = WavFile.Read (wav.Render ().Span).File!; + + Assert.IsNotNull (reloaded.Id3v2Tag, $"{kind} alone must keep the ID3 chunk"); + CollectionAssert.AreEqual (tag.Render ().ToArray (), reloaded.Id3v2Tag.Render ().ToArray ()); + } + + [TestMethod] + [DynamicData (nameof (KindNames))] + public void Aiff_TagWithOnlyThisFrame_IsWritten (string kind) + { + var tag = TagWithOnly (kind); + var aiff = AiffFile.Read (TestBuilders.Aiff.CreateMinimal ()).File!; + aiff.Id3v2Tag = tag; + + var reloaded = AiffFile.Read (aiff.Render ().Span).File!; + + Assert.IsNotNull (reloaded.Id3v2Tag, $"{kind} alone must keep the ID3 chunk"); + CollectionAssert.AreEqual (tag.Render ().ToArray (), reloaded.Id3v2Tag.Render ().ToArray ()); + } + + [TestMethod] + [DynamicData (nameof (KindNames))] + public void Clear_RemovesThisFrame (string kind) + { + var tag = TagWithOnly (kind); + + tag.Clear (); + + CollectionAssert.AreEqual (new Id3v2Tag ().Render ().ToArray (), tag.Render ().ToArray ()); + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal ()).File!; + wav.Id3v2Tag = tag; + Assert.IsNull (WavFile.Read (wav.Render ().Span).File!.Id3v2Tag, "an empty tag writes no chunk"); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16AllocationTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16AllocationTests.cs new file mode 100644 index 00000000..7e2e9d24 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16AllocationTests.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Reading a UTF-16 text frame allocates the frame and its strings, and nothing per string on the way +/// (CLAUDE.md, "Span<T> first: ... avoid allocations"). +/// +/// +/// The bound is measured on this thread with , against building +/// the same objects directly, so it does not depend on machine load or on other threads. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3v2")] +public class Utf16AllocationTests +{ + const int Reads = 2000; + + // What a read may spend beyond the frame and its strings: none of the frame's text, per string, is copied. + const long SlackPerRead = 8; + + static byte[] Utf16 (string text) => [0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (text)]; + + public static IEnumerable Values => [ + ["a"], + ["eighteen characters"], + ["a\0b"], + ["eighteen characters\0another eighteen c"], + ["x\0\0y\0z"], + ["long"], + ]; + + // A value too long for the stack buffer, so the pooled path is measured too. + static string Expand (string value) => + value == "long" ? new string ('L', 600) + "\0" + new string ('M', 600) : value; + + /// One BOM per string, the strings separated by 00 00. + static byte[] Encode (string value) + { + var bytes = new List (); + var parts = value.Split ('\0'); + for (var i = 0; i < parts.Length; i++) { + if (i > 0) + bytes.AddRange (new byte[] { 0, 0 }); + bytes.AddRange (Utf16 (parts[i])); + } + return [.. bytes]; + } + + static long PerCall (Action action) + { + for (var i = 0; i < 50; i++) + action (); + var before = GC.GetAllocatedBytesForCurrentThread (); + for (var i = 0; i < Reads; i++) + action (); + return (GC.GetAllocatedBytesForCurrentThread () - before) / Reads; + } + + [TestMethod] + [DynamicData (nameof (Values))] + public void TextFrameRead_AllocatesOnlyTheFrameAndItsText (string name) + { + var value = Expand (name); + byte[] content = [0x01, .. Encode (value)]; + Assert.AreEqual (value, TextFrame.Read ("TPE1", content, Id3v2Version.V24).Frame!.Text); + + var read = PerCall (() => TextFrame.Read ("TPE1", content, Id3v2Version.V24)); + var direct = PerCall (() => _ = new TextFrame ("TPE1", value.AsSpan ().ToString (), TextEncodingType.Utf16WithBom)); + + Assert.IsTrue (read <= direct + SlackPerRead, $"read allocates {read} B, the frame and its text are {direct} B"); + } + + [TestMethod] + [DynamicData (nameof (Values))] + public void UserTextFrameRead_AllocatesOnlyTheFrameAndItsStrings (string name) + { + var value = Expand (name); + byte[] content = [0x01, .. Utf16 ("MyField"), 0, 0, .. Encode (value)]; + Assert.AreEqual (value, UserTextFrame.Read (content, Id3v2Version.V24).Frame!.Value); + + var read = PerCall (() => UserTextFrame.Read (content, Id3v2Version.V24)); + var direct = PerCall (() => _ = new UserTextFrame ("MyField".AsSpan ().ToString (), value.AsSpan ().ToString (), + TextEncodingType.Utf16WithBom)); + + Assert.IsTrue (read <= direct + SlackPerRead, $"read allocates {read} B, the frame and its strings are {direct} B"); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs new file mode 100644 index 00000000..27a5f3ec --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs @@ -0,0 +1,177 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Encoding $01 text with several strings. ID3v2.4 §4 says the encoding is "UTF-16 encoded Unicode with BOM" +/// and that all strings in a frame share one byte order; ID3v2.3 §3.3 says Unicode strings begin with a BOM. +/// So each string may carry its own BOM, and none of them is part of the text. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3v2")] +public class Utf16MultiStringTests +{ + static readonly byte[] Le = [0xFF, 0xFE]; + static readonly byte[] Be = [0xFE, 0xFF]; + static readonly string[] FirstSecond = ["first", "second"]; + + static byte[] Utf16 (string text, bool bigEndian) => + bigEndian ? System.Text.Encoding.BigEndianUnicode.GetBytes (text) : System.Text.Encoding.Unicode.GetBytes (text); + + /// Two strings, each optionally led by a BOM, separated by 00 00. + static byte[] TwoStrings (bool bigEndian, bool bomOnSecond, bool trailingNul) + { + var bom = bigEndian ? Be : Le; + byte[] second = bomOnSecond ? [.. bom, .. Utf16 ("second", bigEndian)] : Utf16 ("second", bigEndian); + byte[] text = [.. bom, .. Utf16 ("first", bigEndian), 0, 0, .. second]; + return trailingNul ? [.. text, 0, 0] : text; + } + + public static IEnumerable Layouts => [ + [false, true, false], + [true, true, false], + [false, false, false], + [true, false, false], + [false, true, true], + [true, true, true], + ]; + + [TestMethod] + [DynamicData (nameof (Layouts))] + public void Txxx_EachStringsBom_IsNotPartOfTheValue (bool bigEndian, bool bomOnSecond, bool trailingNul) + { + byte[] content = [0x01, .. Le, .. Utf16 ("MyField", false), 0, 0, .. TwoStrings (bigEndian, bomOnSecond, trailingNul)]; + + foreach (var version in new byte[] { 3, 4 }) { + var tag = ReadTag (version, TestBuilders.Id3v2.CreateFrame ("TXXX", content, version)); + + CollectionAssert.AreEqual (FirstSecond, tag.GetCustomField ("MyField").ToArray ()); + } + } + + [TestMethod] + [DynamicData (nameof (Layouts))] + public void TextFrame_EachStringsBom_IsNotPartOfTheValue (bool bigEndian, bool bomOnSecond, bool trailingNul) + { + byte[] content = [0x01, .. TwoStrings (bigEndian, bomOnSecond, trailingNul)]; + + var tag = ReadTag (4, TestBuilders.Id3v2.CreateFrame ("TPE1", content, 4)); + + CollectionAssert.AreEqual (FirstSecond, tag.Performers); + } + + [TestMethod] + public void UserTextFrame_Read_StripsEveryBom () + { + byte[] content = [0x01, .. Le, .. Utf16 ("D", false), 0, 0, .. TwoStrings (false, true, false)]; + + var frame = UserTextFrame.Read (content, Id3v2Version.V24).Frame!; + + Assert.AreEqual ("first\0second", frame.Value); + } + + [TestMethod] + public void TextFrame_Read_StripsEveryBom () + { + byte[] content = [0x01, .. TwoStrings (true, true, false)]; + + var frame = TextFrame.Read ("TPE1", content, Id3v2Version.V24).Frame!; + + Assert.AreEqual ("first\0second", frame.Text); + } + + [TestMethod] + public void Id3v23_SetCustomField_WritesABomBeforeEachValue () + { + var tag = new Id3v2Tag (Id3v2Version.V23); + + tag.SetCustomField ("F", "first", "second"); + + var content = tag.UserTextFrames[0].RenderContent ().ToArray (); + byte[] expected = [0x01, .. Le, .. Utf16 ("F", false), 0, 0, .. Le, .. Utf16 ("first", false), 0, 0, .. Le, .. Utf16 ("second", false)]; + CollectionAssert.AreEqual (expected, content); + var again = Id3v2Tag.Read (tag.Render ().Span).Tag!; + CollectionAssert.AreEqual (FirstSecond, again.GetCustomField ("F").ToArray ()); + } + + [TestMethod] + public void Utf16Frame_WithABomPerString_RendersTheSameBytes () + { + byte[] txxx = [0x01, .. Le, .. Utf16 ("MyField", false), 0, 0, .. TwoStrings (false, true, false)]; + byte[] tpe1 = [0x01, .. TwoStrings (false, true, false)]; + + Assert.IsTrue (UserTextFrame.Read (txxx, Id3v2Version.V24).Frame!.RenderContent ().Span.SequenceEqual (txxx)); + Assert.IsTrue (TextFrame.Read ("TPE1", tpe1, Id3v2Version.V24).Frame!.RenderContent ().Span.SequenceEqual (tpe1)); + } + + public static IEnumerable ReadLayouts => [ + ["one BOM per string", (byte[])[.. Le, .. Utf16 ("first", false), 0, 0, .. Le, .. Utf16 ("second", false)]], + ["one BOM per string, terminated", (byte[])[.. Le, .. Utf16 ("first", false), 0, 0, .. Le, .. Utf16 ("second", false), 0, 0]], + ["one BOM for the frame", (byte[])[.. Le, .. Utf16 ("first", false), 0, 0, .. Utf16 ("second", false)]], + ["one string, terminated", (byte[])[.. Le, .. Utf16 ("first/second", false), 0, 0]], + ["inner NUL, one BOM", (byte[])[.. Le, .. Utf16 ("T", false), 0, 0, .. Utf16 ("T", false)]], + // mutagen's text=['a','','b']: every string, the empty one too, has a BOM. + ["empty middle string with a BOM", (byte[])[.. Le, .. Utf16 ("a", false), 0, 0, .. Le, 0, 0, .. Le, .. Utf16 ("b", false), 0, 0]], + ["empty middle string without a BOM", (byte[])[.. Le, .. Utf16 ("a", false), 0, 0, 0, 0, .. Le, .. Utf16 ("b", false)]], + ["two empty middle strings with BOMs", (byte[])[.. Le, .. Utf16 ("a", false), 0, 0, .. Le, 0, 0, .. Le, 0, 0, .. Le, .. Utf16 ("b", false)]], + ["empty first string", (byte[])[.. Le, 0, 0, .. Le, .. Utf16 ("b", false)]], + // mutagen's text=['x','']: the empty last string has a BOM. + ["empty last string with a BOM", (byte[])[.. Le, .. Utf16 ("x", false), 0, 0, .. Le]], + ["empty last string with a BOM, terminated", (byte[])[.. Le, .. Utf16 ("x", false), 0, 0, .. Le, 0, 0]], + ["two empty strings with BOMs", (byte[])[.. Le, 0, 0, .. Le]], + ["one string, two terminators", (byte[])[.. Le, .. Utf16 ("x", false), 0, 0, 0, 0]], + ]; + + [TestMethod] + [DynamicData (nameof (ReadLayouts))] + public void Utf16Frame_UnchangedRender_KeepsTheLayoutItWasReadWith (string layout, byte[] text) + { + _ = layout; + byte[] txxx = [0x01, .. Le, .. Utf16 ("MyField", false), 0, 0, .. text]; + byte[] tpe1 = [0x01, .. text]; + + CollectionAssert.AreEqual (txxx, UserTextFrame.Read (txxx, Id3v2Version.V24).Frame!.RenderContent ().ToArray ()); + // The text holds no terminator; the layout keeps it, so both frames render the bytes they were read from. + var textFrame = TextFrame.Read ("TPE1", tpe1, Id3v2Version.V24).Frame!; + Assert.IsFalse (textFrame.Text.Contains ('\uFEFF'), "a BOM is not text"); + CollectionAssert.AreEqual (tpe1, textFrame.RenderContent ().ToArray ()); + } + + [TestMethod] + [DataRow ("a\0\uFEFFb")] + [DataRow ("a\0\uFFFEb")] + [DataRow ("\uFEFFa\0b")] + [DataRow ("a\0\uFEFF")] + public void Utf16Text_StringStartingWithAByteOrderMarkChar_KeepsIt (string text) + { + // U+FEFF or U+FFFE at the start of a string's text encodes as the bytes of a BOM; the string then gets a + // real BOM in front, so a reader does not take that char for one. + foreach (var frame in new[] { new TextFrame ("TPE1", text, TextEncodingType.Utf16WithBom) }) { + var again = TextFrame.Read ("TPE1", frame.RenderContent ().Span, Id3v2Version.V24).Frame!; + Assert.AreEqual (text, again.Text); + CollectionAssert.AreEqual (again.RenderContent ().ToArray (), TextFrame.Read ("TPE1", again.RenderContent ().Span, Id3v2Version.V24).Frame!.RenderContent ().ToArray ()); + } + } + + [TestMethod] + public void Utf16SingleString_RendersAsBefore () + { + var frame = new TextFrame ("TIT2", "Song", TextEncodingType.Utf16WithBom); + + byte[] expected = [0x01, .. Le, .. Utf16 ("Song", false)]; + CollectionAssert.AreEqual (expected, frame.RenderContent ().ToArray ()); + } + + static Id3v2Tag ReadTag (byte version, byte[] frame) + { + byte[] header = TestBuilders.Id3v2.CreateHeader (version, (uint)frame.Length); + var result = Id3v2Tag.Read ([.. header, .. frame]); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiValueFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiValueFrameTests.cs new file mode 100644 index 00000000..e405be1f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiValueFrameTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Every multi-value reader over encoding $01 text gets the same strings: text frames (ID3v2.4 §4.2, through the +/// mapped multi-value properties), TXXX (§4.2.6), the involved people lists TIPL, TMCL (§4.2.2) and IPLS +/// (ID3v2.3 §4.4), in ID3v2.2, 2.3 and 2.4. Each string may begin with its own BOM (ID3v2.3 §3.3, and the layout +/// mutagen writes by default); a string without one keeps the byte order of the string before it +/// (ID3v2.4 §4: "All Unicode strings ... SHALL have the same byteorder"). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3v2")] +public class Utf16MultiValueFrameTests +{ + static readonly byte[] Le = [0xFF, 0xFE]; + static readonly byte[] Be = [0xFE, 0xFF]; + static readonly string[] Ab = ["Alpha", "Beta"]; + static readonly string[] MultiValueFrameIds = ["TPE1", "TPE2", "TCOM", "TCON"]; + static readonly string[] AEmptyB = ["a", "", "b"]; + static readonly string[] GuitarEmpty = ["g", ""]; + static readonly string[] GuitarOnly = ["g"]; + + /// The byte layouts a writer produces for the strings, each followed by 00 00 except the last. + public enum Layout + { + /// A little-endian BOM on every string (mutagen's default). + LittleEndianBomEach, + /// A big-endian BOM on every string. + BigEndianBomEach, + /// One little-endian BOM for the frame. + LittleEndianBomOnce, + /// One big-endian BOM for the frame; later strings keep that order. + BigEndianBomOnce, + /// A BOM on every string and a terminator after the last. + LittleEndianBomEachTerminated, + } + + public static IEnumerable Layouts => Enum.GetValues ().Select (l => new object[] { l }); + + static byte[] Encode (Layout layout, params string[] strings) + { + var bigEndian = layout is Layout.BigEndianBomEach or Layout.BigEndianBomOnce; + var bomEach = layout is Layout.LittleEndianBomEach or Layout.BigEndianBomEach or Layout.LittleEndianBomEachTerminated; + var bytes = new List (); + for (var i = 0; i < strings.Length; i++) { + if (i > 0) + bytes.AddRange (new byte[] { 0, 0 }); + if (i == 0 || bomEach) + bytes.AddRange (bigEndian ? Be : Le); + bytes.AddRange (bigEndian + ? System.Text.Encoding.BigEndianUnicode.GetBytes (strings[i]) + : System.Text.Encoding.Unicode.GetBytes (strings[i])); + } + if (layout == Layout.LittleEndianBomEachTerminated) + bytes.AddRange (new byte[] { 0, 0 }); + return [.. bytes]; + } + + static Id3v2Tag ReadTag (byte version, string frameId, byte[] content) + { + var frame = version == 2 + ? TestBuilders.Id3v2.CreateFrameV22 (frameId, content) + : TestBuilders.Id3v2.CreateFrame (frameId, content, version); + var result = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader (version, (uint)frame.Length), .. frame]); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } + + public static IEnumerable TextFrames => + from layout in Enum.GetValues () + from version in new byte[] { 3, 4 } + from id in MultiValueFrameIds + select new object[] { layout, version, id }; + + static string[] PropertyFor (Id3v2Tag tag, string frameId) => frameId switch { + "TPE1" or "TP1" => tag.Performers, + "TPE2" => tag.AlbumArtists, + "TCOM" => tag.Composers, + "TCON" => tag.Genres, + _ => throw new ArgumentOutOfRangeException (nameof (frameId)) + }; + + [TestMethod] + [DynamicData (nameof (TextFrames))] + public void MultiValueTextFrame_ReadsEachStringWithoutItsBom (Layout layout, byte version, string frameId) + { + var tag = ReadTag (version, frameId, [0x01, .. Encode (layout, Ab)]); + + CollectionAssert.AreEqual (Ab, PropertyFor (tag, frameId)); + CollectionAssert.AreEqual (Ab, tag.GetTextFrameValues (frameId).ToArray ()); + } + + [TestMethod] + [DynamicData (nameof (Layouts))] + public void Id3v22TextFrame_ReadsEachStringWithoutItsBom (Layout layout) + { + var tag = ReadTag (2, "TP1", [0x01, .. Encode (layout, Ab)]); + + CollectionAssert.AreEqual (Ab, tag.Performers); + } + + [TestMethod] + [DynamicData (nameof (Layouts))] + public void Txxx_ReadsEachStringWithoutItsBom (Layout layout) + { + foreach (var version in new byte[] { 3, 4 }) { + byte[] content = [0x01, .. Encode (Layout.LittleEndianBomEach, "Field"), 0, 0, .. Encode (layout, Ab)]; + var tag = ReadTag (version, "TXXX", content); + + CollectionAssert.AreEqual (Ab, tag.GetCustomField ("Field").ToArray ()); + } + } + + [TestMethod] + [DynamicData (nameof (Layouts))] + public void InvolvedPeople_ReadsEachStringWithoutItsBom (Layout layout) + { + string[] strings = ["producer", "Alpha", "engineer", "Beta"]; + foreach (var (version, id) in new (byte, string)[] { (4, "TIPL"), (4, "TMCL"), (3, "IPLS") }) { + var frame = InvolvedPeopleFrame.Read (id, [0x01, .. Encode (layout, strings)], + version == 4 ? Id3v2Version.V24 : Id3v2Version.V23).Frame!; + + CollectionAssert.AreEqual ( + new[] { ("producer", "Alpha"), ("engineer", "Beta") }, + frame.Pairs.ToArray (), $"{id} {layout}"); + } + } + + [TestMethod] + public void InvolvedPeople_InTheTag_ReadsEachStringWithoutItsBom () + { + var tag = ReadTag (4, "TIPL", [0x01, .. Encode (Layout.BigEndianBomOnce, "producer", "Alpha")]); + + Assert.AreEqual ("Alpha", tag.InvolvedPeopleFrames[0].GetPerson ("producer")); + } + + [TestMethod] + public void Utf16Text_DecodeStrings_IsTheSplitterEveryReaderUses () + { + var strings = Utf16Text.DecodeStrings (Encode (Layout.BigEndianBomOnce, "a", "", "b")); + + CollectionAssert.AreEqual (AEmptyB, strings.ToArray ()); + Assert.AreEqual ("a\0\0b", Utf16Text.Decode (Encode (Layout.LittleEndianBomEach, "a", "", "b"))); + } + + [TestMethod] + public void InvolvedPeople_LoneByteAfterATerminator_IsAnEmptyPerson () + { + // As #136 reads it: a lone last byte after 00 00 starts a string with no code unit, so the role it follows + // still pairs, with an empty person. The byte itself is never text. + byte[] data = [0x01, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes ("a\0Alpha\0guitar"), 0x00, 0x00, 0x41]; + foreach (var (version, id) in new (byte, string)[] { (4, "TIPL"), (4, "TMCL"), (3, "IPLS") }) { + var frame = InvolvedPeopleFrame.Read (id, data, version == 4 ? Id3v2Version.V24 : Id3v2Version.V23).Frame!; + + CollectionAssert.AreEqual (new[] { ("a", "Alpha"), ("guitar", "") }, frame.Pairs.ToArray (), id); + } + CollectionAssert.AreEqual (GuitarEmpty, Utf16Text.DecodeStrings ([0xFF, 0xFE, 0x67, 0x00, 0x00, 0x00, 0x41]).ToArray ()); + CollectionAssert.AreEqual (GuitarOnly, Utf16Text.DecodeStrings ([0xFF, 0xFE, 0x67, 0x00, 0x00, 0x00]).ToArray (), + "an even frame's trailing terminator is not a value"); + CollectionAssert.AreEqual (GuitarOnly, Utf16Text.DecodeStrings ([0xFF, 0xFE, 0x67, 0x00, 0x41]).ToArray (), + "a lone byte after text is dropped"); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaCustomFieldTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaCustomFieldTests.cs new file mode 100644 index 00000000..9a07ded7 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaCustomFieldTests.cs @@ -0,0 +1,116 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Matroska; + +public partial class MatroskaFileTests +{ + static readonly byte[] Cluster = Master (0x1F43B675, new byte[] { 0x55, 0x66 }); + + static MatroskaFile Reopen (MatroskaFile file, byte[] original) + { + var fs = new MockFileSystem (); + fs.AddFile ("/f.mkv", original); + var saved = file.SaveToFile ("/f.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/f.mkv"); + Assert.AreEqual (1, CountOf (bytes, Cluster), "the cluster is copied once"); + var again = MatroskaFile.Read (bytes); + Assert.IsTrue (again.IsSuccess, again.Error); + return again.File!; + } + + static void AssertCustom (IReadOnlyList actual, params string[] expected) => + CollectionAssert.AreEqual (expected, actual.ToArray ()); + + [TestMethod] + public void CustomField_WritesAtTheItemLevel () + { + var original = FileWith ( + Tags (Tag (50, Simple ("TITLE", "Album")), Tag (30, Simple ("TITLE", "Track"))), + Cluster); + var file = MatroskaFile.Read (original).File!; + + Assert.IsTrue (file.Tag.SetCustomField ("MY_FIELD", "a", "b")); + var again = Reopen (file, original); + + AssertCustom (again.Tag.GetCustomField ("MY_FIELD"), "a", "b"); + Assert.AreEqual ("Album", again.Tag.Album); + Assert.AreEqual ("Track", again.Tag.Title); + Assert.AreEqual (0, again.Tag.GetCustomField ("my_field").Count); + } + + [TestMethod] + public void CustomField_BroaderLevelShowsThroughUntilSetAndRemoveClearsBoth () + { + var original = FileWith ( + Tags (Tag (50, Simple ("LABEL", "Album label")), Tag (30, Simple ("TITLE", "Track"))), + Cluster); + var file = MatroskaFile.Read (original).File!; + + AssertCustom (file.Tag.GetCustomField ("LABEL"), "Album label"); + + file.Tag.SetCustomField ("LABEL", "Track label"); + var again = Reopen (file, original); + AssertCustom (again.Tag.GetCustomField ("LABEL"), "Track label"); + + Assert.IsTrue (again.Tag.RemoveCustomField ("LABEL")); + Assert.AreEqual (0, again.Tag.GetCustomField ("LABEL").Count); + var removed = Reopen (again, original); + Assert.AreEqual (0, removed.Tag.GetCustomField ("LABEL").Count); + } + + [TestMethod] + public void CustomField_ChapterTag_IsNotTheFile () + { + var original = FileWith ( + Tags ( + Tag (50, Simple ("TITLE", "Movie")), + ChapterTag (30, Chapter (7), Simple ("LABEL", "Chapter label"))), + Cluster); + var file = MatroskaFile.Read (original).File!; + + Assert.AreEqual (0, file.Tag.GetCustomField ("LABEL").Count); + Assert.IsFalse (file.Tag.RemoveCustomField ("LABEL")); + + file.Tag.SetCustomField ("LABEL", "File label"); + var again = Reopen (file, original); + AssertCustom (again.Tag.GetCustomField ("LABEL"), "File label"); + var bytes = again.Tag.Render ().ToArray (); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("Chapter label"u8) >= 0); + } + + [TestMethod] + public void CustomField_FileWithoutTags_GetsATagsElement () + { + var original = FileWith (Cluster); + var file = MatroskaFile.Read (original).File!; + + Assert.IsTrue (file.Tag.SetCustomField ("MY_FIELD", "x")); + var again = Reopen (file, original); + + AssertCustom (again.Tag.GetCustomField ("MY_FIELD"), "x"); + } + + [TestMethod] + public void CustomField_TitleOnAlbumOnlyFile_IsTheAlbumTitleAndTheSegmentTitleStays () + { + // A segment title and only album-level (50) tags: the item level is 50, so TITLE is the album title, + // and Title still reads the segment title (RFC 9559 §5.1.2.4, Info\Title). + var info = Master (0x1549A966, Element (0x7BA9, "SegTitle"u8)); + var original = FileWith (info, Tags (Tag (50, Simple ("ARTIST", "A"))), Cluster); + var file = MatroskaFile.Read (original).File!; + Assert.AreEqual ("SegTitle", file.Tag.Title); + + Assert.IsTrue (file.Tag.SetCustomField ("TITLE", "Custom")); + var again = Reopen (file, original); + + AssertCustom (again.Tag.GetCustomField ("TITLE"), "Custom"); + Assert.AreEqual ("Custom", again.Tag.Album); + Assert.AreEqual ("SegTitle", again.Tag.Title); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterTests.cs index 3f47f620..60f1f531 100644 --- a/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterTests.cs +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterTests.cs @@ -1789,6 +1789,36 @@ public void Save_Chapters_TagInMovieMeta_RewritesOnlyTheChapters (bool clear) CollectionAssert.AreEqual (expected, Mp4ChapterCodec.ReadChpl (moov)!.Select (c => c.Title).ToArray (), "chpl is rewritten in udta"); } + /// + /// A custom field and a chapter list set before one save both survive, whether the tag lives in udta/meta + /// (the chapter fixture's own tag) or in moov/meta while udta is rebuilt for chpl. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Save_ChaptersAndACustomField_InOneSave_KeepBoth (bool tagInMovieMeta) + { + var original = tagInMovieMeta ? MovieMetaChapters () : Mp4ChapterTestBuilder.Build (TaggedChapters ()); + var file = Mp4ChapterTestBuilder.ReadFile (original); + + Assert.IsTrue (file.Tag!.SetCustomField ("MYFIELD", "one", "two")); + file.Chapters = Edit (1); + var saved = Save (file, original); + + var reread = Mp4ChapterTestBuilder.ReadFile (saved); + CollectionAssert.AreEqual (CustomOneTwo, reread.Tag!.GetCustomField ("MYFIELD").ToArray ()); + CollectionAssert.AreEqual (Edit (1).Select (c => c.Title).ToArray (), reread.Chapters.Select (c => c.Title).ToArray ()); + Assert.AreEqual (tagInMovieMeta ? "Movie" : "Tagged", reread.Title, "the tag's other fields stay"); + + Assert.IsTrue (reread.Tag.RemoveCustomField ("MYFIELD")); + reread.Chapters = Edit (2); + var again = Mp4ChapterTestBuilder.ReadFile (Save (reread, saved)); + Assert.AreEqual (0, again.Tag!.GetCustomField ("MYFIELD").Count, "a remove in a chapter save stays removed"); + CollectionAssert.AreEqual (Edit (2).Select (c => c.Title).ToArray (), again.Chapters.Select (c => c.Title).ToArray ()); + } + + static readonly string[] CustomOneTwo = ["one", "two"]; + [TestMethod] public void Save_Chapters_TagInMovieMeta_CopiesUdtaMetaAsItWas () { diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4FreeformTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4FreeformTests.cs new file mode 100644 index 00000000..11e78ca6 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4FreeformTests.cs @@ -0,0 +1,199 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// Freeform ---- atoms: which data types are text, and keys whose mean or name holds a colon. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class Mp4FreeformTests +{ + static void AssertValues (IReadOnlyList actual, params string[] expected) => + CollectionAssert.AreEqual (expected, actual.ToArray ()); + + [TestMethod] + [DataRow (0)] + [DataRow (1)] + public void Mp4_ImplicitAndUtf8Data_AreText (int typeIndicator) + { + // Apple's well-known types: 0 is implicit (no type indicated), 1 is UTF-8. GetFreeformTag reads both. + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + file.Tag = new Mp4Tag (); + file.Tag.SetFreeformAtoms ("com.apple.iTunes", "Implicit", + [new Mp4DataAtom (typeIndicator, BinaryData.FromStringUtf8 ("implicit"))]); + var again = Mp4File.Read (file.Render (original).Span).File!; + + Assert.AreEqual ("implicit", again.GetFreeformTag ("com.apple.iTunes", "Implicit")); + AssertValues (again.Tag!.GetCustomField ("Implicit"), "implicit"); + } + + [TestMethod] + public void Mp4_NonTextData_IsNotAValue () + { + var tag = new Mp4Tag (); + tag.SetFreeformAtoms ("com.apple.iTunes", "Blob", [ + new Mp4DataAtom (13, new BinaryData ([0xFF, 0xD8])), + new Mp4DataAtom (1, BinaryData.FromStringUtf8 ("text"))]); + + AssertValues (tag.GetCustomField ("Blob"), "text"); + } + + [TestMethod] + [DataRow ("a:b", "c")] + [DataRow ("a", "b:c")] + [DataRow ("x\\y", "z")] + [DataRow ("a\\:b", "c\\d")] + [DataRow (":lead", "trail:")] + public void Mp4_FreeformMeanAndName_RoundTripWhateverTheyHold (string mean, string name) + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + + file.SetFreeformTag (mean, name, "val"); + var rendered = file.Render (original).ToArray (); + + // mean and name are full boxes: size, type, version and flags, then the UTF-8 text. + byte[] meanBox = [.. "mean"u8, 0, 0, 0, 0, .. Encoding.UTF8.GetBytes (mean)]; + byte[] nameBox = [.. "name"u8, 0, 0, 0, 0, .. Encoding.UTF8.GetBytes (name)]; + Assert.IsTrue (rendered.AsSpan ().IndexOf (meanBox) >= 0, "the mean is written as given"); + Assert.IsTrue (rendered.AsSpan ().IndexOf (nameBox) >= 0, "the name is written as given"); + var again = Mp4File.Read (rendered).File!; + Assert.AreEqual ("val", again.GetFreeformTag (mean, name)); + CollectionAssert.AreEqual (rendered, again.Render (rendered).ToArray (), "an unchanged save keeps the atom"); + } + + [TestMethod] + public void Mp4_FreeformMeanWithColon_IsNotAnotherMeanAndName () + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + + file.SetFreeformTag ("a:b", "c", "one"); + file.SetFreeformTag ("a", "b:c", "two"); + var again = Mp4File.Read (file.Render (original).Span).File!; + + Assert.AreEqual ("one", again.GetFreeformTag ("a:b", "c")); + Assert.AreEqual ("two", again.GetFreeformTag ("a", "b:c")); + } + + // ── #133's two metas: custom fields follow the freeform fields ── + + static byte[] KeyedFile (string[] keys, params byte[][] items) => + TestBuilders.Mp4.CreateWithKeyedMeta ("mdta", TestBuilders.Mp4.KeysPayload (keys), items, inMovie: false, udtaExtra: null); + + static int Count (byte[] data, byte[] needle) + { + var count = 0; + for (var at = data.AsSpan ().IndexOf (needle); at >= 0;) { + count++; + var next = data.AsSpan (at + 1).IndexOf (needle); + at = next < 0 ? -1 : at + 1 + next; + } + return count; + } + + static readonly string[] AB = ["a", "b"]; + static readonly string[] Kept = ["kept"]; + + [TestMethod] + public void Mdta_SetCustomField_WritesAKeyedItemNotAnITunesAtom () + { + var data = KeyedFile (["com.apple.quicktime.artist"], TestBuilders.Mp4.CreateMdtaItem (1, "Artist")); + var file = Mp4File.Read (data).File!; + + Assert.IsTrue (file.Tag!.SetCustomField ("MYFIELD", "a", "b")); + var rendered = file.Render (data).ToArray (); + + Mp4QuickTimeKeysTests.AssertOnlyKeyedItems (rendered, 2); + Assert.AreEqual (0, Count (rendered, "----"u8.ToArray ()), "an mdta meta holds no iTunes freeform atom"); + Assert.AreEqual (1, Count (rendered, "MYFIELD"u8.ToArray ()), "the name is one key"); + CollectionAssert.AreEqual (AB, Mp4File.Read (rendered).File!.Tag!.GetCustomField ("MYFIELD").ToArray ()); + } + + [TestMethod] + public void Mdta_ReadField_IsACustomFieldAndRemoveLeavesNothing () + { + // ffmpeg writes an unmapped name as a key; it reads as a com.apple.iTunes freeform field. + var data = KeyedFile (["com.apple.quicktime.artist", "MYFIELD"], + TestBuilders.Mp4.CreateMdtaItem (1, "Artist"), TestBuilders.Mp4.CreateMdtaItem (2, "kept")); + var file = Mp4File.Read (data).File!; + CollectionAssert.AreEqual (Kept, file.Tag!.GetCustomField ("MYFIELD").ToArray ()); + + Assert.IsTrue (file.Tag.RemoveCustomField ("MYFIELD")); + var rendered = file.Render (data).ToArray (); + + // The item goes; its keys entry stays, as for every field a set removes in an mdta meta (only Clear drops + // keys), so the other items keep their indexes. A key no item uses shows nothing. + Assert.AreEqual (0, Count (rendered, "kept"u8.ToArray ()), "the item is gone"); + Mp4QuickTimeKeysTests.AssertOnlyKeyedItems (rendered, 2); + var again = Mp4File.Read (rendered).File!.Tag!; + Assert.AreEqual (0, again.GetCustomField ("MYFIELD").Count); + Assert.AreEqual ("Artist", again.Artist, "the other key stays"); + Assert.IsFalse (again.RemoveCustomField ("MYFIELD"), "nothing is left to remove"); + } + + [TestMethod] + public void ITunes_RemoveCustomField_DropsTheAtomReadFromTheFile () + { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (original).File!; + file.Tag = new Mp4Tag (); + file.Tag.SetCustomField ("MYFIELD", "kept"); + var saved = file.Render (original).ToArray (); + + var again = Mp4File.Read (saved).File!; + Assert.IsTrue (again.Tag!.RemoveCustomField ("MYFIELD")); + var rendered = again.Render (saved).ToArray (); + + Assert.AreEqual (0, Count (rendered, "MYFIELD"u8.ToArray ())); + Assert.AreEqual (0, Mp4File.Read (rendered).File!.Tag?.GetCustomField ("MYFIELD").Count ?? 0); + } + + [TestMethod] + [DataRow ("mdta")] + [DataRow ("itunes")] + public void Clear_LeavesNoCustomField (string layout) + { + byte[] data; + if (layout == "mdta") { + data = KeyedFile (["MYFIELD"], TestBuilders.Mp4.CreateMdtaItem (1, "kept")); + } else { + var original = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var built = Mp4File.Read (original).File!; + built.Tag = new Mp4Tag (); + built.Tag.SetCustomField ("MYFIELD", "kept"); + data = built.Render (original).ToArray (); + } + var file = Mp4File.Read (data).File!; + Assert.AreEqual (1, file.Tag!.GetCustomField ("MYFIELD").Count); + + file.Tag.Clear (); + var rendered = file.Render (data).ToArray (); + + Assert.AreEqual (0, Count (rendered, "MYFIELD"u8.ToArray ())); + Assert.AreEqual (0, Count (rendered, "kept"u8.ToArray ())); + } + + [TestMethod] + public void CopyTo_KeepsTheTargetsCustomField () + { + // A copy writes mapped fields only; a custom field, like any item the copy does not map, stays. + var data = KeyedFile (["com.apple.quicktime.artist", "MYFIELD"], + TestBuilders.Mp4.CreateMdtaItem (1, "Old"), TestBuilders.Mp4.CreateMdtaItem (2, "kept")); + var file = Mp4File.Read (data).File!; + + new TagLibSharp2.Xiph.VorbisComment ("v") { Artist = "New", Title = "T" }.CopyTo (file.Tag!, TagCopyOptions.All); + var again = Mp4File.Read (file.Render (data).ToArray ()).File!.Tag!; + + Assert.AreEqual ("New", again.Artist); + CollectionAssert.AreEqual (Kept, again.GetCustomField ("MYFIELD").ToArray ()); + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index bd4ea047..1f4e30df 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -248,6 +248,7 @@ namespace TagLibSharp2.Ape public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -258,11 +259,14 @@ namespace TagLibSharp2.Ape public override string? Year { get; set; } public override void Clear() { } public TagLibSharp2.Ape.ApeBinaryData? GetBinaryItem(string key) { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } public string? GetValue(string key) { } public bool Remove(string key) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } public TagLibSharp2.Core.BinaryData RenderWithOptions(bool includeHeader = false) { } public void SetBinaryItem(string key, string filename, byte[] data) { } + public override bool SetCustomField(string name, params string[] values) { } public void SetValue(string key, string value) { } public static TagLibSharp2.Ape.ApeTagParseResult Parse(System.ReadOnlySpan data) { } } @@ -668,6 +672,7 @@ namespace TagLibSharp2.Asf public override string? Album { get; set; } public override string? AlbumArtist { get; set; } public override string? AlbumArtistSort { get; set; } + public override string[] AlbumArtists { get; set; } public override string? AlbumSort { get; set; } public override string? AmazonId { get; set; } public override string? Artist { get; set; } @@ -678,6 +683,7 @@ namespace TagLibSharp2.Asf public override string? Comment { get; set; } public override string? Composer { get; set; } public override string? ComposerSort { get; set; } + public override string[] Composers { get; set; } public override string? Conductor { get; set; } public TagLibSharp2.Asf.AsfContentDescription ContentDescription { get; } public override string? Copyright { get; set; } @@ -689,6 +695,7 @@ namespace TagLibSharp2.Asf public override string? EncoderSettings { get; set; } public TagLibSharp2.Asf.AsfExtendedContentDescription ExtendedContentDescription { get; } public override string? Genre { get; set; } + public override string[] Genres { get; set; } public override string? Grouping { get; set; } public override string? InitialKey { get; set; } public override bool IsCompilation { get; set; } @@ -713,6 +720,7 @@ namespace TagLibSharp2.Asf public override string? MusicBrainzTrackId { get; set; } public override string? MusicBrainzWorkId { get; set; } public override string? OriginalReleaseDate { get; set; } + public override string[] Performers { get; set; } public override TagLibSharp2.Core.IPicture[] Pictures { get; set; } public override string? PodcastFeedUrl { get; set; } public override string? Publisher { get; set; } @@ -725,6 +733,7 @@ namespace TagLibSharp2.Asf public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -734,8 +743,11 @@ namespace TagLibSharp2.Asf public override string? Work { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } public TagLibSharp2.Core.BinaryData RenderContentDescription() { } + public override bool SetCustomField(string name, params string[] values) { } } } namespace TagLibSharp2.Audible @@ -1114,6 +1126,7 @@ namespace TagLibSharp2.Core public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } protected System.Collections.Generic.IReadOnlyList Tags { get; } public override string? Title { get; set; } @@ -1124,7 +1137,10 @@ namespace TagLibSharp2.Core public override string? Work { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } } public sealed class DefaultFileSystem : TagLibSharp2.Core.IFileSystem { @@ -1392,6 +1408,7 @@ namespace TagLibSharp2.Core public virtual string? ReplayGainTrackGain { get; set; } public virtual string? ReplayGainTrackPeak { get; set; } public virtual string? Subtitle { get; set; } + public virtual bool SupportsCustomFields { get; } public abstract TagLibSharp2.Core.TagTypes TagType { get; } public abstract string? Title { get; set; } public virtual string? TitleSort { get; set; } @@ -1402,7 +1419,10 @@ namespace TagLibSharp2.Core public abstract string? Year { get; set; } public abstract void Clear(); public void CopyTo(TagLibSharp2.Core.Tag target, TagLibSharp2.Core.TagCopyOptions options = 63) { } + public virtual System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public virtual bool RemoveCustomField(string name) { } public abstract TagLibSharp2.Core.BinaryData Render(); + public virtual bool SetCustomField(string name, params string[] values) { } public virtual TagLibSharp2.Core.ValidationResult Validate() { } } [System.Flags] @@ -2317,6 +2337,7 @@ namespace TagLibSharp2.Id3.Id3v2 public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public System.Collections.Generic.IReadOnlyList SyncLyricsFrames { get; } public System.Collections.Generic.IReadOnlyList TableOfContentsFrames { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } @@ -2346,6 +2367,7 @@ namespace TagLibSharp2.Id3.Id3v2 public override void Clear() { } public TagLibSharp2.Id3.Id3v2.Frames.ChapterFrame? GetChapter(string? elementId = null) { } public TagLibSharp2.Id3.Id3v2.Frames.CommentFrame? GetCommentFrame(string? language = null, string? description = null) { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } public TagLibSharp2.Id3.Id3v2.Frames.GeneralObjectFrame? GetGeneralObject(string? description = null) { } public TagLibSharp2.Id3.Id3v2.Frames.InvolvedPeopleFrame? GetInvolvedPeopleFrame(string frameId) { } public TagLibSharp2.Id3.Id3v2.Frames.LyricsFrame? GetLyricsFrame(string? language = null, string? description = null) { } @@ -2364,6 +2386,7 @@ namespace TagLibSharp2.Id3.Id3v2 public void RemoveAllPictures() { } public void RemoveChapters(string? elementId = null) { } public void RemoveComments(string? language = null, string? description = null) { } + public override bool RemoveCustomField(string name) { } public void RemoveGeneralObjects(string? description = null) { } public void RemoveInvolvedPeopleFrames(string? frameId = null) { } public void RemoveLyrics(string? language = null, string? description = null) { } @@ -2375,6 +2398,7 @@ namespace TagLibSharp2.Id3.Id3v2 public void RemoveUserTextFrames(string description) { } public override TagLibSharp2.Core.BinaryData Render() { } public TagLibSharp2.Core.BinaryData Render(int paddingSize, bool withFooter = false) { } + public override bool SetCustomField(string name, params string[] values) { } public void SetPicture(TagLibSharp2.Core.PictureType pictureType, TagLibSharp2.Id3.Id3v2.Frames.PictureFrame? picture) { } public void SetPopularimeter(string email, byte rating, ulong playCount = 0) { } public void SetTextFrameValues(string frameId, System.Collections.Generic.IEnumerable? values) { } @@ -2526,6 +2550,7 @@ namespace TagLibSharp2.Matroska public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -2534,7 +2559,10 @@ namespace TagLibSharp2.Matroska public override uint? Track { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } } public sealed class MatroskaTrack { @@ -2824,6 +2852,7 @@ namespace TagLibSharp2.Mp4 public override string? ReplayGainTrackPeak { get; set; } public string? ShortTitle { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -2833,7 +2862,10 @@ namespace TagLibSharp2.Mp4 public override string? Work { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } } } namespace TagLibSharp2.Mpeg @@ -3364,13 +3396,17 @@ namespace TagLibSharp2.Riff public override bool IsEmpty { get; } public override string[] Performers { get; set; } public string? Software { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override uint? Track { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } public string? GetField(string fourCC) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } public void SetField(string fourCC, string? value) { } public static TagLibSharp2.Riff.RiffInfoTag? Parse(TagLibSharp2.Core.BinaryData data) { } } @@ -3776,6 +3812,7 @@ namespace TagLibSharp2.Xiph public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -3785,7 +3822,10 @@ namespace TagLibSharp2.Xiph public override string? Work { get; set; } public override string? Year { get; set; } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } + public override bool RemoveCustomField(string name) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } } public sealed class VorbisComment : TagLibSharp2.Core.Tag { @@ -3859,6 +3899,7 @@ namespace TagLibSharp2.Xiph public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } public override string? Subtitle { get; set; } + public override bool SupportsCustomFields { get; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; } public override string? TitleSort { get; set; } @@ -3871,12 +3912,15 @@ namespace TagLibSharp2.Xiph public void AddField(string name, string value) { } public void AddPicture(TagLibSharp2.Xiph.FlacPicture picture) { } public override void Clear() { } + public override System.Collections.Generic.IReadOnlyList GetCustomField(string name) { } public string? GetValue(string name) { } public System.Collections.Generic.IReadOnlyList GetValues(string name) { } public void RemoveAll(string name) { } public void RemoveAllPictures() { } + public override bool RemoveCustomField(string name) { } public void RemovePictures(TagLibSharp2.Core.PictureType pictureType) { } public override TagLibSharp2.Core.BinaryData Render() { } + public override bool SetCustomField(string name, params string[] values) { } public void SetValue(string name, string? value) { } public static TagLibSharp2.Xiph.VorbisCommentReadResult Read(System.ReadOnlySpan data) { } } diff --git a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs index 0b76d431..2b2252fe 100644 --- a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs @@ -90,6 +90,90 @@ public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, str Assert.AreEqual (names.IndexOf ("LIST INFO") - 1, names.IndexOf ("CSET"), $"{cell}: the CSET comes right before the list"); } + /// + /// The same matrix with the change made through the custom-field API: SetCustomField adds a field the + /// file did not hold, or RemoveCustomField drops one it did. Each cell keeps the unchanged field's bytes, or + /// re-encodes it as UTF-8 when the list must become UTF-8, or refuses, exactly as a mapped field change does. + /// + [TestMethod] + [DynamicData (nameof (Matrix))] + public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int codePage, string unchangedKind, string changedKind) + { + var unchanged = UnchangedBytes (codePage, unchangedKind); + var builder = new AviTestBuilder { CharacterSet = codePage < 0 ? null : (ushort?)codePage }; + builder.Info.Add (("INAM", "Old")); + builder.Info.Add (("IOLD", "drop me")); + builder.InfoBytes.Add (("IART", unchanged)); + var original = builder.Build (); + var file = AviFile.Read (original).File!; + var artist = file.InfoTag.Artist; + var changed = changedKind == "ascii" ? ChangedAscii : ChangedNonAscii; + Assert.IsTrue (file.InfoTag.SetCustomField ("IXYZ", changed), "an AVI INFO list takes any text"); + Assert.IsTrue (file.InfoTag.RemoveCustomField ("IOLD")); + + var fs = new MockFileSystem (); + var result = file.SaveToFile ("/out.avi", original, fs); + + var becameUtf8 = changedKind == "nonascii" && codePage != 65001; + var kind = Kind (codePage, unchanged); + var cell = $"CSET {codePage}, unchanged {unchangedKind}, custom field {changedKind}"; + if (becameUtf8 && kind == "guess") { + Assert.IsFalse (result.IsSuccess, cell); + StringAssert.Contains (result.Error, "IART", cell); + return; + } + + Assert.IsTrue (result.IsSuccess, $"{cell}: {result.Error}"); + var saved = fs.ReadAllBytes ("/out.avi"); + var again = AviFile.Read (saved).File!.InfoTag; + if (becameUtf8 && kind == "exact") { + var declared = Oracle (codePage).GetString (unchanged, 0, Array.IndexOf (unchanged, (byte)0)); + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (declared + "\0"), AviTestBuilder.InfoField (saved, "IART"), cell); + } else { + CollectionAssert.AreEqual (unchanged, AviTestBuilder.InfoField (saved, "IART"), cell); + } + + Assert.AreEqual (artist, again.Artist, cell); + Assert.AreEqual ("Old", again.Title, cell); + CollectionAssert.AreEqual (new[] { changed }, again.GetCustomField ("IXYZ").ToArray (), cell); + Assert.AreEqual (0, again.GetCustomField ("IOLD").Count, cell); + Assert.IsNull (AviTestBuilder.InfoField (saved, "IOLD"), cell); + if (becameUtf8) + Assert.AreEqual ((ushort)65001, CodePage (saved), cell); + else if (codePage >= 0) + Assert.AreEqual ((ushort)codePage, CodePage (saved), $"{cell}: the declared code page is kept"); + } + + [TestMethod] + [DataRow ((ushort)1252, "Café", new byte[] { (byte)'C', (byte)'a', (byte)'f', 0xE9, 0 })] + [DataRow ((ushort)28591, "Café", new byte[] { (byte)'C', (byte)'a', (byte)'f', 0xE9, 0 })] + [DataRow ((ushort)0, "Café", new byte[] { (byte)'C', (byte)'a', (byte)'f', 0xE9, 0 })] + public void Save_CustomFieldThatFitsTheDeclaredCodePage_IsWrittenInIt (ushort codePage, string value, byte[] expected) + { + var builder = new AviTestBuilder { CharacterSet = codePage }; + builder.Info.Add (("INAM", "Old")); + var original = builder.Build (); + var file = AviFile.Read (original).File!; + Assert.IsTrue (file.InfoTag.SetCustomField ("IXYZ", value)); + + var fs = new MockFileSystem (); + Assert.IsTrue (file.SaveToFile ("/out.avi", original, fs).IsSuccess); + var saved = fs.ReadAllBytes ("/out.avi"); + + CollectionAssert.AreEqual (expected, AviTestBuilder.InfoField (saved, "IXYZ")); + Assert.AreEqual (codePage, CodePage (saved), "the CSET is kept"); + CollectionAssert.AreEqual (new[] { value }, AviFile.Read (saved).File!.InfoTag.GetCustomField ("IXYZ").ToArray ()); + } + + [TestMethod] + public void WavInfo_CustomFieldOutsideLatin1_IsRefused () + { + // A WAV INFO list is Latin-1 and has no CSET, so text it cannot hold is refused, not mangled. + var tag = new RiffInfoTag (); + Assert.IsFalse (tag.SetCustomField ("IXYZ", ChangedNonAscii)); + Assert.IsTrue (tag.SetCustomField ("IXYZ", "Café")); + } + public static IEnumerable Matrix () { foreach (var codePage in new[] { -1, 0, 28591, 932, 1252, 65001 }) diff --git a/tests/TagLibSharp2.Tests/Riff/WavFileRoundTripTests.cs b/tests/TagLibSharp2.Tests/Riff/WavFileRoundTripTests.cs index 8e2f801e..b13b542b 100644 --- a/tests/TagLibSharp2.Tests/Riff/WavFileRoundTripTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/WavFileRoundTripTests.cs @@ -268,4 +268,15 @@ public void BothTags_PreferenceMaintained () Assert.AreEqual ("Info Title", reloaded.InfoTag?.Title); Assert.AreEqual ("ID3 Title", reloaded.Id3v2Tag?.Title); } + + [TestMethod] + public void Id3TagWithOnlyAlbumArtist_IsWritten () + { + WavFile.TryRead (CreateMinimalWav (), out var file); + file!.Id3v2Tag = new Id3v2Tag { AlbumArtist = "Various" }; + + WavFile.TryRead (file.Render (), out var reloaded); + + Assert.AreEqual ("Various", reloaded?.Id3v2Tag?.AlbumArtist); + } }