From c2a45cd01f46334b2b921c05e1610ac62141a0e2 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 20 Nov 2026 15:38:27 -0700 Subject: [PATCH 01/29] fix: Drop a terminating NUL from ID3 text Fixes #128 --- .../Id3/Id3v2/Frames/CommentFrame.cs | 3 + .../Id3/Id3v2/Frames/GeneralObjectFrame.cs | 2 + .../Id3/Id3v2/Frames/InvolvedPeopleFrame.cs | 3 + .../Id3/Id3v2/Frames/LyricsFrame.cs | 3 + .../Id3/Id3v2/Frames/SyncLyricsFrame.cs | 3 + .../Id3/Id3v2/Frames/TextFrame.cs | 15 +- .../Id3/Id3v2/Frames/UserTextFrame.cs | 2 + .../Id3/Id3v2/Frames/UserUrlFrame.cs | 10 +- src/TagLibSharp2/Id3/Id3v2/Id3Text.cs | 27 + src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 44 +- .../Id3/Id3v2/Id3v2TrailingTerminatorTests.cs | 487 ++++++++++++++++++ 11 files changed, 583 insertions(+), 16 deletions(-) create mode 100644 src/TagLibSharp2/Id3/Id3v2/Id3Text.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs index 3dfc40dd..f5870edf 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs @@ -201,6 +201,9 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // A comment is one string. Drop only a trailing terminator. + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs index 751ad207..9421ed74 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs @@ -197,6 +197,8 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs index aad26514..973ad8fe 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs @@ -346,6 +346,9 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // Each role or person is already split. Drop only that piece's trailing terminator. + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs index e0aa4209..0edd3fcb 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs @@ -201,6 +201,9 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // Lyrics are one string. Drop only a trailing terminator. + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs index e56ec664..665e6d29 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs @@ -374,6 +374,9 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // A lyric line is one string, not a NUL-separated list. Drop only a trailing terminator. + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs index 17d405c6..89e84532 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -105,19 +105,13 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) static string DecodeTextLatin1 (ReadOnlySpan data) { - // Strip trailing null bytes only (preserve internal nulls for multi-value support) - while (data.Length > 0 && data[data.Length - 1] == 0) - data = data.Slice (0, data.Length - 1); - + data = Id3Text.TrimTrailingTerminator (data, TextEncodingType.Latin1); return Polyfills.Latin1.GetString (data); } static string DecodeTextUtf8 (ReadOnlySpan data) { - // Strip trailing null bytes only (preserve internal nulls for multi-value support) - while (data.Length > 0 && data[data.Length - 1] == 0) - data = data.Slice (0, data.Length - 1); - + data = Id3Text.TrimTrailingTerminator (data, TextEncodingType.Utf8); return System.Text.Encoding.UTF8.GetString (data); } @@ -149,9 +143,8 @@ static string DecodeTextUtf16BE (ReadOnlySpan data) static string DecodeTextUtf16 (ReadOnlySpan data, bool isLittleEndian) { - // Strip trailing double-null bytes only (preserve internal nulls for multi-value support) - while (data.Length >= 2 && data[data.Length - 2] == 0 && data[data.Length - 1] == 0) - data = data.Slice (0, data.Length - 2); + // Width only: both UTF-16 encodings use a 2-byte terminator. + data = Id3Text.TrimTrailingTerminator (data, TextEncodingType.Utf16WithBom); var encoding = isLittleEndian ? System.Text.Encoding.Unicode diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs index 0bd37b4d..1cd50766 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -156,6 +156,8 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs index 1b76b2ca..0d76792b 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs @@ -125,11 +125,14 @@ public BinaryData RenderContent () if (terminatorIndex < 0) { // No terminator found - treat entire content as URL - return (string.Empty, Polyfills.Latin1.GetString (data)); + var whole = Id3Text.TrimTrailingTerminator (data, TextEncodingType.Latin1); + return (string.Empty, Polyfills.Latin1.GetString (whole)); } var descriptionData = data.Slice (0, terminatorIndex); - var urlData = data.Slice (terminatorIndex + terminatorSize); + var urlData = Id3Text.TrimTrailingTerminator ( + data.Slice (terminatorIndex + terminatorSize), + TextEncodingType.Latin1); var description = DecodeText (descriptionData, encoding); var url = Polyfills.Latin1.GetString (urlData); @@ -156,6 +159,9 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // Descriptions follow the text rule: a trailing terminator is not part of the string. + data = Id3Text.TrimTrailingTerminator (data, encoding); + return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs new file mode 100644 index 00000000..5be4e017 --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -0,0 +1,27 @@ +// 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.Id3.Id3v2; + +/// +/// Shared decoding for ID3 text. A trailing terminator is not part of the string. +/// +internal static class Id3Text +{ + /// + /// Drops trailing string terminators. Internal NULs stay: ID3v2.4 uses them to + /// separate values, and a comment or lyric line is one string. + /// + internal static ReadOnlySpan TrimTrailingTerminator (ReadOnlySpan data, TextEncodingType encoding) + { + if (encoding is TextEncodingType.Utf16WithBom or TextEncodingType.Utf16BE) { + while (data.Length >= 2 && data[data.Length - 2] == 0 && data[data.Length - 1] == 0) + data = data.Slice (0, data.Length - 2); + return data; + } + + while (data.Length > 0 && data[data.Length - 1] == 0) + data = data.Slice (0, data.Length - 1); + return data; + } +} diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 72b73105..bcf701dc 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1447,11 +1447,26 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) } /// - /// Gets the value of a text frame by ID. + /// Gets the first value of a text frame by ID. /// /// The frame ID (e.g., TIT2, TPE1). - /// The text value, or null if not found. + /// + /// The first non-empty value, or null if the frame is absent. + /// A NUL separates further values and is not included. A slash is not a separator here. + /// public string? GetTextFrame (string frameId) + { + var text = GetRawTextFrame (frameId); + if (text is null) + return null; + + return FirstTextValue (text); + } + + /// + /// Gets the stored frame text, including NUL separators between values. + /// + string? GetRawTextFrame (string frameId) { // Use for loop instead of LINQ for better performance for (var i = 0; i < _frames.Count; i++) { @@ -1461,6 +1476,28 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) return null; } + /// + /// Returns the first non-empty NUL-separated piece. No slash split. + /// + static string FirstTextValue (string text) + { + var start = 0; + for (var i = 0; i < text.Length; i++) { + if (text[i] != '\0') + continue; + + if (i > start) + return text.Substring (start, i - start); + start = i + 1; + } + + if (start == 0) + return text; + if (start < text.Length) + return text.Substring (start); + return string.Empty; + } + /// /// Gets all values from a text frame (multi-value support). /// @@ -1472,7 +1509,8 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) /// public IReadOnlyList GetTextFrameValues (string frameId) { - var text = GetTextFrame (frameId); + // Raw text. GetTextFrame returns only the first value, which would drop the rest. + var text = GetRawTextFrame (frameId); if (string.IsNullOrEmpty (text)) return Array.Empty (); diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs new file mode 100644 index 00000000..f6aeb9da --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -0,0 +1,487 @@ +// 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.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// A stored terminator is not part of the text. Internal NULs still separate values. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2TrailingTerminatorTests +{ + [TestMethod] + public void Comment_Utf16YepaWithTerminator_DropsTrailingNul () + { + var tag = ReadFrame (TestConstants.Id3v2.Version4, "COMM", Utf16Comment ("eng", "", "yepa", terminated: true)); + + Assert.AreEqual ("yepa", tag.Comment); + AssertNoNul (tag.Comment); + Assert.AreEqual ("yepa", tag.Comments[0].Text); + Assert.AreEqual ("eng", tag.Comments[0].Language); + } + + [TestMethod] + public void Comment_Latin1WithTrailingNul_DropsTerminator () + { + var content = Latin1DescribedText (TextEncodingType.Latin1, "eng", "", "yepa", terminated: true); + var tag = ReadFrame (TestConstants.Id3v2.Version4, "COMM", content); + + Assert.AreEqual ("yepa", tag.Comment); + AssertNoNul (tag.Comment); + } + + [TestMethod] + public void Comment_Utf16BeWithTerminator_DropsTrailingNul () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16BE); + builder.Add ("eng"u8); + builder.Add (0, 0); + builder.Add (Encoding.BigEndianUnicode.GetBytes ("yepa")); + builder.Add (0, 0); + + var frame = CommentFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("yepa", frame.Frame!.Text); + AssertNoNul (frame.Frame.Text); + } + + [TestMethod] + public void Comment_InternalNul_IsNotASeparator () + { + // Description terminator, then ye + NUL + pa, then a trailing terminator. + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("eng"u8); + builder.Add (0); + builder.Add ((byte)'y', (byte)'e', 0, (byte)'p', (byte)'a', 0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "COMM", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("ye\0pa", tag.Comment); + Assert.AreEqual (2, tag.Comment!.IndexOf ('\0')); + } + + [TestMethod] + public void Title_Utf16EmbeddedNul_ReturnsFirstValue () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("T\0T")); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("T\0T", tag.Frames[0].Text); + Assert.AreEqual ("T", tag.Title); + Assert.AreEqual ("T", tag.GetTextFrame ("TIT2")); + + var values = tag.GetTextFrameValues ("TIT2"); + Assert.HasCount (2, values); + Assert.AreEqual ("T", values[0]); + Assert.AreEqual ("T", values[1]); + } + + [TestMethod] + public void Title_TrailingNul_HasNoEmptySecondValue () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("Title"u8); + builder.Add (0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("Title", tag.Title); + AssertNoNul (tag.Title); + var values = tag.GetTextFrameValues ("TIT2"); + Assert.HasCount (1, values); + Assert.AreEqual ("Title", values[0]); + } + + [TestMethod] + public void Title_RoundTrip_DoesNotKeepTrailingNul () + { + var original = new Id3v2Tag (Id3v2Version.V24) { Title = "Title" }; + + var result = Id3v2Tag.Read (original.Render ().Span); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Title", result.Tag!.Title); + AssertNoNul (result.Tag.Title); + var values = result.Tag.GetTextFrameValues ("TIT2"); + Assert.HasCount (1, values); + Assert.AreEqual ("Title", values[0]); + } + + [TestMethod] + public void Performers_Utf16NullSeparated_KeepsBothNames () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("Alice\0Bob")); + builder.Add (0, 0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("Alice\0Bob", tag.Frames[0].Text); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("Alice", tag.Performers[0]); + Assert.AreEqual ("Bob", tag.Performers[1]); + Assert.AreEqual ("Alice", tag.Artist); + } + + [TestMethod] + public void Performers_V23SlashSeparated_SingleGetterDoesNotSplit () + { + var frame = TestBuilders.Id3v2.CreateTextFrame ("TPE1", "A/B", TestConstants.Id3v2.Version3); + var tag = ReadTag (TestConstants.Id3v2.Version3, frame); + + Assert.AreEqual ("A/B", tag.GetTextFrame ("TPE1")); + Assert.AreEqual ("A/B", tag.Artist); + var values = tag.GetTextFrameValues ("TPE1"); + Assert.HasCount (2, values); + Assert.AreEqual ("A", values[0]); + Assert.AreEqual ("B", values[1]); + Assert.HasCount (2, tag.Performers); + } + + [TestMethod] + public void Lyrics_TrailingNul_DropsTerminator () + { + var tag = ReadFrame (TestConstants.Id3v2.Version4, "USLT", Utf16Comment ("eng", "", "yepa", terminated: true)); + + Assert.AreEqual ("yepa", tag.Lyrics); + AssertNoNul (tag.Lyrics); + } + + [TestMethod] + public void Lyrics_InternalNul_IsNotASeparator () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("eng"u8); + builder.Add (0); + builder.Add ((byte)'y', (byte)'e', 0, (byte)'p', (byte)'a', 0); + + var frame = LyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("ye\0pa", frame.Frame!.Text); + } + + [TestMethod] + public void UserText_TrailingNul_DropsTerminator () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf8); + builder.Add ("MOOD"u8); + builder.Add (0); + builder.Add ("yepa"u8); + builder.Add (0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TXXX", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("MOOD", tag.UserTextFrames[0].Description); + AssertNoNul (tag.UserTextFrames[0].Description); + Assert.AreEqual ("yepa", tag.GetUserText ("MOOD")); + AssertNoNul (tag.GetUserText ("MOOD")); + } + + [TestMethod] + public void UserText_InternalNul_IsKeptAndTrailingTerminatorIsNot () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf8); + builder.Add ("MOOD"u8); + builder.Add (0); + builder.Add ((byte)'y', (byte)'e', 0, (byte)'p', (byte)'a', 0); + + var frame = UserTextFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("ye\0pa", frame.Frame!.Value); + } + + [TestMethod] + public void UserText_Utf16ValueWithTerminator_DropsTrailingNul () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("MOOD")); + builder.Add (0, 0); + builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (0, 0); + + var frame = UserTextFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("MOOD", frame.Frame!.Description); + AssertNoNul (frame.Frame.Description); + Assert.AreEqual ("yepa", frame.Frame.Value); + AssertNoNul (frame.Frame.Value); + } + + [TestMethod] + public void UserUrl_DescriptionAndUrl_DropTrailingTerminator () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (0, 0); + builder.Add ("https://example.com"u8); + builder.Add (0); + + var frame = UserUrlFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("yepa", frame.Frame!.Description); + AssertNoNul (frame.Frame.Description); + Assert.AreEqual ("https://example.com", frame.Frame.Url); + AssertNoNul (frame.Frame.Url); + } + + [TestMethod] + public void UserUrl_Latin1Description_DropsTrailingUrlNul () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("site"u8); + builder.Add (0); + builder.Add ("https://example.com"u8); + builder.Add (0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "WXXX", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("site", tag.UserUrlFrames[0].Description); + AssertNoNul (tag.UserUrlFrames[0].Description); + Assert.AreEqual ("https://example.com", tag.GetUserUrl ("site")); + AssertNoNul (tag.GetUserUrl ("site")); + } + + [TestMethod] + public void SyncLyrics_TrailingTerminator_IsNotPartOfTheLine () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("eng"u8); + builder.Add ((byte)TimestampFormat.Milliseconds); + builder.Add ((byte)SyncLyricsType.Lyrics); + builder.Add (0); + builder.Add ("yepa"u8); + builder.Add (0); + builder.Add (0, 0, 0, 1); + builder.Add ("next"u8); + builder.Add (0); + builder.Add (0, 0, 0, 2); + + var frame = SyncLyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("", frame.Frame!.Description); + Assert.HasCount (2, frame.Frame.SyncItems); + Assert.AreEqual ("yepa", frame.Frame.SyncItems[0].Text); + AssertNoNul (frame.Frame.SyncItems[0].Text); + Assert.AreEqual (1u, frame.Frame.SyncItems[0].Timestamp); + Assert.AreEqual ("next", frame.Frame.SyncItems[1].Text); + AssertNoNul (frame.Frame.SyncItems[1].Text); + Assert.AreEqual (2u, frame.Frame.SyncItems[1].Timestamp); + } + + [TestMethod] + public void SyncLyrics_Utf16LineWithTerminator_DropsTrailingNul () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add ("eng"u8); + builder.Add ((byte)TimestampFormat.Milliseconds); + builder.Add ((byte)SyncLyricsType.Lyrics); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("desc")); + builder.Add (0, 0); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (0, 0); + builder.Add (0, 0, 0, 5); + + var frame = SyncLyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("desc", frame.Frame!.Description); + AssertNoNul (frame.Frame.Description); + Assert.HasCount (1, frame.Frame.SyncItems); + Assert.AreEqual ("yepa", frame.Frame.SyncItems[0].Text); + AssertNoNul (frame.Frame.SyncItems[0].Text); + Assert.AreEqual (5u, frame.Frame.SyncItems[0].Timestamp); + } + + [TestMethod] + public void GeneralObject_TrailingTerminator_IsNotPartOfTheText () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add ("text/plain"u8); + builder.Add (0); + builder.Add ("yepa.txt"u8); + builder.Add (0); + builder.Add ("cover"u8); + builder.Add (0); + builder.Add (0, 1, 0); + + var frame = GeneralObjectFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("yepa.txt", frame.Frame!.FileName); + AssertNoNul (frame.Frame.FileName); + Assert.AreEqual ("cover", frame.Frame.Description); + AssertNoNul (frame.Frame.Description); + CollectionAssert.AreEqual (new byte[] { 0, 1, 0 }, frame.Frame.Data.ToArray ()); + } + + [TestMethod] + public void GeneralObject_Utf16NamesWithTerminator_DropTrailingNul () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add ("application/octet-stream"u8); + builder.Add (0); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (0, 0); + builder.Add (Encoding.Unicode.GetBytes ("note")); + builder.Add (0, 0); + builder.Add (9); + + var frame = GeneralObjectFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("yepa", frame.Frame!.FileName); + AssertNoNul (frame.Frame.FileName); + Assert.AreEqual ("note", frame.Frame.Description); + AssertNoNul (frame.Frame.Description); + CollectionAssert.AreEqual (new byte[] { 9 }, frame.Frame.Data.ToArray ()); + } + + [TestMethod] + public void InvolvedPeople_TrailingTerminator_DoesNotCollapsePairs () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf8); + builder.Add ("guitar"u8); + builder.Add (0); + builder.Add ("Jane"u8); + builder.Add (0); + builder.Add ("bass"u8); + builder.Add (0); + builder.Add ("Bob"u8); + builder.Add (0); + + var frame = InvolvedPeopleFrame.Read ("TMCL", builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual (2, frame.Frame!.Count); + Assert.AreEqual ("Jane", frame.Frame.GetPerson ("guitar")); + Assert.AreEqual ("Bob", frame.Frame.GetPerson ("bass")); + AssertNoNul (frame.Frame.Pairs[0].Role); + AssertNoNul (frame.Frame.Pairs[0].Person); + AssertNoNul (frame.Frame.Pairs[1].Role); + AssertNoNul (frame.Frame.Pairs[1].Person); + } + + [TestMethod] + public void InvolvedPeople_Utf16PairsWithTerminator_KeepBothPairs () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("guitar")); + builder.Add (0, 0); + builder.Add (Encoding.Unicode.GetBytes ("Jane")); + builder.Add (0, 0); + builder.Add (Encoding.Unicode.GetBytes ("bass")); + builder.Add (0, 0); + builder.Add (Encoding.Unicode.GetBytes ("Bob")); + builder.Add (0, 0); + + var frame = InvolvedPeopleFrame.Read ("TIPL", builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual (2, frame.Frame!.Count); + Assert.AreEqual (("guitar", "Jane"), frame.Frame.Pairs[0]); + Assert.AreEqual (("bass", "Bob"), frame.Frame.Pairs[1]); + AssertNoNul (frame.Frame.Pairs[0].Person); + AssertNoNul (frame.Frame.Pairs[1].Person); + } + + static byte[] Utf16Comment (string language, string description, string text, bool terminated) + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (Encoding.ASCII.GetBytes (language)); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes (description)); + builder.Add (0, 0); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes (text)); + if (terminated) + builder.Add (0, 0); + return builder.ToBinaryData ().ToArray (); + } + + static byte[] Latin1DescribedText (TextEncodingType encoding, string language, string description, string text, bool terminated) + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)encoding); + builder.Add (Encoding.ASCII.GetBytes (language)); + builder.Add (Encoding.Latin1.GetBytes (description)); + builder.Add (0); + builder.Add (Encoding.Latin1.GetBytes (text)); + if (terminated) + builder.Add (0); + return builder.ToBinaryData ().ToArray (); + } + + static Id3v2Tag ReadFrame (byte version, string frameId, byte[] content) + { + var frame = TestBuilders.Id3v2.CreateFrame (frameId, content, version); + return ReadTag (version, frame); + } + + static Id3v2Tag ReadTag (byte version, params byte[][] frames) + { + var bodyLength = 0; + for (var i = 0; i < frames.Length; i++) + bodyLength += frames[i].Length; + + var header = TestBuilders.Id3v2.CreateHeader (version, (uint)bodyLength); + var bytes = new byte[header.Length + bodyLength]; + header.CopyTo (bytes, 0); + var offset = header.Length; + for (var i = 0; i < frames.Length; i++) { + frames[i].CopyTo (bytes, offset); + offset += frames[i].Length; + } + + var result = Id3v2Tag.Read (bytes); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } + + static void AssertNoNul (string? value) + { + Assert.IsNotNull (value); + Assert.AreEqual (-1, value.IndexOf ('\0')); + } +} From 791faa75010c9adcb1990a283d23c1af7afb23f4 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 20 Nov 2026 15:43:38 -0700 Subject: [PATCH 02/29] fix: Keep multi-value fields when a tag is copied The single-value composer and album artist are the first entry. Copying them after the array replaced the list with that one name. Fixes #128 --- src/TagLibSharp2/Core/Tag.cs | 6 ++++-- tests/TagLibSharp2.Tests/Core/TagCopyTests.cs | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 5eb98911..3fd52b46 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -1224,9 +1224,11 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) target.Genres = Genres; // Extended single values - if (AlbumArtist is not null) + // The singular value is the first entry. Writing it after the array + // replaces the whole list with that one name. + if (AlbumArtist is not null && AlbumArtists is not { Length: > 0 }) target.AlbumArtist = AlbumArtist; - if (Composer is not null) + if (Composer is not null && Composers is not { Length: > 0 }) target.Composer = Composer; if (Conductor is not null) target.Conductor = Conductor; diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs index 06a20f5a..f912362e 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs @@ -266,6 +266,7 @@ public void CopyTo_CopiesArrayProperties () { var source = new Id3v2Tag (); source.Performers = ["Artist 1", "Artist 2"]; + source.AlbumArtists = ["Album Artist 1", "Album Artist 2"]; source.Genres = ["Rock", "Pop"]; source.Composers = ["Composer 1", "Composer 2"]; @@ -276,8 +277,11 @@ public void CopyTo_CopiesArrayProperties () Assert.HasCount (2, target.Performers); Assert.AreEqual ("Artist 1", target.Performers[0]); Assert.AreEqual ("Artist 2", target.Performers[1]); + Assert.HasCount (2, target.AlbumArtists); + Assert.AreEqual ("Album Artist 1", target.AlbumArtist); Assert.HasCount (2, target.Genres); Assert.HasCount (2, target.Composers); + Assert.AreEqual ("Composer 1", target.Composer); } [TestMethod] From 6dcd383d2d28c1dcf8fe6f21260d1c7ecf1bf654 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 20 Nov 2026 18:15:03 -0700 Subject: [PATCH 03/29] fix: Keep every APE name and the first ID3 value A Basic copy still copies only the first artist and genre. That is the Basic contract. APE overrides of the performer, album artist, composer, and genre lists are what keep the extra names. UTF-16 values each use their own BOM. A comment or lyric ends at the first NUL. A leading NUL is an empty first value, not a skipped one. --- src/TagLibSharp2/Ape/ApeTag.cs | 93 +++++++ .../Id3/Id3v2/Frames/CommentFrame.cs | 4 +- .../Id3/Id3v2/Frames/GeneralObjectFrame.cs | 3 +- .../Id3/Id3v2/Frames/InvolvedPeopleFrame.cs | 2 +- .../Id3/Id3v2/Frames/LyricsFrame.cs | 4 +- .../Id3/Id3v2/Frames/SyncLyricsFrame.cs | 6 +- .../Id3/Id3v2/Frames/TextFrame.cs | 22 +- .../Id3/Id3v2/Frames/UserTextFrame.cs | 23 +- .../Id3/Id3v2/Frames/UserUrlFrame.cs | 4 +- src/TagLibSharp2/Id3/Id3v2/Id3Text.cs | 113 +++++++- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 26 +- tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs | 79 ++++++ tests/TagLibSharp2.Tests/Core/TagCopyTests.cs | 39 +++ .../Id3/Id3v2/Id3v2TrailingTerminatorTests.cs | 245 ++++++++++-------- .../TagLibSharp2.PublicApi.verified.txt | 4 + 15 files changed, 480 insertions(+), 187 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 1cd75c97..6493db85 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text; using TagLibSharp2.Core; #pragma warning disable CA1307 // Specify StringComparison for clarity - IndexOf with char doesn't need it @@ -181,6 +182,17 @@ public override string? Artist { set => SetOrRemove (Keys.Artist, value); } + /// + /// + /// Names share one item. A NUL separates them, and a single name has no extra NUL. + /// +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + public override string[] Performers { + get => GetTextList (Keys.Artist); + set => SetTextList (Keys.Artist, value); + } +#pragma warning restore CA1819 + /// public override string? Album { get => GetValue (Keys.Album); @@ -199,6 +211,21 @@ public override string? AlbumArtist { set => SetOrRemove (Keys.AlbumArtist, value); } + /// + /// + /// Names share one "Album Artist" item, separated by NUL. A single name has no extra NUL. + /// Reading also accepts "ALBUMARTIST". + /// +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + public override string[] AlbumArtists { + get { + var values = GetTextList (Keys.AlbumArtist); + return values.Length > 0 ? values : GetTextList ("ALBUMARTIST"); + } + set => SetTextList (Keys.AlbumArtist, value); + } +#pragma warning restore CA1819 + /// public override string? Year { get => GetValue (Keys.Year) ?? GetValue (Keys.Date); @@ -217,6 +244,17 @@ public override string? Genre { set => SetOrRemove (Keys.Genre, value); } + /// + /// + /// Names share one item. A NUL separates them, and a single name has no extra NUL. + /// +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + public override string[] Genres { + get => GetTextList (Keys.Genre); + set => SetTextList (Keys.Genre, value); + } +#pragma warning restore CA1819 + /// public override uint? Track { get => ParseTrackDisc (GetValue (Keys.Track))?.Number; @@ -297,6 +335,17 @@ public override string? Composer { set => SetOrRemove (Keys.Composer, value); } + /// + /// + /// Names share one item. A NUL separates them, and a single name has no extra NUL. + /// +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + public override string[] Composers { + get => GetTextList (Keys.Composer); + set => SetTextList (Keys.Composer, value); + } +#pragma warning restore CA1819 + /// public override string? Conductor { get => GetValue (Keys.Conductor); @@ -728,6 +777,50 @@ public void SetValue (string key, string value) _items[key] = ApeTagItem.CreateText (key, value); } + /// + /// Reads every non-empty NUL-separated value. Internal NULs are separators, not stripped text. + /// + string[] GetTextList (string key) + { + if (!_items.TryGetValue (key, out var item) || item.ItemType != ApeItemType.Text) + return []; + + var text = Encoding.UTF8.GetString (item.RawValue); + if (text.Length == 0) + return []; + + var parts = text.Split ('\0'); + var result = new List (parts.Length); + for (var i = 0; i < parts.Length; i++) { + if (parts[i].Length != 0) + result.Add (parts[i]); + } + + return result.Count == 0 ? [] : result.ToArray (); + } + + /// + /// Stores names in one item. A single name has no extra NUL. + /// + void SetTextList (string key, string[]? values) + { + if (values is null || values.Length == 0) { + _items.Remove (key); + return; + } + + var kept = new List (values.Length); + for (var i = 0; i < values.Length; i++) { + if (!string.IsNullOrEmpty (values[i])) + kept.Add (values[i]); + } + + if (kept.Count == 0) + _items.Remove (key); + else + SetValue (key, string.Join ("\0", kept)); + } + /// /// Gets a binary item by key (e.g., cover art). /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs index f5870edf..2bc05b42 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs @@ -201,8 +201,8 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - // A comment is one string. Drop only a trailing terminator. - data = Id3Text.TrimTrailingTerminator (data, encoding); + // A comment is one string. An internal NUL ends it. + data = Id3Text.CutAtFirstNul (data, encoding); return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs index 9421ed74..ad3f551a 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs @@ -197,8 +197,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - data = Id3Text.TrimTrailingTerminator (data, encoding); - + // ReadNullTerminatedString already dropped this field's terminator. return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs index 973ad8fe..f7072f5c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs @@ -346,7 +346,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - // Each role or person is already split. Drop only that piece's trailing terminator. + // The last unterminated piece can end on a lone byte. Do not let that byte eat the character. data = Id3Text.TrimTrailingTerminator (data, encoding); return encoding switch { diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs index 0edd3fcb..9f40be57 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs @@ -201,8 +201,8 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - // Lyrics are one string. Drop only a trailing terminator. - data = Id3Text.TrimTrailingTerminator (data, encoding); + // Lyrics are one string. An internal NUL ends them. + data = Id3Text.CutAtFirstNul (data, encoding); return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs index 665e6d29..794cd61b 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs @@ -251,7 +251,7 @@ public static SyncLyricsFrameReadResult Read (ReadOnlySpan data, Id3v2Vers Description = description }; - // Read synchronized items + // A NUL ends that line only. Later timestamps are still read. while (remaining.Length > 4) { var (text, textBytes) = ReadNullTerminatedString (remaining, encoding); remaining = remaining.Slice (textBytes); @@ -374,9 +374,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - // A lyric line is one string, not a NUL-separated list. Drop only a trailing terminator. - data = Id3Text.TrimTrailingTerminator (data, encoding); - + // ReadNullTerminatedString already ended this line at the first NUL. return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs index 89e84532..552a8f6d 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -115,26 +115,8 @@ static string DecodeTextUtf8 (ReadOnlySpan data) return System.Text.Encoding.UTF8.GetString (data); } - static string DecodeTextUtf16WithBom (ReadOnlySpan data) - { - if (data.Length < 2) - return string.Empty; - - // Check BOM to determine endianness - var isLittleEndian = data[0] == 0xFF && data[1] == 0xFE; - var isBigEndian = data[0] == 0xFE && data[1] == 0xFF; - - if (!isLittleEndian && !isBigEndian) { - // No BOM found - fall back to little-endian (Windows default) - // This handles buggy taggers that don't write BOM - return DecodeTextUtf16 (data, isLittleEndian: true); - } - - // Skip BOM - data = data.Slice (2); - - return DecodeTextUtf16 (data, isLittleEndian); - } + static string DecodeTextUtf16WithBom (ReadOnlySpan data) => + Id3Text.DecodeUtf16BomText (data); static string DecodeTextUtf16BE (ReadOnlySpan data) { diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs index 1cd50766..dcf79d0c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -161,33 +161,12 @@ 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.Utf16WithBom => Id3Text.DecodeUtf16BomText (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 - data = data.Slice (2); - var encoding = isLittleEndian - ? System.Text.Encoding.Unicode - : System.Text.Encoding.BigEndianUnicode; - - return encoding.GetString (data); - } - static BinaryData EncodeText (string text, TextEncodingType encoding) { return encoding switch { diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs index 0d76792b..06c457e2 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs @@ -159,9 +159,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; - // Descriptions follow the text rule: a trailing terminator is not part of the string. - data = Id3Text.TrimTrailingTerminator (data, encoding); - + // The description slice already stops at its terminator. return encoding switch { TextEncodingType.Latin1 => Polyfills.Latin1.GetString (data), TextEncodingType.Utf8 => System.Text.Encoding.UTF8.GetString (data), diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs index 5be4e017..355bf695 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -1,6 +1,8 @@ // 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; + namespace TagLibSharp2.Id3.Id3v2; /// @@ -9,19 +11,120 @@ namespace TagLibSharp2.Id3.Id3v2; internal static class Id3Text { /// - /// Drops trailing string terminators. Internal NULs stay: ID3v2.4 uses them to - /// separate values, and a comment or lyric line is one string. + /// Drops trailing terminators. A lone UTF-16 byte is not a terminator unit: + /// pairing it with the previous byte would consume the last character. /// internal static ReadOnlySpan TrimTrailingTerminator (ReadOnlySpan data, TextEncodingType encoding) { if (encoding is TextEncodingType.Utf16WithBom or TextEncodingType.Utf16BE) { - while (data.Length >= 2 && data[data.Length - 2] == 0 && data[data.Length - 1] == 0) - data = data.Slice (0, data.Length - 2); - return data; + var length = data.Length; + if ((length & 1) != 0) + length--; + + while (length >= 2 && data[length - 2] == 0 && data[length - 1] == 0) + length -= 2; + + return data.Slice (0, length); } while (data.Length > 0 && data[data.Length - 1] == 0) data = data.Slice (0, data.Length - 1); return data; } + + /// + /// Ends one comment or lyric at the first NUL. Text-frame values stay separated. + /// + internal static ReadOnlySpan CutAtFirstNul (ReadOnlySpan data, TextEncodingType encoding) + { + data = TrimTrailingTerminator (data, encoding); + if (encoding is TextEncodingType.Utf16WithBom or TextEncodingType.Utf16BE) { + var split = IndexOfUtf16Nul (data); + return split < 0 ? data : data.Slice (0, split); + } + + var index = data.IndexOf ((byte)0); + return index < 0 ? data : data.Slice (0, index); + } + + /// + /// 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 + } + + static int IndexOfUtf16Nul (ReadOnlySpan data) + { + for (var i = 0; i + 1 < data.Length; i += 2) { + if (data[i] == 0 && data[i + 1] == 0) + return i; + } + + return -1; + } } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index bcf701dc..d974c096 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1451,7 +1451,7 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) /// /// The frame ID (e.g., TIT2, TPE1). /// - /// The first non-empty value, or null if the frame is absent. + /// The first value, even when that value is empty, or null when the frame is absent. /// A NUL separates further values and is not included. A slash is not a separator here. /// public string? GetTextFrame (string frameId) @@ -1477,25 +1477,16 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) } /// - /// Returns the first non-empty NUL-separated piece. No slash split. + /// Returns the text before the first NUL. A leading NUL is an empty value, not a reason to skip ahead. /// static string FirstTextValue (string text) { - var start = 0; for (var i = 0; i < text.Length; i++) { - if (text[i] != '\0') - continue; - - if (i > start) - return text.Substring (start, i - start); - start = i + 1; + if (text[i] == '\0') + return text.Substring (0, i); } - if (start == 0) - return text; - if (start < text.Length) - return text.Substring (start); - return string.Empty; + return text; } /// @@ -2112,12 +2103,15 @@ public void RemoveComments (string? language = null, string? description = null) /// Gets the value of a user-defined text frame (TXXX) by description. /// /// The description (key) of the TXXX frame. - /// The value, or null if not found. + /// + /// The first value, even when that value is empty, or null when the frame is absent. + /// An embedded NUL is not included. The frame still stores the rest of the text. + /// public string? GetUserText (string description) { for (var i = 0; i < _userTextFrames.Count; i++) { if (string.Equals (_userTextFrames[i].Description, description, StringComparison.OrdinalIgnoreCase)) - return _userTextFrames[i].Value; + return FirstTextValue (_userTextFrames[i].Value); } return null; } diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index cce27d50..aec0037e 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System.Globalization; +using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using TagLibSharp2.Ape; using TagLibSharp2.Core; @@ -1657,6 +1658,84 @@ public void ApeTagHeaderParseResult_Equality_WorksCorrectly () Assert.IsTrue (failure.Equals ((object)failure)); } + [TestMethod] + public void TextLists_RoundTrip_KeepsEveryNameWithoutAnExtraNul () + { + var tag = new ApeTag { + Performers = ["Eve", "Fay"], + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Genres = ["Jazz", "Soul"] + }; + + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("Fay", tag.Performers[1]); + Assert.HasCount (2, tag.AlbumArtists); + Assert.AreEqual ("Bea", tag.AlbumArtists[1]); + Assert.HasCount (2, tag.Composers); + Assert.AreEqual ("Dan", tag.Composers[1]); + Assert.HasCount (2, tag.Genres); + Assert.AreEqual ("Soul", tag.Genres[1]); + AssertRaw (tag, "Artist", "Eve\0Fay"); + AssertRaw (tag, "Album Artist", "Ada\0Bea"); + AssertRaw (tag, "Composer", "Cara\0Dan"); + AssertRaw (tag, "Genre", "Jazz\0Soul"); + + var parsedMany = ApeTag.Parse (tag.Render ().Span); + Assert.IsTrue (parsedMany.IsSuccess, parsedMany.Error); + Assert.HasCount (2, parsedMany.Tag!.AlbumArtists); + Assert.AreEqual ("Ada", parsedMany.Tag.AlbumArtists[0]); + Assert.AreEqual ("Bea", parsedMany.Tag.AlbumArtists[1]); + Assert.HasCount (2, parsedMany.Tag.Composers); + Assert.HasCount (2, parsedMany.Tag.Performers); + Assert.HasCount (2, parsedMany.Tag.Genres); + + tag.Performers = ["Eve"]; + tag.AlbumArtists = ["Ada"]; + tag.Composers = ["Cara"]; + tag.Genres = ["Jazz"]; + AssertRaw (tag, "Artist", "Eve"); + AssertRaw (tag, "Album Artist", "Ada"); + AssertRaw (tag, "Composer", "Cara"); + AssertRaw (tag, "Genre", "Jazz"); + + var parsed = ApeTag.Parse (tag.Render ().Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.HasCount (1, parsed.Tag!.Performers); + Assert.AreEqual ("Eve", parsed.Tag.Performers[0]); + Assert.AreEqual ("Ada", parsed.Tag.AlbumArtists[0]); + Assert.AreEqual ("Cara", parsed.Tag.Composers[0]); + Assert.AreEqual ("Jazz", parsed.Tag.Genres[0]); + + var alias = new ApeTag (); + alias.SetValue ("ALBUMARTIST", "Ada\0Bea"); + Assert.HasCount (2, alias.AlbumArtists); + Assert.AreEqual ("Ada", alias.AlbumArtists[0]); + Assert.AreEqual ("Bea", alias.AlbumArtists[1]); + } + + static void AssertRaw (ApeTag tag, string key, string expected) + { + var raw = RawText (tag, key); + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (expected), raw); + } + + static byte[] RawText (ApeTag tag, string key) + { + var bytes = tag.Render ().ToArray (); + var items = bytes.AsSpan (0, bytes.Length - ApeTagFooter.Size); + while (!items.IsEmpty) { + var parsed = ApeTagItem.Parse (items); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + if (string.Equals (parsed.Item!.Key, key, StringComparison.OrdinalIgnoreCase)) + return parsed.Item.RawValue; + items = items.Slice (parsed.BytesConsumed); + } + + Assert.Fail ("Missing " + key); + return []; + } + [TestMethod] public void ApeTagItemParseResult_Equality_WorksCorrectly () { diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs index f912362e..5a3f406e 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs @@ -1,6 +1,7 @@ // 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.Ape; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Id3.Id3v2.Frames; @@ -284,6 +285,44 @@ public void CopyTo_CopiesArrayProperties () Assert.AreEqual ("Composer 1", target.Composer); } + [TestMethod] + public void CopyTo_Id3v2ToApe_KeepsAlbumArtistsAndComposers () + { + var source = new Id3v2Tag { + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Performers = ["Eve", "Fay"], + Genres = ["Jazz", "Soul"] + }; + + // The single-value getter stays the first name, not the NUL-joined blob. + Assert.AreEqual ("Ada", source.AlbumArtist); + Assert.AreEqual ("Cara", source.Composer); + Assert.AreEqual ("Eve", source.Artist); + Assert.AreEqual ("Jazz", source.Genre); + Assert.AreEqual (-1, source.GetTextFrame ("TPE2")!.IndexOf ('\0')); + + var target = new ApeTag (); + source.CopyTo (target); + + var parsed = ApeTag.Parse (target.Render ().Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + var round = parsed.Tag!; + + Assert.HasCount (2, round.AlbumArtists); + Assert.AreEqual ("Ada", round.AlbumArtists[0]); + Assert.AreEqual ("Bea", round.AlbumArtists[1]); + Assert.HasCount (2, round.Composers); + Assert.AreEqual ("Cara", round.Composers[0]); + Assert.AreEqual ("Dan", round.Composers[1]); + Assert.HasCount (2, round.Performers); + Assert.AreEqual ("Eve", round.Performers[0]); + Assert.AreEqual ("Fay", round.Performers[1]); + Assert.HasCount (2, round.Genres); + Assert.AreEqual ("Jazz", round.Genres[0]); + Assert.AreEqual ("Soul", round.Genres[1]); + } + [TestMethod] public void CopyTo_CopiesCompilationFlag () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs index f6aeb9da..62c0064d 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -9,7 +9,8 @@ namespace TagLibSharp2.Tests.Id3.Id3v2; /// -/// A stored terminator is not part of the text. Internal NULs still separate values. +/// A stored terminator is not part of the text. +/// Text frames keep internal NULs between values. A comment or lyric ends at the first NUL. /// [TestClass] [TestCategory ("Unit")] @@ -56,7 +57,7 @@ public void Comment_Utf16BeWithTerminator_DropsTrailingNul () } [TestMethod] - public void Comment_InternalNul_IsNotASeparator () + public void Comment_InternalNul_EndsTheText () { // Description terminator, then ye + NUL + pa, then a trailing terminator. using var builder = new BinaryDataBuilder (); @@ -67,8 +68,17 @@ public void Comment_InternalNul_IsNotASeparator () var tag = ReadFrame (TestConstants.Id3v2.Version4, "COMM", builder.ToBinaryData ().ToArray ()); - Assert.AreEqual ("ye\0pa", tag.Comment); - Assert.AreEqual (2, tag.Comment!.IndexOf ('\0')); + Assert.AreEqual ("ye", tag.Comment); + AssertNoNul (tag.Comment); + } + + [TestMethod] + public void Comment_Utf16InternalNul_EndsTheText () + { + var tag = ReadFrame (TestConstants.Id3v2.Version4, "COMM", Utf16Comment ("eng", "", "ye\0pa", terminated: true)); + + Assert.AreEqual ("ye", tag.Comment); + AssertNoNul (tag.Comment); } [TestMethod] @@ -166,7 +176,7 @@ public void Lyrics_TrailingNul_DropsTerminator () } [TestMethod] - public void Lyrics_InternalNul_IsNotASeparator () + public void Lyrics_InternalNul_EndsTheText () { using var builder = new BinaryDataBuilder (); builder.Add ((byte)TextEncodingType.Latin1); @@ -177,7 +187,18 @@ public void Lyrics_InternalNul_IsNotASeparator () var frame = LyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual ("ye\0pa", frame.Frame!.Text); + Assert.AreEqual ("ye", frame.Frame!.Text); + AssertNoNul (frame.Frame.Text); + } + + [TestMethod] + public void Lyrics_Utf16InternalNul_EndsTheText () + { + var frame = LyricsFrame.Read (Utf16Comment ("eng", "", "ye\0pa", terminated: true), Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual ("ye", frame.Frame!.Text); + AssertNoNul (frame.Frame.Text); } [TestMethod] @@ -272,157 +293,161 @@ public void UserUrl_Latin1Description_DropsTrailingUrlNul () } [TestMethod] - public void SyncLyrics_TrailingTerminator_IsNotPartOfTheLine () + public void InvolvedPeople_Utf16OddLength_DoesNotDropTheLastCharacter () { using var builder = new BinaryDataBuilder (); - builder.Add ((byte)TextEncodingType.Latin1); - builder.Add ("eng"u8); - builder.Add ((byte)TimestampFormat.Milliseconds); - builder.Add ((byte)SyncLyricsType.Lyrics); - builder.Add (0); - builder.Add ("yepa"u8); - builder.Add (0); - builder.Add (0, 0, 0, 1); - builder.Add ("next"u8); - builder.Add (0); - builder.Add (0, 0, 0, 2); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("guitar")); + builder.Add (0, 0); + builder.Add (0x41, 0x00); // A + builder.Add (0x00); // lone byte; pairing it with the low byte of A would eat the name - var frame = SyncLyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + var frame = InvolvedPeopleFrame.Read ("TIPL", builder.ToBinaryData ().Span, Id3v2Version.V24); Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual ("", frame.Frame!.Description); - Assert.HasCount (2, frame.Frame.SyncItems); - Assert.AreEqual ("yepa", frame.Frame.SyncItems[0].Text); - AssertNoNul (frame.Frame.SyncItems[0].Text); - Assert.AreEqual (1u, frame.Frame.SyncItems[0].Timestamp); - Assert.AreEqual ("next", frame.Frame.SyncItems[1].Text); - AssertNoNul (frame.Frame.SyncItems[1].Text); - Assert.AreEqual (2u, frame.Frame.SyncItems[1].Timestamp); + Assert.AreEqual (1, frame.Frame!.Count); + Assert.AreEqual ("A", frame.Frame.GetPerson ("guitar")); } [TestMethod] - public void SyncLyrics_Utf16LineWithTerminator_DropsTrailingNul () + public void Performers_Utf16BomOnEachValue_ReturnsBothNames () { using var builder = new BinaryDataBuilder (); builder.Add ((byte)TextEncodingType.Utf16WithBom); - builder.Add ("eng"u8); - builder.Add ((byte)TimestampFormat.Milliseconds); - builder.Add ((byte)SyncLyricsType.Lyrics); builder.Add (0xFF, 0xFE); - builder.Add (Encoding.Unicode.GetBytes ("desc")); + builder.Add (Encoding.Unicode.GetBytes ("a")); builder.Add (0, 0); builder.Add (0xFF, 0xFE); - builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (Encoding.Unicode.GetBytes ("b")); builder.Add (0, 0); - builder.Add (0, 0, 0, 5); - var frame = SyncLyricsFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); - Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual ("desc", frame.Frame!.Description); - AssertNoNul (frame.Frame.Description); - Assert.HasCount (1, frame.Frame.SyncItems); - Assert.AreEqual ("yepa", frame.Frame.SyncItems[0].Text); - AssertNoNul (frame.Frame.SyncItems[0].Text); - Assert.AreEqual (5u, frame.Frame.SyncItems[0].Timestamp); + Assert.AreEqual ("a\0b", tag.Frames[0].Text); + Assert.AreEqual (-1, tag.Frames[0].Text.IndexOf ('\uFEFF')); + Assert.AreEqual ("a", tag.GetTextFrame ("TPE1")); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("a", tag.Performers[0]); + Assert.AreEqual ("b", tag.Performers[1]); + Assert.AreEqual ("a", tag.Artist); } [TestMethod] - public void GeneralObject_TrailingTerminator_IsNotPartOfTheText () + public void Performers_Utf16SecondValueBigEndianBom_ReturnsBothNames () { using var builder = new BinaryDataBuilder (); - builder.Add ((byte)TextEncodingType.Latin1); - builder.Add ("text/plain"u8); - builder.Add (0); - builder.Add ("yepa.txt"u8); - builder.Add (0); - builder.Add ("cover"u8); - builder.Add (0); - builder.Add (0, 1, 0); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (0x61, 0x00); + builder.Add (0, 0); + builder.Add (0xFE, 0xFF); + builder.Add (0x00, 0x62); - var frame = GeneralObjectFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); - Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual ("yepa.txt", frame.Frame!.FileName); - AssertNoNul (frame.Frame.FileName); - Assert.AreEqual ("cover", frame.Frame.Description); - AssertNoNul (frame.Frame.Description); - CollectionAssert.AreEqual (new byte[] { 0, 1, 0 }, frame.Frame.Data.ToArray ()); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("a", tag.Performers[0]); + Assert.AreEqual ("b", tag.Performers[1]); + Assert.AreEqual (-1, tag.Performers[1].IndexOf ('\uFEFF')); } [TestMethod] - public void GeneralObject_Utf16NamesWithTerminator_DropTrailingNul () + public void Performers_Utf16SecondValueWithoutBom_UsesFirstBom () { using var builder = new BinaryDataBuilder (); builder.Add ((byte)TextEncodingType.Utf16WithBom); - builder.Add ("application/octet-stream"u8); - builder.Add (0); - builder.Add (0xFF, 0xFE); - builder.Add (Encoding.Unicode.GetBytes ("yepa")); + builder.Add (0xFE, 0xFF); + builder.Add (0x00, 0x61); builder.Add (0, 0); - builder.Add (Encoding.Unicode.GetBytes ("note")); - builder.Add (0, 0); - builder.Add (9); + builder.Add (0x00, 0x62); - var frame = GeneralObjectFrame.Read (builder.ToBinaryData ().Span, Id3v2Version.V24); + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); - Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual ("yepa", frame.Frame!.FileName); - AssertNoNul (frame.Frame.FileName); - Assert.AreEqual ("note", frame.Frame.Description); - AssertNoNul (frame.Frame.Description); - CollectionAssert.AreEqual (new byte[] { 9 }, frame.Frame.Data.ToArray ()); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("a", tag.Performers[0]); + Assert.AreEqual ("b", tag.Performers[1]); } [TestMethod] - public void InvolvedPeople_TrailingTerminator_DoesNotCollapsePairs () + public void Title_Utf16OddLength_DoesNotDropLastCharacter () { using var builder = new BinaryDataBuilder (); - builder.Add ((byte)TextEncodingType.Utf8); - builder.Add ("guitar"u8); - builder.Add (0); - builder.Add ("Jane"u8); - builder.Add (0); - builder.Add ("bass"u8); - builder.Add (0); - builder.Add ("Bob"u8); - builder.Add (0); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (0x41, 0x00); + builder.Add (0x42, 0x00); + builder.Add (0x00); - var frame = InvolvedPeopleFrame.Read ("TMCL", builder.ToBinaryData ().Span, Id3v2Version.V24); + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", builder.ToBinaryData ().ToArray ()); - Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual (2, frame.Frame!.Count); - Assert.AreEqual ("Jane", frame.Frame.GetPerson ("guitar")); - Assert.AreEqual ("Bob", frame.Frame.GetPerson ("bass")); - AssertNoNul (frame.Frame.Pairs[0].Role); - AssertNoNul (frame.Frame.Pairs[0].Person); - AssertNoNul (frame.Frame.Pairs[1].Role); - AssertNoNul (frame.Frame.Pairs[1].Person); + Assert.AreEqual ("AB", tag.Title); + Assert.AreEqual ("AB", tag.Frames[0].Text); } [TestMethod] - public void InvolvedPeople_Utf16PairsWithTerminator_KeepBothPairs () + public void Text_LeadingNul_FirstValueIsEmpty () { using var builder = new BinaryDataBuilder (); - builder.Add ((byte)TextEncodingType.Utf16WithBom); - builder.Add (0xFF, 0xFE); - builder.Add (Encoding.Unicode.GetBytes ("guitar")); - builder.Add (0, 0); - builder.Add (Encoding.Unicode.GetBytes ("Jane")); - builder.Add (0, 0); - builder.Add (Encoding.Unicode.GetBytes ("bass")); - builder.Add (0, 0); - builder.Add (Encoding.Unicode.GetBytes ("Bob")); - builder.Add (0, 0); + builder.Add ((byte)TextEncodingType.Latin1); + builder.Add (0, (byte)'b', 0); + var leading = builder.ToBinaryData ().ToArray (); + + var v23 = ReadFrame (TestConstants.Id3v2.Version3, "TIT2", leading); + Assert.AreEqual ("", v23.GetTextFrame ("TIT2")); + Assert.AreEqual ("\0b", v23.Frames[0].Text); + var values23 = v23.GetTextFrameValues ("TIT2"); + Assert.HasCount (1, values23); + Assert.AreEqual ("b", values23[0]); + + var v24 = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", leading); + Assert.AreEqual ("", v24.GetTextFrame ("TIT2")); + var values24 = v24.GetTextFrameValues ("TIT2"); + Assert.HasCount (1, values24); + Assert.AreEqual ("b", values24[0]); + + using var skipped = new BinaryDataBuilder (); + skipped.Add ((byte)TextEncodingType.Latin1); + skipped.Add (0, 0, (byte)'T'); + var allEmpty = ReadFrame (TestConstants.Id3v2.Version3, "TIT2", skipped.ToBinaryData ().ToArray ()); + Assert.AreEqual ("", allEmpty.GetTextFrame ("TIT2")); + Assert.AreEqual ("T", allEmpty.GetTextFrameValues ("TIT2")[0]); + Assert.IsNull (new Id3v2Tag ().GetTextFrame ("TIT2")); + } - var frame = InvolvedPeopleFrame.Read ("TIPL", builder.ToBinaryData ().Span, Id3v2Version.V24); + [TestMethod] + public void CatalogNumber_EmbeddedNul_ReturnsFirstValue () + { + var catalog = UserText ("CATALOGNUMBER", "A\0B"); + var barcode = UserText ("BARCODE", "A\0B"); + var tag = ReadTag ( + TestConstants.Id3v2.Version4, + TestBuilders.Id3v2.CreateFrame ("TXXX", catalog, TestConstants.Id3v2.Version4), + TestBuilders.Id3v2.CreateFrame ("TXXX", barcode, TestConstants.Id3v2.Version4)); + + Assert.AreEqual ("A", tag.CatalogNumber); + Assert.AreEqual ("A", tag.Barcode); + Assert.AreEqual ("A", tag.GetUserText ("CATALOGNUMBER")); + AssertNoNul (tag.CatalogNumber); + + string? stored = null; + for (var i = 0; i < tag.UserTextFrames.Count; i++) { + if (tag.UserTextFrames[i].Description == "CATALOGNUMBER") + stored = tag.UserTextFrames[i].Value; + } - Assert.IsTrue (frame.IsSuccess, frame.Error); - Assert.AreEqual (2, frame.Frame!.Count); - Assert.AreEqual (("guitar", "Jane"), frame.Frame.Pairs[0]); - Assert.AreEqual (("bass", "Bob"), frame.Frame.Pairs[1]); - AssertNoNul (frame.Frame.Pairs[0].Person); - AssertNoNul (frame.Frame.Pairs[1].Person); + Assert.AreEqual ("A\0B", stored); + Assert.IsNull (tag.GetUserText ("MISSING")); + } + + static byte[] UserText (string description, string value) + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf8); + builder.Add (Encoding.UTF8.GetBytes (description)); + builder.Add (0); + builder.Add (Encoding.UTF8.GetBytes (value)); + return builder.ToBinaryData ().ToArray (); } static byte[] Utf16Comment (string language, string description, string text, bool terminated) diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 1b99c9e8..fe0ee779 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -118,6 +118,7 @@ namespace TagLibSharp2.Ape 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; } @@ -128,6 +129,7 @@ namespace TagLibSharp2.Ape 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 override string? Copyright { get; set; } public override string? DateTagged { get; set; } @@ -138,6 +140,7 @@ namespace TagLibSharp2.Ape public override string? EncodedBy { get; set; } public override string? EncoderSettings { get; set; } 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; } @@ -162,6 +165,7 @@ namespace TagLibSharp2.Ape 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; } From 8c8e23a13109b83b0c40de3ba6a286f060bc8150 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 20 Nov 2026 21:21:59 -0700 Subject: [PATCH 04/29] fix: Read the first APE name and drop the stale album-artist item Setting or clearing album artists removes both Album Artist and ALBUMARTIST. Artist, album artist, composer, and genre return the first name. A copy into MP4 or ASF still keeps only that first name. --- src/TagLibSharp2/Ape/ApeTag.cs | 43 ++-- tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs | 143 ++++++++++++++ tests/TagLibSharp2.Tests/Core/TagCopyTests.cs | 82 ++++++++ .../Id3/Id3v2/Id3v2TrailingTerminatorTests.cs | 187 ++++++++++++++++++ 4 files changed, 443 insertions(+), 12 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 6493db85..c8e83eb5 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -92,6 +92,7 @@ private static class Keys public const string Artist = "Artist"; public const string Album = "Album"; public const string AlbumArtist = "Album Artist"; + public const string AlbumArtistAlias = "ALBUMARTIST"; public const string Year = "Year"; public const string Date = "Date"; // Alternative to Year public const string Comment = "Comment"; @@ -177,8 +178,11 @@ public override string? Title { } /// + /// + /// The first performer. Other names stay on ; a comma does not join them. + /// public override string? Artist { - get => GetValue (Keys.Artist); + get => FirstName (Performers); set => SetOrRemove (Keys.Artist, value); } @@ -203,26 +207,26 @@ public override string? Album { /// Gets or sets the album artist. /// /// - /// Reads from "Album Artist" with fallback to "ALBUMARTIST" for compatibility. - /// Writes to "Album Artist". + /// The first album artist. Reads "Album Artist", or "ALBUMARTIST" when that item is absent. + /// Setting or clearing removes both items and stores the name in "Album Artist". /// public override string? AlbumArtist { - get => GetValue (Keys.AlbumArtist) ?? GetValue ("ALBUMARTIST"); - set => SetOrRemove (Keys.AlbumArtist, value); + get => FirstName (AlbumArtists); + set => SetOrRemove (Keys.AlbumArtist, value, Keys.AlbumArtistAlias); } /// /// /// Names share one "Album Artist" item, separated by NUL. A single name has no extra NUL. - /// Reading also accepts "ALBUMARTIST". + /// Reading also accepts "ALBUMARTIST". Setting or clearing removes both items. /// #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public override string[] AlbumArtists { get { var values = GetTextList (Keys.AlbumArtist); - return values.Length > 0 ? values : GetTextList ("ALBUMARTIST"); + return values.Length > 0 ? values : GetTextList (Keys.AlbumArtistAlias); } - set => SetTextList (Keys.AlbumArtist, value); + set => SetTextList (Keys.AlbumArtist, value, Keys.AlbumArtistAlias); } #pragma warning restore CA1819 @@ -239,8 +243,11 @@ public override string? Comment { } /// + /// + /// The first genre. Other names stay on ; a comma does not join them. + /// public override string? Genre { - get => GetValue (Keys.Genre); + get => FirstName (Genres); set => SetOrRemove (Keys.Genre, value); } @@ -330,8 +337,11 @@ public override string? DiscSubtitle { } /// + /// + /// The first composer. Other names stay on ; a comma does not join them. + /// public override string? Composer { - get => GetValue (Keys.Composer); + get => FirstName (Composers); set => SetOrRemove (Keys.Composer, value); } @@ -799,11 +809,17 @@ string[] GetTextList (string key) return result.Count == 0 ? [] : result.ToArray (); } + static string? FirstName (string[] names) => names.Length == 0 ? null : names[0]; + /// /// Stores names in one item. A single name has no extra NUL. + /// is removed on set and on clear so a second item cannot outlive the write. /// - void SetTextList (string key, string[]? values) + void SetTextList (string key, string[]? values, string? alias = null) { + if (alias is not null) + _items.Remove (alias); + if (values is null || values.Length == 0) { _items.Remove (key); return; @@ -842,8 +858,11 @@ public void SetBinaryItem (string key, string filename, byte[] data) /// public bool Remove (string key) => _items.Remove (key); - private void SetOrRemove (string key, string? value) + private void SetOrRemove (string key, string? value, string? alias = null) { + if (alias is not null) + _items.Remove (alias); + if (string.IsNullOrEmpty (value)) { _items.Remove (key); } else { diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index aec0037e..855fc44b 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs @@ -1714,6 +1714,149 @@ public void TextLists_RoundTrip_KeepsEveryNameWithoutAnExtraNul () Assert.AreEqual ("Bea", alias.AlbumArtists[1]); } + [TestMethod] + public void SingularNames_ReturnTheFirstListValue () + { + var tag = new ApeTag { + Performers = ["A", "B"], + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Genres = ["Jazz", "Soul"] + }; + + Assert.AreEqual ("A", tag.Artist); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("A", tag.Performers[0]); + Assert.AreEqual ("B", tag.Performers[1]); + Assert.AreEqual ("Ada", tag.AlbumArtist); + Assert.HasCount (2, tag.AlbumArtists); + Assert.AreEqual ("Bea", tag.AlbumArtists[1]); + Assert.AreEqual ("Cara", tag.Composer); + Assert.HasCount (2, tag.Composers); + Assert.AreEqual ("Dan", tag.Composers[1]); + Assert.AreEqual ("Jazz", tag.Genre); + Assert.HasCount (2, tag.Genres); + Assert.AreEqual ("Soul", tag.Genres[1]); + + var parsed = ApeTag.Parse (tag.Render ().Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.AreEqual ("A", parsed.Tag!.Artist); + Assert.HasCount (2, parsed.Tag.Performers); + Assert.AreEqual ("B", parsed.Tag.Performers[1]); + Assert.AreEqual ("Ada", parsed.Tag.AlbumArtist); + Assert.AreEqual ("Cara", parsed.Tag.Composer); + Assert.AreEqual ("Jazz", parsed.Tag.Genre); + Assert.HasCount (2, parsed.Tag.Genres); + } + + [TestMethod] + public void AlbumArtists_SetAndClear_RemovesBothItemNames () + { + var replaced = new ApeTag (); + replaced.SetValue ("Album Artist", "Cara\0Dan"); + replaced.SetValue ("ALBUMARTIST", "Ada\0Bea"); + replaced.AlbumArtists = ["A"]; + + Assert.AreEqual ("A", replaced.AlbumArtist); + Assert.HasCount (1, replaced.AlbumArtists); + Assert.AreEqual ("A", replaced.AlbumArtists[0]); + Assert.IsNull (replaced.GetValue ("ALBUMARTIST")); + AssertRaw (replaced, "Album Artist", "A"); + + var parsed = ApeTag.Parse (replaced.Render ().Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.HasCount (1, parsed.Tag!.AlbumArtists); + Assert.AreEqual ("A", parsed.Tag.AlbumArtists[0]); + Assert.AreEqual ("A", parsed.Tag.AlbumArtist); + Assert.IsNull (parsed.Tag.GetValue ("ALBUMARTIST")); + Assert.IsNull (parsed.Tag.GetValue ("AlbumArtist")); + + var singular = new ApeTag (); + singular.SetValue ("Album Artist", "Ada\0Bea"); + singular.SetValue ("ALBUMARTIST", "Cara\0Dan"); + singular.AlbumArtist = "A"; + Assert.AreEqual ("A", singular.AlbumArtist); + Assert.HasCount (1, singular.AlbumArtists); + Assert.IsNull (singular.GetValue ("ALBUMARTIST")); + Assert.AreEqual ("A", singular.GetValue ("Album Artist")); + + singular.AlbumArtist = null; + Assert.IsNull (singular.AlbumArtist); + Assert.HasCount (0, singular.AlbumArtists); + Assert.IsNull (singular.GetValue ("Album Artist")); + Assert.IsNull (singular.GetValue ("ALBUMARTIST")); + Assert.AreEqual (0, singular.ItemCount); + + var cleared = new ApeTag (); + cleared.SetValue ("Album Artist", "Cara\0Dan"); + cleared.SetValue ("ALBUMARTIST", "Ada\0Bea"); + cleared.AlbumArtists = null!; + + var parsedClear = ApeTag.Parse (cleared.Render ().Span); + Assert.IsTrue (parsedClear.IsSuccess, parsedClear.Error); + Assert.HasCount (0, parsedClear.Tag!.AlbumArtists); + Assert.IsNull (parsedClear.Tag.AlbumArtist); + Assert.IsNull (parsedClear.Tag.GetValue ("ALBUMARTIST")); + Assert.IsNull (parsedClear.Tag.GetValue ("Album Artist")); + Assert.AreEqual (0, parsedClear.Tag.ItemCount); + + var empty = new ApeTag (); + empty.SetValue ("ALBUMARTIST", "Ada\0Bea"); + empty.AlbumArtists = []; + Assert.AreEqual (0, empty.ItemCount); + Assert.IsNull (empty.AlbumArtist); + Assert.HasCount (0, empty.AlbumArtists); + + var blanks = new ApeTag (); + blanks.SetValue ("Album Artist", "Ada\0Bea"); + blanks.SetValue ("ALBUMARTIST", "Cara"); + blanks.AlbumArtists = [""]; + Assert.AreEqual (0, blanks.ItemCount); + Assert.IsNull (blanks.GetValue ("ALBUMARTIST")); + Assert.IsNull (blanks.GetValue ("Album Artist")); + } + + [TestMethod] + public void TextList_EmptyPartsAndNonText_AreNotNames () + { + var split = new ApeTag (); + split.SetValue ("Artist", "A\0\0B"); + Assert.AreEqual ("A", split.Artist); + Assert.HasCount (2, split.Performers); + Assert.AreEqual ("B", split.Performers[1]); + + split.Performers = ["A", "", "B"]; + Assert.AreEqual ("A", split.Artist); + Assert.HasCount (2, split.Performers); + Assert.AreEqual ("B", split.Performers[1]); + AssertRaw (split, "Artist", "A\0B"); + + var onlyNuls = new ApeTag (); + onlyNuls.SetValue ("Artist", "\0\0"); + Assert.IsNull (onlyNuls.Artist); + Assert.HasCount (0, onlyNuls.Performers); + + var emptyText = new ApeTag (); + emptyText.SetValue ("Genre", ""); + Assert.IsNull (emptyText.Genre); + Assert.HasCount (0, emptyText.Genres); + + var cleared = new ApeTag { Performers = ["A", "B"], Composers = ["Cara", "Dan"] }; + cleared.Performers = null!; + cleared.Composers = []; + Assert.IsNull (cleared.Artist); + Assert.IsNull (cleared.GetValue ("Artist")); + Assert.IsNull (cleared.Composer); + Assert.IsNull (cleared.GetValue ("Composer")); + Assert.HasCount (0, cleared.Performers); + Assert.HasCount (0, cleared.Composers); + + var binary = new ApeTag (); + binary.SetBinaryItem ("Artist", "a.jpg", [0x01]); + Assert.IsNull (binary.Artist); + Assert.HasCount (0, binary.Performers); + } + static void AssertRaw (ApeTag tag, string key, string expected) { var raw = RawText (tag, key); diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs index 5a3f406e..53110d97 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs @@ -2,9 +2,11 @@ // Licensed under the MIT License. See LICENSE file in the project root for full license information. using TagLibSharp2.Ape; +using TagLibSharp2.Asf; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Mp4; using TagLibSharp2.Xiph; namespace TagLibSharp2.Tests.Core; @@ -323,6 +325,86 @@ public void CopyTo_Id3v2ToApe_KeepsAlbumArtistsAndComposers () Assert.AreEqual ("Soul", round.Genres[1]); } + [TestMethod] + public void CopyTo_ApeToId3_KeepsEveryNameAndBasicKeepsTheFirst () + { + var source = new ApeTag { + Performers = ["A", "B"], + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Genres = ["Jazz", "Soul"] + }; + + Assert.AreEqual ("A", source.Artist); + Assert.AreEqual ("Ada", source.AlbumArtist); + Assert.AreEqual ("Cara", source.Composer); + Assert.AreEqual ("Jazz", source.Genre); + Assert.HasCount (2, source.Performers); + Assert.AreEqual ("B", source.Performers[1]); + + var target = new Id3v2Tag (); + source.CopyTo (target); + + Assert.HasCount (2, target.Performers); + Assert.AreEqual ("A", target.Performers[0]); + Assert.AreEqual ("B", target.Performers[1]); + Assert.AreEqual ("A", target.Artist); + Assert.HasCount (2, target.AlbumArtists); + Assert.AreEqual ("Ada", target.AlbumArtists[0]); + Assert.AreEqual ("Bea", target.AlbumArtists[1]); + Assert.HasCount (2, target.Composers); + Assert.AreEqual ("Cara", target.Composers[0]); + Assert.AreEqual ("Dan", target.Composers[1]); + Assert.HasCount (2, target.Genres); + Assert.AreEqual ("Jazz", target.Genres[0]); + Assert.AreEqual ("Soul", target.Genres[1]); + Assert.AreEqual ("Jazz", target.Genre); + + var basic = new Id3v2Tag (); + source.CopyTo (basic, TagCopyOptions.Basic); + Assert.AreEqual ("A", basic.Artist); + Assert.AreEqual ("Jazz", basic.Genre); + Assert.HasCount (1, basic.Performers); + Assert.AreEqual ("A", basic.Performers[0]); + Assert.IsNull (basic.AlbumArtist); + Assert.IsNull (basic.Composer); + } + + [TestMethod] + public void CopyTo_ApeToMp4AndAsf_KeepsOnlyTheFirstName () + { + var source = new ApeTag { + Performers = ["A", "B"], + AlbumArtists = ["Ada", "Bea"], + Composers = ["Cara", "Dan"], + Genres = ["Jazz", "Soul"] + }; + + var mp4 = new Mp4Tag (); + source.CopyTo (mp4); + Assert.AreEqual ("A", mp4.Artist); + Assert.HasCount (1, mp4.Performers); + Assert.AreEqual ("A", mp4.Performers[0]); + Assert.AreEqual ("Ada", mp4.AlbumArtist); + Assert.HasCount (1, mp4.AlbumArtists); + Assert.AreEqual ("Cara", mp4.Composer); + Assert.HasCount (1, mp4.Composers); + Assert.AreEqual ("Jazz", mp4.Genre); + Assert.HasCount (1, mp4.Genres); + + var asf = new AsfTag (); + source.CopyTo (asf); + Assert.AreEqual ("A", asf.Artist); + Assert.HasCount (1, asf.Performers); + Assert.AreEqual ("A", asf.Performers[0]); + Assert.AreEqual ("Ada", asf.AlbumArtist); + Assert.HasCount (1, asf.AlbumArtists); + Assert.AreEqual ("Cara", asf.Composer); + Assert.HasCount (1, asf.Composers); + Assert.AreEqual ("Jazz", asf.Genre); + Assert.HasCount (1, asf.Genres); + } + [TestMethod] public void CopyTo_CopiesCompilationFlag () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs index 62c0064d..3862cc59 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -440,6 +440,193 @@ public void CatalogNumber_EmbeddedNul_ReturnsFirstValue () Assert.IsNull (tag.GetUserText ("MISSING")); } + [TestMethod] + public void Title_Utf16OddLengthAndRepeatedTerminator_DropsOnlyTerminatorUnits () + { + using var oddAndNul = new BinaryDataBuilder (); + oddAndNul.Add ((byte)TextEncodingType.Utf16WithBom); + oddAndNul.Add (0xFF, 0xFE); + oddAndNul.Add (0x41, 0x00); + oddAndNul.Add (0, 0); + oddAndNul.Add (0x00); + + var kept = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", oddAndNul.ToBinaryData ().ToArray ()); + Assert.AreEqual ("A", kept.Title); + Assert.AreEqual ("A", kept.Frames[0].Text); + Assert.HasCount (1, kept.GetTextFrameValues ("TIT2")); + Assert.AreEqual ("A", kept.GetTextFrameValues ("TIT2")[0]); + + using var repeated = new BinaryDataBuilder (); + repeated.Add ((byte)TextEncodingType.Utf16WithBom); + repeated.Add (0xFF, 0xFE); + repeated.Add (0x41, 0x00); + repeated.Add (0, 0); + repeated.Add (0, 0); + + var once = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", repeated.ToBinaryData ().ToArray ()); + Assert.AreEqual ("A", once.Title); + Assert.AreEqual ("A", once.Frames[0].Text); + Assert.HasCount (1, once.GetTextFrameValues ("TIT2")); + + using var onlyOdd = new BinaryDataBuilder (); + onlyOdd.Add ((byte)TextEncodingType.Utf16WithBom); + onlyOdd.Add (0x41); + + var dropped = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", onlyOdd.ToBinaryData ().ToArray ()); + Assert.AreEqual ("", dropped.Title); + Assert.AreEqual ("", dropped.Frames[0].Text); + Assert.HasCount (0, dropped.GetTextFrameValues ("TIT2")); + + using var beOdd = new BinaryDataBuilder (); + beOdd.Add ((byte)TextEncodingType.Utf16BE); + beOdd.Add (0x00, 0x41); + beOdd.Add (0x00, 0x42); + beOdd.Add (0x00); + + var be = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", beOdd.ToBinaryData ().ToArray ()); + Assert.AreEqual ("AB", be.Title); + Assert.AreEqual ("AB", be.Frames[0].Text); + } + + [TestMethod] + public void Title_Utf16EmptyBom_IsAnEmptyString () + { + using var little = new BinaryDataBuilder (); + little.Add ((byte)TextEncodingType.Utf16WithBom); + little.Add (0xFF, 0xFE); + + var le = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", little.ToBinaryData ().ToArray ()); + Assert.AreEqual ("", le.Title); + Assert.AreEqual ("", le.Frames[0].Text); + Assert.AreEqual (-1, le.Frames[0].Text.IndexOf ('\uFEFF')); + Assert.HasCount (0, le.GetTextFrameValues ("TIT2")); + + using var big = new BinaryDataBuilder (); + big.Add ((byte)TextEncodingType.Utf16WithBom); + big.Add (0xFE, 0xFF); + + var be = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", big.ToBinaryData ().ToArray ()); + Assert.AreEqual ("", be.Title); + Assert.AreEqual ("", be.Frames[0].Text); + Assert.AreEqual (-1, be.Frames[0].Text.IndexOf ('\uFEFF')); + + using var onlyTerminator = new BinaryDataBuilder (); + onlyTerminator.Add ((byte)TextEncodingType.Utf16WithBom); + onlyTerminator.Add (0, 0); + + var trimmed = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", onlyTerminator.ToBinaryData ().ToArray ()); + Assert.AreEqual ("", trimmed.Title); + Assert.AreEqual ("", trimmed.Frames[0].Text); + } + + [TestMethod] + public void Performers_Utf16WithoutBom_KeepsBothNames () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (Encoding.Unicode.GetBytes ("Alice\0Bob")); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("Alice\0Bob", tag.Frames[0].Text); + Assert.AreEqual ("Alice", tag.Artist); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("Alice", tag.Performers[0]); + Assert.AreEqual ("Bob", tag.Performers[1]); + } + + [TestMethod] + public void Performers_Utf16LeadingNul_FirstValueIsEmpty () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0, 0); + builder.Add (0x62, 0x00); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("\0b", tag.Frames[0].Text); + Assert.AreEqual ("", tag.GetTextFrame ("TPE1")); + Assert.AreEqual ("", tag.Artist); + var values = tag.GetTextFrameValues ("TPE1"); + Assert.HasCount (1, values); + Assert.AreEqual ("b", values[0]); + Assert.HasCount (1, tag.Performers); + Assert.AreEqual ("b", tag.Performers[0]); + } + + [TestMethod] + public void Performers_Utf16EmptyBomBetweenNames_SkipsThatValue () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (0x61, 0x00); + builder.Add (0, 0); + builder.Add (0xFF, 0xFE); + builder.Add (0, 0); + builder.Add (0x62, 0x00); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("a\0\0b", tag.Frames[0].Text); + Assert.AreEqual (-1, tag.Frames[0].Text.IndexOf ('\uFEFF')); + Assert.AreEqual ("a", tag.GetTextFrame ("TPE1")); + Assert.AreEqual ("a", tag.Artist); + var values = tag.GetTextFrameValues ("TPE1"); + Assert.HasCount (2, values); + Assert.AreEqual ("a", values[0]); + Assert.AreEqual ("b", values[1]); + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("b", tag.Performers[1]); + } + + [TestMethod] + public void Comment_Utf16OddLength_KeepsTheLastCharacterAndEndsAtTheNul () + { + using var odd = new BinaryDataBuilder (); + odd.Add ((byte)TextEncodingType.Utf16WithBom); + odd.Add ("eng"u8); + odd.Add (0xFF, 0xFE); + odd.Add (0, 0); + odd.Add (0xFF, 0xFE); + odd.Add (0x41, 0x00); + odd.Add (0x42, 0x00); + odd.Add (0x00); + + var kept = CommentFrame.Read (odd.ToBinaryData ().Span, Id3v2Version.V24); + Assert.IsTrue (kept.IsSuccess, kept.Error); + Assert.AreEqual ("AB", kept.Frame!.Text); + AssertNoNul (kept.Frame.Text); + + using var split = new BinaryDataBuilder (); + split.Add ((byte)TextEncodingType.Utf16WithBom); + split.Add ("eng"u8); + split.Add (0xFF, 0xFE); + split.Add (0, 0); + split.Add (0xFF, 0xFE); + split.Add (Encoding.Unicode.GetBytes ("ye")); + split.Add (0, 0); + split.Add (Encoding.Unicode.GetBytes ("pa")); + split.Add (0x00); + + var ended = CommentFrame.Read (split.ToBinaryData ().Span, Id3v2Version.V24); + Assert.IsTrue (ended.IsSuccess, ended.Error); + Assert.AreEqual ("ye", ended.Frame!.Text); + AssertNoNul (ended.Frame.Text); + + using var terminator = new BinaryDataBuilder (); + terminator.Add ((byte)TextEncodingType.Utf16WithBom); + terminator.Add ("eng"u8); + terminator.Add (0xFF, 0xFE); + terminator.Add (0, 0); + terminator.Add (0, 0); + + var empty = CommentFrame.Read (terminator.ToBinaryData ().Span, Id3v2Version.V24); + Assert.IsTrue (empty.IsSuccess, empty.Error); + Assert.AreEqual ("", empty.Frame!.Text); + } + static byte[] UserText (string description, string value) { using var builder = new BinaryDataBuilder (); From 033b365d4c885b5a9cfb35daaf64d26d2da3f954 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 20 Nov 2026 23:52:09 -0700 Subject: [PATCH 05/29] fix: Keep fallback tag fields in step with the value that is read Setting or clearing an APE year also removes Date, so an old date cannot come back. A locator or an empty text item reads the same string for a name as it does for a title. A Vorbis original-release write also removes ORIGINALYEAR, and a movement write also removes MOVEMENTNAME. The changelog records that an APE artist is the first name, and that a Basic copy into MP4, ASF, RIFF INFO, or ID3v1 keeps that first name. --- CHANGELOG.md | 6 ++ src/TagLibSharp2/Ape/ApeTag.cs | 38 ++++++++-- src/TagLibSharp2/Xiph/VorbisComment.cs | 14 +++- tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs | 69 ++++++++++++++++++- .../VorbisCommentExtendedMetadataTests.cs | 33 +++++++++ 5 files changed, 150 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec1c69d3..5d12d5b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska: `DiscNumber` and `TotalDiscs` are read and written (#130). Setting or clearing a track or disc number or total leaves the other three as they were, including a total held in a `4/12` or `2/3` slash, and a clear removes every element the getter could still read. - Matroska: every rendered Tag has a `Targets` element. An omitted `TargetTypeValue` is not written back as 50, and an empty one reads as the default 50. A Tag that a clear leaves with no SimpleTag is not written (RFC 9559 section 5.1.8.1.2); one that was already empty when read is kept. +### 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. +- Setting or clearing an APE year also removes `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. +- Setting or clearing a Vorbis original release date also removes `ORIGINALYEAR`. Setting or clearing a movement also removes `MOVEMENTNAME`. + ## [0.6.0] - 2026-01-05 ### Breaking Changes diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index c8e83eb5..af6b61e8 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -182,7 +182,7 @@ public override string? Title { /// The first performer. Other names stay on ; a comma does not join them. /// public override string? Artist { - get => FirstName (Performers); + get => ReadFirstName (Keys.Artist); set => SetOrRemove (Keys.Artist, value); } @@ -211,7 +211,7 @@ public override string? Album { /// Setting or clearing removes both items and stores the name in "Album Artist". /// public override string? AlbumArtist { - get => FirstName (AlbumArtists); + get => ReadFirstName (Keys.AlbumArtist, Keys.AlbumArtistAlias); set => SetOrRemove (Keys.AlbumArtist, value, Keys.AlbumArtistAlias); } @@ -233,7 +233,7 @@ public override string[] AlbumArtists { /// public override string? Year { get => GetValue (Keys.Year) ?? GetValue (Keys.Date); - set => SetOrRemove (Keys.Year, value); + set => SetOrRemove (Keys.Year, value, Keys.Date); } /// @@ -247,7 +247,7 @@ public override string? Comment { /// The first genre. Other names stay on ; a comma does not join them. /// public override string? Genre { - get => FirstName (Genres); + get => ReadFirstName (Keys.Genre); set => SetOrRemove (Keys.Genre, value); } @@ -341,7 +341,7 @@ public override string? DiscSubtitle { /// The first composer. Other names stay on ; a comma does not join them. /// public override string? Composer { - get => FirstName (Composers); + get => ReadFirstName (Keys.Composer); set => SetOrRemove (Keys.Composer, value); } @@ -809,7 +809,33 @@ string[] GetTextList (string key) return result.Count == 0 ? [] : result.ToArray (); } - static string? FirstName (string[] names) => names.Length == 0 ? null : names[0]; + /// + /// The first text name, or the same string returns for a + /// locator, an empty text item, or a binary item. + /// + string? ReadFirstName (string key, string? alias = null) + { + var primary = ReadListedOrRaw (key); + if (!string.IsNullOrEmpty (primary) || alias is null) + return primary; + + var secondary = ReadListedOrRaw (alias); + return string.IsNullOrEmpty (secondary) ? primary ?? secondary : secondary; + } + + string? ReadListedOrRaw (string key) + { + if (!_items.TryGetValue (key, out var item)) + return null; + + if (item.ItemType == ApeItemType.Text) { + var names = GetTextList (key); + if (names.Length > 0) + return names[0]; + } + + return item.ValueAsString; + } /// /// Stores names in one item. A single name has no extra NUL. diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 54eaf0f7..b71d4b15 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -130,7 +130,7 @@ public override string? Year { /// public override string? OriginalReleaseDate { get => GetValue ("ORIGINALDATE") ?? GetValue ("ORIGINALYEAR"); - set => SetValue ("ORIGINALDATE", value); + set => SetValueRemoving ("ORIGINALDATE", value, "ORIGINALYEAR"); } /// @@ -272,7 +272,7 @@ public override string? Work { /// public override string? Movement { get => GetValue ("MOVEMENT") ?? GetValue ("MOVEMENTNAME"); - set => SetValue ("MOVEMENT", value); + set => SetValueRemoving ("MOVEMENT", value, "MOVEMENTNAME"); } /// @@ -912,6 +912,16 @@ public void SetValue (string name, string? value) AddField (name, value); } + /// + /// Writes and removes , + /// so a getter that falls back to the second field cannot revive a stale value. + /// + void SetValueRemoving (string name, string? value, string alsoRemove) + { + RemoveAll (alsoRemove); + SetValue (name, value); + } + /// /// Removes all fields with the specified name. /// diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index 855fc44b..ac429214 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs @@ -1833,12 +1833,12 @@ public void TextList_EmptyPartsAndNonText_AreNotNames () var onlyNuls = new ApeTag (); onlyNuls.SetValue ("Artist", "\0\0"); - Assert.IsNull (onlyNuls.Artist); + Assert.AreEqual ("", onlyNuls.Artist); Assert.HasCount (0, onlyNuls.Performers); var emptyText = new ApeTag (); emptyText.SetValue ("Genre", ""); - Assert.IsNull (emptyText.Genre); + Assert.AreEqual ("", emptyText.Genre); Assert.HasCount (0, emptyText.Genres); var cleared = new ApeTag { Performers = ["A", "B"], Composers = ["Cara", "Dan"] }; @@ -1857,6 +1857,71 @@ public void TextList_EmptyPartsAndNonText_AreNotNames () Assert.HasCount (0, binary.Performers); } + [TestMethod] + public void Year_SetAndClear_RemovesDate () + { + var replaced = new ApeTag (); + replaced.SetValue ("Date", "1999"); + replaced.Year = "2001"; + + Assert.AreEqual ("2001", replaced.Year); + Assert.AreEqual ("2001", replaced.GetValue ("Year")); + Assert.IsNull (replaced.GetValue ("Date")); + + replaced.Year = null; + Assert.IsNull (replaced.Year); + Assert.IsNull (replaced.GetValue ("Year")); + Assert.IsNull (replaced.GetValue ("Date")); + + var cleared = new ApeTag (); + cleared.SetValue ("Date", "1999-05-01"); + cleared.Year = null; + Assert.IsNull (cleared.Year); + Assert.IsNull (cleared.GetValue ("Date")); + } + + [TestMethod] + public void LocatorName_ReadsTheSameStringAsTitle () + { + const string url = "http://example.com/name"; + var title = TagWith (CreateExternalLocatorItem ("Title", url)); + var artist = TagWith (CreateExternalLocatorItem ("Artist", url)); + var albumArtist = TagWith (CreateExternalLocatorItem ("Album Artist", url)); + var composer = TagWith (CreateExternalLocatorItem ("Composer", url)); + var genre = TagWith (CreateExternalLocatorItem ("Genre", url)); + + Assert.AreEqual (url, title.Title); + Assert.AreEqual (title.Title, artist.Artist); + Assert.AreEqual (url, albumArtist.AlbumArtist); + Assert.AreEqual (url, composer.Composer); + Assert.AreEqual (url, genre.Genre); + Assert.HasCount (0, artist.Performers); + + var emptyTitle = new ApeTag (); + emptyTitle.SetValue ("Title", ""); + var emptyArtist = new ApeTag (); + emptyArtist.SetValue ("Artist", ""); + Assert.AreEqual (emptyTitle.Title, emptyArtist.Artist); + + var binaryTitle = new ApeTag (); + binaryTitle.SetBinaryItem ("Title", "t.jpg", [0x01]); + var binaryArtist = new ApeTag (); + binaryArtist.SetBinaryItem ("Artist", "a.jpg", [0x01]); + Assert.IsNull (binaryTitle.Title); + Assert.IsNull (binaryArtist.Artist); + } + + static ApeTag TagWith (byte[] item) + { + var footer = CreateValidFooter (2000, (uint)(item.Length + 32), 1, 0); + var data = new byte[item.Length + footer.Length]; + item.CopyTo (data, 0); + footer.CopyTo (data, item.Length); + var parsed = ApeTag.Parse (data); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + return parsed.Tag!; + } + static void AssertRaw (ApeTag tag, string key, string expected) { var raw = RawText (tag, key); diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs index dcd4b269..3b42c37f 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -355,6 +355,39 @@ public void OriginalReleaseDate_PrefersOriginalDateOverYear () Assert.AreEqual ("1969-09-26", comment.OriginalReleaseDate); } + [TestMethod] + public void OriginalReleaseDate_SetAndClear_RemovesOriginalYear () + { + var comment = new VorbisComment ("test"); + comment.AddField ("ORIGINALYEAR", "1969"); + comment.OriginalReleaseDate = "2001-01-01"; + + Assert.AreEqual ("2001-01-01", comment.OriginalReleaseDate); + Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + + comment.AddField ("ORIGINALYEAR", "1969"); + comment.OriginalReleaseDate = null; + Assert.IsNull (comment.OriginalReleaseDate); + Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + Assert.HasCount (0, comment.GetValues ("ORIGINALDATE")); + } + + [TestMethod] + public void Movement_SetAndClear_RemovesMovementName () + { + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.Movement = "Allegro"; + + Assert.AreEqual ("Allegro", comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + + comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.Movement = null; + Assert.IsNull (comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + } + [TestMethod] public void OriginalReleaseDate_SetNull_ClearsField () { From 513a15f9de71e7df6abff3994256052ba4e7acd8 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 00:21:34 -0700 Subject: [PATCH 06/29] fix: Prefer a text album artist over a locator in the other item AlbumArtist returned a locator URL as soon as Album Artist had one, while AlbumArtists skipped that non-text item and read ALBUMARTIST. A text name on either key is the first album artist. A locator is used only when neither key has text. --- src/TagLibSharp2/Ape/ApeTag.cs | 21 ++++++++++-- tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs | 37 ++++++++++++++++++--- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index af6b61e8..5348b6b1 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -207,7 +207,8 @@ public override string? Album { /// Gets or sets the album artist. /// /// - /// The first album artist. Reads "Album Artist", or "ALBUMARTIST" when that item is absent. + /// The first album artist. A text name on "Album Artist" wins, then a text name on + /// "ALBUMARTIST". A locator is used only when neither item has text. /// Setting or clearing removes both items and stores the name in "Album Artist". /// public override string? AlbumArtist { @@ -810,11 +811,19 @@ string[] GetTextList (string key) } /// - /// The first text name, or the same string returns for a - /// locator, an empty text item, or a binary item. + /// The first text name on , or on + /// when the primary item has none. A locator, an empty text item, or a binary + /// item is used only when neither key has a text name, and then it matches + /// . /// string? ReadFirstName (string key, string? alias = null) { + var text = FirstTextName (key); + if (text is null && alias is not null) + text = FirstTextName (alias); + if (text is not null) + return text; + var primary = ReadListedOrRaw (key); if (!string.IsNullOrEmpty (primary) || alias is null) return primary; @@ -823,6 +832,12 @@ string[] GetTextList (string key) return string.IsNullOrEmpty (secondary) ? primary ?? secondary : secondary; } + string? FirstTextName (string key) + { + var names = GetTextList (key); + return names.Length == 0 ? null : names[0]; + } + string? ReadListedOrRaw (string key) { if (!_items.TryGetValue (key, out var item)) diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index ac429214..34da8690 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs @@ -1911,12 +1911,39 @@ public void LocatorName_ReadsTheSameStringAsTitle () Assert.IsNull (binaryArtist.Artist); } - static ApeTag TagWith (byte[] item) + [TestMethod] + public void AlbumArtist_LocatorDoesNotHideAliasText () { - var footer = CreateValidFooter (2000, (uint)(item.Length + 32), 1, 0); - var data = new byte[item.Length + footer.Length]; - item.CopyTo (data, 0); - footer.CopyTo (data, item.Length); + const string url = "http://example.com/name"; + var names = new[] { "Ada", "Bea" }; + var hidden = TagWith ( + CreateExternalLocatorItem ("Album Artist", url), + CreateTextItem ("ALBUMARTIST", "Ada\0Bea")); + + Assert.AreEqual ("Ada", hidden.AlbumArtist); + CollectionAssert.AreEqual (names, hidden.AlbumArtists); + + var onlyLocator = TagWith (CreateExternalLocatorItem ("Album Artist", url)); + Assert.AreEqual (url, onlyLocator.AlbumArtist); + Assert.HasCount (0, onlyLocator.AlbumArtists); + + var textWins = TagWith ( + CreateTextItem ("Album Artist", "Ada\0Bea"), + CreateExternalLocatorItem ("ALBUMARTIST", url)); + Assert.AreEqual ("Ada", textWins.AlbumArtist); + CollectionAssert.AreEqual (names, textWins.AlbumArtists); + } + + static ApeTag TagWith (params byte[][] items) + { + using var body = new MemoryStream (); + foreach (var item in items) + body.Write (item); + var itemsData = body.ToArray (); + var footer = CreateValidFooter (2000, (uint)(itemsData.Length + 32), (uint)items.Length, 0); + var data = new byte[itemsData.Length + footer.Length]; + itemsData.CopyTo (data, 0); + footer.CopyTo (data, itemsData.Length); var parsed = ApeTag.Parse (data); Assert.IsTrue (parsed.IsSuccess, parsed.Error); return parsed.Tag!; From ae6e4be6d5fe83aac9577d4426cccee86ac9f4d3 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 00:45:03 -0700 Subject: [PATCH 07/29] fix: Clear every ID3 frame a date or movement getter can read Original release date reads TDOR or TORY, but a write only replaced one of them, so clearing the property brought the other frame back. Movement reads MVNM or MVIN before the TXXX field, so a write to TXXX left the Apple frame in front. A write now updates both, and a clear removes both. Setting one half of MVIN keeps the other half. --- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 58 ++++++++++++++++--- .../Id3/Id3v2/Id3v2TagClassicalMusicTests.cs | 35 +++++++++++ .../Id3v2/Id3v2TagExtendedMetadataTests.cs | 24 ++++++++ 3 files changed, 109 insertions(+), 8 deletions(-) diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index d974c096..3b443ac6 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -248,6 +248,7 @@ private protected override string? CopyableDate { /// In ID3v2.4, uses the TDOR (Original Release Time) frame. /// In ID3v2.3, uses the TORY (Original Release Year) frame. /// When reading, falls back to the other version's frame if the primary is not found. + /// Setting or clearing removes both frames, then writes the frame for this version. /// public override string? OriginalReleaseDate { get { @@ -264,7 +265,12 @@ public override string? OriginalReleaseDate { return NormalizeYear (tory); return NormalizeReleaseTimestamp (GetTextFrame ("TDOR")); } - set => SetDateFrame (Version == 4 ? "TDOR" : "TORY", value, Version == 4, keepMatchingYear: false); + set => SetDateFrame ( + Version == 4 ? "TDOR" : "TORY", + value, + Version == 4, + keepMatchingYear: false, + alsoClear: Version == 4 ? "TORY" : "TDOR"); } /// @@ -991,17 +997,20 @@ public override string? Work { /// /// /// Reads from Apple's MVNM frame first, then falls back to TXXX:MOVEMENT. - /// Writes to TXXX:MOVEMENT for compatibility with non-Apple software. + /// A write stores the same value in both, and a clear removes both. /// public override string? Movement { get => GetTextFrame ("MVNM") ?? GetUserText ("MOVEMENT"); - set => SetUserText ("MOVEMENT", value); + set { + SetTextFrame ("MVNM", value); + SetUserText ("MOVEMENT", value); + } } /// /// /// Reads from Apple's MVIN frame first (index part), then falls back to TXXX:MOVEMENTNUMBER. - /// Writes to TXXX:MOVEMENTNUMBER for compatibility with non-Apple software. + /// A write updates MVIN and the TXXX field together so the other half of MVIN is kept. /// public override uint? MovementNumber { get { @@ -1016,13 +1025,19 @@ public override uint? MovementNumber { var value = GetUserText ("MOVEMENTNUMBER"); return uint.TryParse (value, out var result) ? result : null; } - set => SetUserText ("MOVEMENTNUMBER", value?.ToString (System.Globalization.CultureInfo.InvariantCulture)); + set { + var total = MovementTotal; + SetUserText ("MOVEMENTNUMBER", value?.ToString (CultureInfo.InvariantCulture)); + if (total is not null) + SetUserText ("MOVEMENTTOTAL", total.Value.ToString (CultureInfo.InvariantCulture)); + WriteMovementIndex (value, total); + } } /// /// /// Reads from Apple's MVIN frame first (total part), then falls back to TXXX:MOVEMENTTOTAL. - /// Writes to TXXX:MOVEMENTTOTAL for compatibility with non-Apple software. + /// A write updates MVIN and the TXXX field together so the index half of MVIN is kept. /// public override uint? MovementTotal { get { @@ -1037,7 +1052,30 @@ public override uint? MovementTotal { var value = GetUserText ("MOVEMENTTOTAL"); return uint.TryParse (value, out var result) ? result : null; } - set => SetUserText ("MOVEMENTTOTAL", value?.ToString (System.Globalization.CultureInfo.InvariantCulture)); + set { + var number = MovementNumber; + SetUserText ("MOVEMENTTOTAL", value?.ToString (CultureInfo.InvariantCulture)); + if (number is not null) + SetUserText ("MOVEMENTNUMBER", number.Value.ToString (CultureInfo.InvariantCulture)); + WriteMovementIndex (number, value); + } + } + + /// + /// Stores the movement index in MVIN. A null index removes MVIN; the total then lives + /// only in TXXX:MOVEMENTTOTAL, which the getter already reads. + /// + void WriteMovementIndex (uint? number, uint? total) + { + if (number is null) { + SetTextFrame ("MVIN", null); + return; + } + + var index = number.Value.ToString (CultureInfo.InvariantCulture); + SetTextFrame ("MVIN", total is null + ? index + : index + "/" + total.Value.ToString (CultureInfo.InvariantCulture)); } /// @@ -1664,10 +1702,12 @@ public override string[] Genres { /// leaves the timestamp in place. An invalid value also leaves the existing frame. /// Null or empty still clears it. /// - void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatchingYear) + void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatchingYear, string? alsoClear = null) { if (value is null || value.Length == 0) { SetTextFrame (frameId, null); + if (alsoClear is not null) + SetTextFrame (alsoClear, null); return; } @@ -1681,6 +1721,8 @@ void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatch if (normalized is null) return; + if (alsoClear is not null) + SetTextFrame (alsoClear, null); SetTextFrame (frameId, normalized); } diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs index 454cb9a2..a3258332 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs @@ -134,6 +134,41 @@ public void Work_SetNull_ClearsValue () Assert.IsNull (tag.Work); } + [TestMethod] + public void Movement_SetAndClear_ReplacesAppleFrames () + { + var named = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("MVNM", "Scherzo", TestConstants.Id3v2.Version3)); + Assert.IsTrue (named.IsSuccess, named.Error); + named.Tag!.Movement = "Allegro"; + Assert.AreEqual ("Allegro", named.Tag.Movement); + Assert.AreEqual ("Allegro", named.Tag.GetTextFrame ("MVNM")); + Assert.AreEqual ("Allegro", named.Tag.GetUserText ("MOVEMENT")); + + named.Tag.Movement = null; + Assert.IsNull (named.Tag.Movement); + Assert.IsNull (named.Tag.GetTextFrame ("MVNM")); + Assert.IsNull (named.Tag.GetUserText ("MOVEMENT")); + + var indexed = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("MVIN", "1/4", TestConstants.Id3v2.Version3)); + Assert.IsTrue (indexed.IsSuccess, indexed.Error); + indexed.Tag!.MovementNumber = 9; + Assert.AreEqual (9u, indexed.Tag.MovementNumber); + Assert.AreEqual (4u, indexed.Tag.MovementTotal); + + indexed.Tag.MovementTotal = 9; + Assert.AreEqual (9u, indexed.Tag.MovementNumber); + Assert.AreEqual (9u, indexed.Tag.MovementTotal); + + indexed.Tag.MovementNumber = null; + Assert.IsNull (indexed.Tag.MovementNumber); + Assert.AreEqual (9u, indexed.Tag.MovementTotal); + + indexed.Tag.MovementTotal = null; + Assert.IsNull (indexed.Tag.MovementNumber); + Assert.IsNull (indexed.Tag.MovementTotal); + Assert.IsNull (indexed.Tag.GetTextFrame ("MVIN")); + } + [TestMethod] public void Movement_SetNull_ClearsValue () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs index acda6d6a..89792ccd 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagExtendedMetadataTests.cs @@ -493,6 +493,30 @@ public void OriginalReleaseDate_InvalidValue_LeavesExistingFrame () Assert.AreEqual ("1969", v23.GetTextFrame ("TORY")); } + [TestMethod] + public void OriginalReleaseDate_SetAndClear_RemovesTheOtherVersionFrame () + { + var v24 = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("TORY", "1999", TestConstants.Id3v2.Version4)); + Assert.IsTrue (v24.IsSuccess, v24.Error); + v24.Tag!.OriginalReleaseDate = "2001-01-01"; + Assert.AreEqual ("2001-01-01", v24.Tag.OriginalReleaseDate); + Assert.AreEqual ("2001-01-01", v24.Tag.GetTextFrame ("TDOR")); + Assert.IsNull (v24.Tag.GetTextFrame ("TORY")); + + v24.Tag.SetTextFrameValues ("TORY", ["1999"]); + v24.Tag.OriginalReleaseDate = null; + Assert.IsNull (v24.Tag.OriginalReleaseDate); + Assert.IsNull (v24.Tag.GetTextFrame ("TDOR")); + Assert.IsNull (v24.Tag.GetTextFrame ("TORY")); + + var v23 = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("TDOR", "1999-05-01", TestConstants.Id3v2.Version3)); + Assert.IsTrue (v23.IsSuccess, v23.Error); + v23.Tag!.OriginalReleaseDate = null; + Assert.IsNull (v23.Tag.OriginalReleaseDate); + Assert.IsNull (v23.Tag.GetTextFrame ("TDOR")); + Assert.IsNull (v23.Tag.GetTextFrame ("TORY")); + } + [TestMethod] public void OriginalReleaseDate_SetNull_ClearsField () { From 7de58c540a71bd37516c63fe935f1b212d7d55d2 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 10:56:37 -0700 Subject: [PATCH 08/29] test: Pin the MVIN half a movement number or total clear keeps Clearing the number from MVIN "1/4" alone must keep the total 4, which only the TXXX:MOVEMENTTOTAL rewrite preserves once MVIN is removed. The existing step now uses a total that differs from the number, so a swap of the two halves fails. --- .../Id3/Id3v2/Id3v2TagClassicalMusicTests.cs | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs index a3258332..7d400727 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs @@ -155,13 +155,14 @@ public void Movement_SetAndClear_ReplacesAppleFrames () Assert.AreEqual (9u, indexed.Tag.MovementNumber); Assert.AreEqual (4u, indexed.Tag.MovementTotal); - indexed.Tag.MovementTotal = 9; + indexed.Tag.MovementTotal = 12; Assert.AreEqual (9u, indexed.Tag.MovementNumber); - Assert.AreEqual (9u, indexed.Tag.MovementTotal); + Assert.AreEqual (12u, indexed.Tag.MovementTotal); + Assert.AreEqual ("9/12", indexed.Tag.GetTextFrame ("MVIN")); indexed.Tag.MovementNumber = null; Assert.IsNull (indexed.Tag.MovementNumber); - Assert.AreEqual (9u, indexed.Tag.MovementTotal); + Assert.AreEqual (12u, indexed.Tag.MovementTotal); indexed.Tag.MovementTotal = null; Assert.IsNull (indexed.Tag.MovementNumber); @@ -169,6 +170,52 @@ public void Movement_SetAndClear_ReplacesAppleFrames () Assert.IsNull (indexed.Tag.GetTextFrame ("MVIN")); } + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void MovementNumber_ClearFromIndexOnly_KeepsTotalFromIndex (byte version) + { + // MVIN alone holds both halves. Clearing the number removes MVIN, so the total + // must be written to TXXX:MOVEMENTTOTAL first or it is lost. + var result = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("MVIN", "1/4", version)); + Assert.IsTrue (result.IsSuccess, result.Error); + var tag = result.Tag!; + Assert.IsNull (tag.GetUserText ("MOVEMENTTOTAL")); + + tag.MovementNumber = null; + + Assert.IsNull (tag.MovementNumber); + Assert.AreEqual (4u, tag.MovementTotal); + Assert.IsNull (tag.GetTextFrame ("MVIN")); + Assert.AreEqual ("4", tag.GetUserText ("MOVEMENTTOTAL")); + + var reparsed = Id3v2Tag.Read (tag.Render ().Span); + Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); + Assert.IsNull (reparsed.Tag!.MovementNumber); + Assert.AreEqual (4u, reparsed.Tag.MovementTotal); + } + + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void MovementTotal_ClearFromIndexOnly_KeepsNumberFromIndex (byte version) + { + var result = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("MVIN", "2/5", version)); + Assert.IsTrue (result.IsSuccess, result.Error); + var tag = result.Tag!; + + tag.MovementTotal = null; + + Assert.AreEqual (2u, tag.MovementNumber); + Assert.IsNull (tag.MovementTotal); + Assert.AreEqual ("2", tag.GetTextFrame ("MVIN")); + + var reparsed = Id3v2Tag.Read (tag.Render ().Span); + Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); + Assert.AreEqual (2u, reparsed.Tag!.MovementNumber); + Assert.IsNull (reparsed.Tag.MovementTotal); + } + [TestMethod] public void Movement_SetNull_ClearsValue () { From e024c56228e39f747bcce054883c2c10216ce0d9 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 11:02:04 -0700 Subject: [PATCH 09/29] fix: Keep the fallback field when a value is written back A Vorbis movement or original release date write removed MOVEMENTNAME or ORIGINALYEAR even when the value was set, not cleared. Picard keeps the movement name in MOVEMENTNAME beside a MOVEMENT number, and the original year in ORIGINALYEAR beside ORIGINALDATE, so an editor writing back the values it showed erased them. An APE year write removed Date in the same way. Now only a clear removes the fallback. Writing back the value already read changes nothing. A new value also replaces an existing fallback: the name in MOVEMENTNAME, the four-digit year in ORIGINALYEAR, and the year in Date. --- src/TagLibSharp2/Ape/ApeTag.cs | 19 ++- src/TagLibSharp2/Xiph/VorbisComment.cs | 51 +++++++- tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs | 30 ++++- .../Xiph/FlacFileRoundTripTests.cs | 32 +++++ .../VorbisCommentExtendedMetadataTests.cs | 123 +++++++++++++++++- 5 files changed, 239 insertions(+), 16 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 5348b6b1..bbc67dd2 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -232,9 +232,26 @@ public override string[] AlbumArtists { #pragma warning restore CA1819 /// + /// + /// Reads "Year", then "Date". Writing back the value already read changes nothing. + /// A new value is written to "Year" and to an existing "Date". Clearing removes both. + /// public override string? Year { get => GetValue (Keys.Year) ?? GetValue (Keys.Date); - set => SetOrRemove (Keys.Year, value, Keys.Date); + set { + if (string.IsNullOrEmpty (value)) { + _items.Remove (Keys.Year); + _items.Remove (Keys.Date); + return; + } + + if (string.Equals (Year, value, StringComparison.Ordinal)) + return; + + SetValue (Keys.Year, value!); + if (_items.ContainsKey (Keys.Date)) + SetValue (Keys.Date, value!); + } } /// diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index b71d4b15..b1a77af3 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -127,10 +127,14 @@ public override string? Year { /// /// /// Uses ORIGINALDATE field. Falls back to ORIGINALYEAR if ORIGINALDATE is not found. + /// Writing back the value already read changes nothing. A new value is written to ORIGINALDATE, + /// and an existing ORIGINALYEAR is rewritten to its four-digit year (MusicBrainz Picard keeps + /// both: https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). + /// Clearing removes both. /// public override string? OriginalReleaseDate { get => GetValue ("ORIGINALDATE") ?? GetValue ("ORIGINALYEAR"); - set => SetValueRemoving ("ORIGINALDATE", value, "ORIGINALYEAR"); + set => SetValueWithFallback ("ORIGINALDATE", value, "ORIGINALYEAR", LeadingYear); } /// @@ -269,10 +273,13 @@ public override string? Work { /// /// /// Uses the MOVEMENT field. Falls back to MOVEMENTNAME for compatibility. + /// Writing back the value already read changes nothing, so a MOVEMENTNAME that Picard or Mp3tag + /// wrote beside a MOVEMENT number is kept. A new value is written to MOVEMENT and to an existing + /// MOVEMENTNAME. Clearing removes both. /// public override string? Movement { get => GetValue ("MOVEMENT") ?? GetValue ("MOVEMENTNAME"); - set => SetValueRemoving ("MOVEMENT", value, "MOVEMENTNAME"); + set => SetValueWithFallback ("MOVEMENT", value, "MOVEMENTNAME", static v => v); } /// @@ -913,13 +920,45 @@ public void SetValue (string name, string? value) } /// - /// Writes and removes , - /// so a getter that falls back to the second field cannot revive a stale value. + /// Sets a field whose getter falls back to . + /// A null or empty value clears the fallback too, so it cannot come back. + /// The value the getter already returns is a no-op, so neither field is lost. + /// Any other value goes to , and to + /// when that field exists and gives a value for it. /// - void SetValueRemoving (string name, string? value, string alsoRemove) + void SetValueWithFallback (string name, string? value, string fallback, Func toFallback) { - RemoveAll (alsoRemove); + if (string.IsNullOrEmpty (value)) { + RemoveAll (fallback); + SetValue (name, value); + return; + } + + var current = GetValue (name) ?? GetValue (fallback); + if (string.Equals (current, value, StringComparison.Ordinal)) + return; + SetValue (name, value); + if (GetValue (fallback) is null) + return; + + var fallbackValue = toFallback (value!); + if (fallbackValue is not null) + SetValue (fallback, fallbackValue); + } + + /// + /// The leading four-digit year of a date such as "1969-09-26", or null when it has none. + /// + static string? LeadingYear (string date) + { + if (date.Length < 4) + return null; + for (var i = 0; i < 4; i++) { + if (date[i] < '0' || date[i] > '9') + return null; + } + return date.Length == 4 || date[4] is < '0' or > '9' ? date.Substring (0, 4) : null; } /// diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index 34da8690..11d510a4 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs @@ -1858,7 +1858,7 @@ public void TextList_EmptyPartsAndNonText_AreNotNames () } [TestMethod] - public void Year_SetAndClear_RemovesDate () + public void Year_Set_RewritesDate_ClearRemovesBoth () { var replaced = new ApeTag (); replaced.SetValue ("Date", "1999"); @@ -1866,7 +1866,7 @@ public void Year_SetAndClear_RemovesDate () Assert.AreEqual ("2001", replaced.Year); Assert.AreEqual ("2001", replaced.GetValue ("Year")); - Assert.IsNull (replaced.GetValue ("Date")); + Assert.AreEqual ("2001", replaced.GetValue ("Date")); replaced.Year = null; Assert.IsNull (replaced.Year); @@ -1875,9 +1875,33 @@ public void Year_SetAndClear_RemovesDate () var cleared = new ApeTag (); cleared.SetValue ("Date", "1999-05-01"); - cleared.Year = null; + cleared.Year = ""; Assert.IsNull (cleared.Year); Assert.IsNull (cleared.GetValue ("Date")); + + var noDate = new ApeTag (); + noDate.Year = "2001"; + Assert.IsNull (noDate.GetValue ("Date")); + } + + [TestMethod] + public void Year_UnchangedWriteBack_KeepsDate () + { + var both = new ApeTag (); + both.SetValue ("Year", "2001"); + both.SetValue ("Date", "2001-05-03"); + both.Year = both.Year; + + var reparsed = ApeTag.Parse (both.Render ().Span); + Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); + Assert.AreEqual ("2001", reparsed.Tag!.GetValue ("Year")); + Assert.AreEqual ("2001-05-03", reparsed.Tag.GetValue ("Date")); + + var dateOnly = new ApeTag (); + dateOnly.SetValue ("Date", "2001-05-03"); + dateOnly.Year = dateOnly.Year; + Assert.AreEqual ("2001-05-03", dateOnly.Year); + Assert.AreEqual ("2001-05-03", dateOnly.GetValue ("Date")); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Xiph/FlacFileRoundTripTests.cs b/tests/TagLibSharp2.Tests/Xiph/FlacFileRoundTripTests.cs index a462e9e4..be075da5 100644 --- a/tests/TagLibSharp2.Tests/Xiph/FlacFileRoundTripTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/FlacFileRoundTripTests.cs @@ -35,6 +35,38 @@ public void MinimalFile_PreservesStructure () Assert.AreEqual ("Test Artist", file2.VorbisComment?.Artist); } + [TestMethod] + public void PicardMovementAndOriginalYear_SurviveUnchangedWriteBack () + { + // An editor that writes back every field it shows must not drop MOVEMENTNAME or + // ORIGINALYEAR, which Picard stores beside MOVEMENT (the number) and ORIGINALDATE. + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Allegro"); + comment.AddField ("MOVEMENT", "2"); + comment.AddField ("MOVEMENTTOTAL", "4"); + comment.AddField ("ORIGINALDATE", "1969-09-26"); + comment.AddField ("ORIGINALYEAR", "1969"); + var seed = FlacFile.Read (TestBuilders.Flac.CreateMinimal ()).File!; + seed.VorbisComment = comment; + var original = seed.Render (TestBuilders.Flac.CreateMinimal ()).ToArray (); + + var file = FlacFile.Read (original).File!; + var vc = file.VorbisComment!; + vc.Movement = vc.Movement; + vc.OriginalReleaseDate = vc.OriginalReleaseDate; + var written = file.Render (original); + + var reread = FlacFile.Read (written.Span); + Assert.IsTrue (reread.IsSuccess, reread.Error); + var after = reread.File!.VorbisComment!; + Assert.AreEqual ("Allegro", after.GetValue ("MOVEMENTNAME")); + Assert.AreEqual ("2", after.GetValue ("MOVEMENT")); + Assert.AreEqual ("4", after.GetValue ("MOVEMENTTOTAL")); + Assert.AreEqual ("1969-09-26", after.GetValue ("ORIGINALDATE")); + Assert.AreEqual ("1969", after.GetValue ("ORIGINALYEAR")); + CollectionAssert.AreEqual (original, written.ToArray ()); + } + [TestMethod] public void AllMetadataFields_SurviveRoundTrip () { diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs index 3b42c37f..c9833e79 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -355,17 +355,29 @@ public void OriginalReleaseDate_PrefersOriginalDateOverYear () Assert.AreEqual ("1969-09-26", comment.OriginalReleaseDate); } + static void AssertSingle (VorbisComment comment, string name, string expected) + { + var values = comment.GetValues (name); + Assert.HasCount (1, values, name); + Assert.AreEqual (expected, values[0], name); + } + [TestMethod] - public void OriginalReleaseDate_SetAndClear_RemovesOriginalYear () + public void OriginalReleaseDate_Set_RewritesOriginalYear_ClearRemovesBoth () { var comment = new VorbisComment ("test"); comment.AddField ("ORIGINALYEAR", "1969"); comment.OriginalReleaseDate = "2001-01-01"; Assert.AreEqual ("2001-01-01", comment.OriginalReleaseDate); - Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + AssertSingle (comment, "ORIGINALDATE", "2001-01-01"); + AssertSingle (comment, "ORIGINALYEAR", "2001"); + + // No four-digit year to copy: ORIGINALYEAR keeps its value; the getter reads ORIGINALDATE. + comment.OriginalReleaseDate = "Summer"; + Assert.AreEqual ("Summer", comment.OriginalReleaseDate); + AssertSingle (comment, "ORIGINALYEAR", "2001"); - comment.AddField ("ORIGINALYEAR", "1969"); comment.OriginalReleaseDate = null; Assert.IsNull (comment.OriginalReleaseDate); Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); @@ -373,21 +385,120 @@ public void OriginalReleaseDate_SetAndClear_RemovesOriginalYear () } [TestMethod] - public void Movement_SetAndClear_RemovesMovementName () + [DataRow ("1970", "1970")] + [DataRow ("1970-02", "1970")] + [DataRow ("1970/02/03", "1970")] + [DataRow ("197", "1969")] + [DataRow ("19701", "1969")] + [DataRow ("19x0-01-01", "1969")] + public void OriginalReleaseDate_Set_CopiesOnlyALeadingFourDigitYear (string date, string expectedYear) + { + var comment = new VorbisComment ("test"); + comment.AddField ("ORIGINALYEAR", "1969"); + comment.OriginalReleaseDate = date; + + Assert.AreEqual (date, comment.OriginalReleaseDate); + AssertSingle (comment, "ORIGINALYEAR", expectedYear); + } + + [TestMethod] + public void OriginalReleaseDate_SetWithoutOriginalYear_DoesNotAddIt () + { + var comment = new VorbisComment ("test"); + comment.OriginalReleaseDate = "2001-01-01"; + + Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + } + + [TestMethod] + public void OriginalReleaseDate_SetEmpty_RemovesOriginalYear () + { + var comment = new VorbisComment ("test"); + comment.AddField ("ORIGINALYEAR", "1969"); + comment.OriginalReleaseDate = ""; + + Assert.AreEqual ("", comment.OriginalReleaseDate); + Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + } + + [TestMethod] + public void Movement_Set_RewritesMovementName_ClearRemovesBoth () { var comment = new VorbisComment ("test"); comment.AddField ("MOVEMENTNAME", "Adagio"); comment.Movement = "Allegro"; Assert.AreEqual ("Allegro", comment.Movement); - Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + AssertSingle (comment, "MOVEMENT", "Allegro"); + AssertSingle (comment, "MOVEMENTNAME", "Allegro"); - comment.AddField ("MOVEMENTNAME", "Adagio"); comment.Movement = null; Assert.IsNull (comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + } + + [TestMethod] + public void Movement_SetWithoutMovementName_DoesNotAddIt () + { + var comment = new VorbisComment ("test"); + comment.Movement = "Allegro"; + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); } + [TestMethod] + public void Movement_SetEmpty_RemovesMovementName () + { + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.Movement = ""; + + Assert.AreEqual ("", comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + } + + [TestMethod] + public void PicardTags_UnchangedWriteBack_KeepsEveryField () + { + // Picard's mapping: MOVEMENTNAME is the name, MOVEMENT the number, ORIGINALYEAR the year + // beside ORIGINALDATE. Writing back what the getters return must not lose any of them. + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Allegro"); + comment.AddField ("MOVEMENT", "2"); + comment.AddField ("MOVEMENTTOTAL", "4"); + comment.AddField ("ORIGINALDATE", "1969-09-26"); + comment.AddField ("ORIGINALYEAR", "1969"); + + comment.Movement = comment.Movement; + comment.OriginalReleaseDate = comment.OriginalReleaseDate; + + var reparsed = VorbisComment.Read (comment.Render ().Span); + Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); + var tag = reparsed.Tag!; + AssertSingle (tag, "MOVEMENTNAME", "Allegro"); + AssertSingle (tag, "MOVEMENT", "2"); + AssertSingle (tag, "MOVEMENTTOTAL", "4"); + AssertSingle (tag, "ORIGINALDATE", "1969-09-26"); + AssertSingle (tag, "ORIGINALYEAR", "1969"); + } + + [TestMethod] + public void FallbackOnly_UnchangedWriteBack_KeepsFallbackField () + { + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Allegro"); + comment.AddField ("ORIGINALYEAR", "1969"); + + comment.Movement = comment.Movement; + comment.OriginalReleaseDate = comment.OriginalReleaseDate; + + Assert.AreEqual ("Allegro", comment.Movement); + Assert.AreEqual ("1969", comment.OriginalReleaseDate); + AssertSingle (comment, "MOVEMENTNAME", "Allegro"); + AssertSingle (comment, "ORIGINALYEAR", "1969"); + } + [TestMethod] public void OriginalReleaseDate_SetNull_ClearsField () { From 970f33673f13b1488d3bb9702b158d7d6c7c6b73 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 11:02:04 -0700 Subject: [PATCH 10/29] docs: Describe the ID3 movement frames and fallback writes The movement remarks now name MVNM and MVIN for ID3v2. The changelog records the new ID3v2 MVNM and MVIN writes, the TDOR and TORY clear, and the narrowed Vorbis and APE fallback rule. --- CHANGELOG.md | 6 ++++-- src/TagLibSharp2/Core/Tag.cs | 12 ++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d12d5b5..f04c7e78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- Setting or clearing an APE year also removes `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. -- Setting or clearing a Vorbis original release date also removes `ORIGINALYEAR`. Setting or clearing a movement also removes `MOVEMENTNAME`. +- Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. +- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. +- An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. +- Setting or clearing an ID3v2 original release date removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. ## [0.6.0] - 2026-01-05 diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 3fd52b46..63561b67 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -342,8 +342,10 @@ public virtual string[] Composers { /// Used in conjunction with to describe the full piece. /// /// - /// In ID3v2, this is stored in a TXXX frame with description "MOVEMENT". - /// In Vorbis Comments, this is stored as MOVEMENT or MOVEMENTNAME. + /// In ID3v2, this is read from Apple's MVNM frame, then a TXXX frame with description "MOVEMENT". + /// A write stores the name in both, and a clear removes both. + /// In Vorbis Comments, this is stored as MOVEMENT or MOVEMENTNAME; a new value also replaces an + /// existing MOVEMENTNAME, and writing back the value already read changes nothing. /// Not all tag formats support this field. Default implementation returns null. /// /// @@ -358,7 +360,8 @@ public virtual string[] Composers { /// Used with to show position like "Movement 2 of 4". /// /// - /// In ID3v2, this is stored in a TXXX frame with description "MOVEMENTNUMBER". + /// In ID3v2, this is read from the index half of Apple's MVIN frame ("2/4"), then a TXXX frame + /// with description "MOVEMENTNUMBER". A write updates both and keeps the total half of MVIN. /// In Vorbis Comments, this is stored as MOVEMENTNUMBER. /// Not all tag formats support this field. Default implementation returns null. /// @@ -374,7 +377,8 @@ public virtual string[] Composers { /// Used with to show position like "Movement 2 of 4". /// /// - /// In ID3v2, this is stored in a TXXX frame with description "MOVEMENTTOTAL". + /// In ID3v2, this is read from the total half of Apple's MVIN frame ("2/4"), then a TXXX frame + /// with description "MOVEMENTTOTAL". A write updates both and keeps the index half of MVIN. /// In Vorbis Comments, this is stored as MOVEMENTTOTAL or MOVEMENTCOUNT. /// Not all tag formats support this field. Default implementation returns null. /// From f4224542d77f5a21ea0bb67759d935daf3b72096 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 12:09:59 -0700 Subject: [PATCH 11/29] test: Pin the TXXX movement number a total clear keeps Clearing the total from MVIN "2/5" must leave TXXX:MOVEMENTNUMBER holding 2, so a reader that only looks at TXXX still sees the number. --- .../Id3/Id3v2/Id3v2TagClassicalMusicTests.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs index 7d400727..eefc97eb 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs @@ -204,11 +204,14 @@ public void MovementTotal_ClearFromIndexOnly_KeepsNumberFromIndex (byte version) Assert.IsTrue (result.IsSuccess, result.Error); var tag = result.Tag!; + Assert.IsNull (tag.GetUserText ("MOVEMENTNUMBER")); + tag.MovementTotal = null; Assert.AreEqual (2u, tag.MovementNumber); Assert.IsNull (tag.MovementTotal); Assert.AreEqual ("2", tag.GetTextFrame ("MVIN")); + Assert.AreEqual ("2", tag.GetUserText ("MOVEMENTNUMBER")); var reparsed = Id3v2Tag.Read (tag.Render ().Span); Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); From 6c3db685df6a66003bd2a1317b8faca0d9d5985a Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 12:09:59 -0700 Subject: [PATCH 12/29] fix: Make a write-back of any single-value field a no-op A single-value getter returns the first name of a multi-value ID3v2 frame, APE item, or repeated Vorbis field, and the setter stored that one name in place of the list. An editor that writes back what it read erased every other artist, composer, or genre. Every ID3v2 text and TXXX property, every APE text property, and every Vorbis text field now leaves the tag alone when the value equals what the getter returns, an empty string included. The ID3v2 movement number, total, and original release date follow the same rule. Any other value still replaces the list, and null still clears it. An empty MOVEMENT, ORIGINALDATE, APE Year, or ID3v2 MVNM no longer hides a filled fallback, and a TDOR or TORY without a date no longer hides the other frame. Before, the getter returned the empty value and writing it back deleted the fallback. An ID3v2 genre whose first value is empty reads as an empty string, like the other text frames. --- src/TagLibSharp2/Ape/ApeTag.cs | 144 ++++++----- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 192 ++++++++------ src/TagLibSharp2/Xiph/VorbisComment.cs | 156 ++++++----- .../Ape/ApeTagWriteBackTests.cs | 170 ++++++++++++ .../Id3/Id3v2/Id3v2WriteBackTests.cs | 242 ++++++++++++++++++ .../VorbisCommentExtendedMetadataTests.cs | 45 ++++ .../Xiph/VorbisCommentWriteBackTests.cs | 83 ++++++ 7 files changed, 835 insertions(+), 197 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs create mode 100644 tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index bbc67dd2..3351bd58 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -174,7 +174,7 @@ private ApeTag (Dictionary items) /// public override string? Title { get => GetValue (Keys.Title); - set => SetOrRemove (Keys.Title, value); + set => SetOrRemoveProperty (Keys.Title, value, Title); } /// @@ -183,7 +183,7 @@ public override string? Title { /// public override string? Artist { get => ReadFirstName (Keys.Artist); - set => SetOrRemove (Keys.Artist, value); + set => SetOrRemoveProperty (Keys.Artist, value, Artist); } /// @@ -200,7 +200,7 @@ public override string[] Performers { /// public override string? Album { get => GetValue (Keys.Album); - set => SetOrRemove (Keys.Album, value); + set => SetOrRemoveProperty (Keys.Album, value, Album); } /// @@ -213,7 +213,7 @@ public override string? Album { /// public override string? AlbumArtist { get => ReadFirstName (Keys.AlbumArtist, Keys.AlbumArtistAlias); - set => SetOrRemove (Keys.AlbumArtist, value, Keys.AlbumArtistAlias); + set => SetOrRemoveProperty (Keys.AlbumArtist, value, AlbumArtist, Keys.AlbumArtistAlias); } /// @@ -233,21 +233,27 @@ public override string[] AlbumArtists { /// /// - /// Reads "Year", then "Date". Writing back the value already read changes nothing. + /// Reads "Year", then "Date" when "Year" is missing or empty. Writing back the value already read changes nothing. /// A new value is written to "Year" and to an existing "Date". Clearing removes both. /// public override string? Year { - get => GetValue (Keys.Year) ?? GetValue (Keys.Date); + get { + var year = GetValue (Keys.Year); + if (!string.IsNullOrEmpty (year)) + return year; + var date = GetValue (Keys.Date); + return string.IsNullOrEmpty (date) ? year ?? date : date; + } set { + if (IsUnchanged (value, Year)) + return; + if (string.IsNullOrEmpty (value)) { _items.Remove (Keys.Year); _items.Remove (Keys.Date); return; } - if (string.Equals (Year, value, StringComparison.Ordinal)) - return; - SetValue (Keys.Year, value!); if (_items.ContainsKey (Keys.Date)) SetValue (Keys.Date, value!); @@ -257,7 +263,7 @@ public override string? Year { /// public override string? Comment { get => GetValue (Keys.Comment); - set => SetOrRemove (Keys.Comment, value); + set => SetOrRemoveProperty (Keys.Comment, value, Comment); } /// @@ -266,7 +272,7 @@ public override string? Comment { /// public override string? Genre { get => ReadFirstName (Keys.Genre); - set => SetOrRemove (Keys.Genre, value); + set => SetOrRemoveProperty (Keys.Genre, value, Genre); } /// @@ -351,7 +357,7 @@ public override uint? TotalDiscs { /// public override string? DiscSubtitle { get => GetValue ("DiscSubtitle"); - set => SetOrRemove ("DiscSubtitle", value); + set => SetOrRemoveProperty ("DiscSubtitle", value, DiscSubtitle); } /// @@ -360,7 +366,7 @@ public override string? DiscSubtitle { /// public override string? Composer { get => ReadFirstName (Keys.Composer); - set => SetOrRemove (Keys.Composer, value); + set => SetOrRemoveProperty (Keys.Composer, value, Composer); } /// @@ -377,133 +383,133 @@ public override string[] Composers { /// public override string? Conductor { get => GetValue (Keys.Conductor); - set => SetOrRemove (Keys.Conductor, value); + set => SetOrRemoveProperty (Keys.Conductor, value, Conductor); } /// public override string? Copyright { get => GetValue (Keys.Copyright); - set => SetOrRemove (Keys.Copyright, value); + set => SetOrRemoveProperty (Keys.Copyright, value, Copyright); } /// public override string? MusicBrainzTrackId { get => GetValue (Keys.MusicBrainzTrackId); - set => SetOrRemove (Keys.MusicBrainzTrackId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzTrackId, value, MusicBrainzTrackId); } /// public override string? MusicBrainzReleaseId { get => GetValue (Keys.MusicBrainzAlbumId); - set => SetOrRemove (Keys.MusicBrainzAlbumId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzAlbumId, value, MusicBrainzReleaseId); } /// public override string? MusicBrainzArtistId { get => GetValue (Keys.MusicBrainzArtistId); - set => SetOrRemove (Keys.MusicBrainzArtistId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzArtistId, value, MusicBrainzArtistId); } /// public override string? MusicBrainzAlbumArtistId { get => GetValue (Keys.MusicBrainzAlbumArtistId); - set => SetOrRemove (Keys.MusicBrainzAlbumArtistId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzAlbumArtistId, value, MusicBrainzAlbumArtistId); } /// public override string? MusicBrainzReleaseGroupId { get => GetValue (Keys.MusicBrainzReleaseGroupId); - set => SetOrRemove (Keys.MusicBrainzReleaseGroupId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzReleaseGroupId, value, MusicBrainzReleaseGroupId); } /// public override string? MusicBrainzWorkId { get => GetValue (Keys.MusicBrainzWorkId); - set => SetOrRemove (Keys.MusicBrainzWorkId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzWorkId, value, MusicBrainzWorkId); } /// public override string? MusicBrainzDiscId { get => GetValue (Keys.MusicBrainzDiscId); - set => SetOrRemove (Keys.MusicBrainzDiscId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzDiscId, value, MusicBrainzDiscId); } /// public override string? ReplayGainTrackGain { get => GetValue (Keys.ReplayGainTrackGain); - set => SetOrRemove (Keys.ReplayGainTrackGain, value); + set => SetOrRemoveProperty (Keys.ReplayGainTrackGain, value, ReplayGainTrackGain); } /// public override string? ReplayGainTrackPeak { get => GetValue (Keys.ReplayGainTrackPeak); - set => SetOrRemove (Keys.ReplayGainTrackPeak, value); + set => SetOrRemoveProperty (Keys.ReplayGainTrackPeak, value, ReplayGainTrackPeak); } /// public override string? ReplayGainAlbumGain { get => GetValue (Keys.ReplayGainAlbumGain); - set => SetOrRemove (Keys.ReplayGainAlbumGain, value); + set => SetOrRemoveProperty (Keys.ReplayGainAlbumGain, value, ReplayGainAlbumGain); } /// public override string? ReplayGainAlbumPeak { get => GetValue (Keys.ReplayGainAlbumPeak); - set => SetOrRemove (Keys.ReplayGainAlbumPeak, value); + set => SetOrRemoveProperty (Keys.ReplayGainAlbumPeak, value, ReplayGainAlbumPeak); } /// public override string? R128TrackGain { get => GetValue ("R128_TRACK_GAIN"); - set => SetOrRemove ("R128_TRACK_GAIN", value); + set => SetOrRemoveProperty ("R128_TRACK_GAIN", value, R128TrackGain); } /// public override string? R128AlbumGain { get => GetValue ("R128_ALBUM_GAIN"); - set => SetOrRemove ("R128_ALBUM_GAIN", value); + set => SetOrRemoveProperty ("R128_ALBUM_GAIN", value, R128AlbumGain); } /// public override string? Subtitle { get => GetValue (Keys.Subtitle); - set => SetOrRemove (Keys.Subtitle, value); + set => SetOrRemoveProperty (Keys.Subtitle, value, Subtitle); } /// public override string? Publisher { get => GetValue (Keys.Publisher); - set => SetOrRemove (Keys.Publisher, value); + set => SetOrRemoveProperty (Keys.Publisher, value, Publisher); } /// public override string? Isrc { get => GetValue (Keys.Isrc); - set => SetOrRemove (Keys.Isrc, value); + set => SetOrRemoveProperty (Keys.Isrc, value, Isrc); } /// public override string? Barcode { get => GetValue (Keys.Barcode); - set => SetOrRemove (Keys.Barcode, value); + set => SetOrRemoveProperty (Keys.Barcode, value, Barcode); } /// public override string? CatalogNumber { get => GetValue (Keys.CatalogNumber); - set => SetOrRemove (Keys.CatalogNumber, value); + set => SetOrRemoveProperty (Keys.CatalogNumber, value, CatalogNumber); } /// public override string? Language { get => GetValue (Keys.Language); - set => SetOrRemove (Keys.Language, value); + set => SetOrRemoveProperty (Keys.Language, value, Language); } /// public override string? Lyrics { get => GetValue ("Lyrics"); - set => SetOrRemove ("Lyrics", value); + set => SetOrRemoveProperty ("Lyrics", value, Lyrics); } // ═══════════════════════════════════════════════════════════════ @@ -543,67 +549,67 @@ public override bool IsCompilation { /// public override string? OriginalReleaseDate { get => GetValue (Keys.OriginalDate); - set => SetOrRemove (Keys.OriginalDate, value); + set => SetOrRemoveProperty (Keys.OriginalDate, value, OriginalReleaseDate); } /// public override string? Grouping { get => GetValue (Keys.Grouping); - set => SetOrRemove (Keys.Grouping, value); + set => SetOrRemoveProperty (Keys.Grouping, value, Grouping); } /// public override string? Remixer { get => GetValue (Keys.Remixer); - set => SetOrRemove (Keys.Remixer, value); + set => SetOrRemoveProperty (Keys.Remixer, value, Remixer); } /// public override string? InitialKey { get => GetValue (Keys.InitialKey); - set => SetOrRemove (Keys.InitialKey, value); + set => SetOrRemoveProperty (Keys.InitialKey, value, InitialKey); } /// public override string? Mood { get => GetValue (Keys.Mood); - set => SetOrRemove (Keys.Mood, value); + set => SetOrRemoveProperty (Keys.Mood, value, Mood); } /// public override string? MediaType { get => GetValue (Keys.MediaType); - set => SetOrRemove (Keys.MediaType, value); + set => SetOrRemoveProperty (Keys.MediaType, value, MediaType); } /// public override string? EncodedBy { get => GetValue (Keys.EncodedBy); - set => SetOrRemove (Keys.EncodedBy, value); + set => SetOrRemoveProperty (Keys.EncodedBy, value, EncodedBy); } /// public override string? EncoderSettings { get => GetValue (Keys.EncoderSettings); - set => SetOrRemove (Keys.EncoderSettings, value); + set => SetOrRemoveProperty (Keys.EncoderSettings, value, EncoderSettings); } /// public override string? Description { get => GetValue (Keys.Description); - set => SetOrRemove (Keys.Description, value); + set => SetOrRemoveProperty (Keys.Description, value, Description); } /// public override string? DateTagged { get => GetValue (Keys.DateTagged); - set => SetOrRemove (Keys.DateTagged, value); + set => SetOrRemoveProperty (Keys.DateTagged, value, DateTagged); } /// public override string? AmazonId { get => GetValue (Keys.AmazonId); - set => SetOrRemove (Keys.AmazonId, value); + set => SetOrRemoveProperty (Keys.AmazonId, value, AmazonId); } // ═══════════════════════════════════════════════════════════════ @@ -613,25 +619,25 @@ public override string? AmazonId { /// public override string? MusicBrainzRecordingId { get => GetValue (Keys.MusicBrainzRecordingId); - set => SetOrRemove (Keys.MusicBrainzRecordingId, value); + set => SetOrRemoveProperty (Keys.MusicBrainzRecordingId, value, MusicBrainzRecordingId); } /// public override string? MusicBrainzReleaseStatus { get => GetValue (Keys.MusicBrainzReleaseStatus); - set => SetOrRemove (Keys.MusicBrainzReleaseStatus, value); + set => SetOrRemoveProperty (Keys.MusicBrainzReleaseStatus, value, MusicBrainzReleaseStatus); } /// public override string? MusicBrainzReleaseType { get => GetValue (Keys.MusicBrainzReleaseType); - set => SetOrRemove (Keys.MusicBrainzReleaseType, value); + set => SetOrRemoveProperty (Keys.MusicBrainzReleaseType, value, MusicBrainzReleaseType); } /// public override string? MusicBrainzReleaseCountry { get => GetValue (Keys.MusicBrainzReleaseCountry); - set => SetOrRemove (Keys.MusicBrainzReleaseCountry, value); + set => SetOrRemoveProperty (Keys.MusicBrainzReleaseCountry, value, MusicBrainzReleaseCountry); } // ═══════════════════════════════════════════════════════════════ @@ -641,19 +647,19 @@ public override string? MusicBrainzReleaseCountry { /// public override string? AcoustIdId { get => GetValue (Keys.AcoustIdId); - set => SetOrRemove (Keys.AcoustIdId, value); + set => SetOrRemoveProperty (Keys.AcoustIdId, value, AcoustIdId); } /// public override string? AcoustIdFingerprint { get => GetValue (Keys.AcoustIdFingerprint); - set => SetOrRemove (Keys.AcoustIdFingerprint, value); + set => SetOrRemoveProperty (Keys.AcoustIdFingerprint, value, AcoustIdFingerprint); } /// public override string? PodcastFeedUrl { get => GetValue (Keys.PodcastFeedUrl); - set => SetOrRemove (Keys.PodcastFeedUrl, value); + set => SetOrRemoveProperty (Keys.PodcastFeedUrl, value, PodcastFeedUrl); } // ═══════════════════════════════════════════════════════════════ @@ -663,13 +669,13 @@ public override string? PodcastFeedUrl { /// public override string? Work { get => GetValue (Keys.Work); - set => SetOrRemove (Keys.Work, value); + set => SetOrRemoveProperty (Keys.Work, value, Work); } /// public override string? Movement { get => GetValue (Keys.Movement); - set => SetOrRemove (Keys.Movement, value); + set => SetOrRemoveProperty (Keys.Movement, value, Movement); } /// @@ -711,31 +717,31 @@ public override uint? MovementTotal { /// public override string? TitleSort { get => GetValue ("TitleSort") ?? GetValue ("TITLESORT"); - set => SetOrRemove ("TitleSort", value); + set => SetOrRemoveProperty ("TitleSort", value, TitleSort); } /// public override string? ArtistSort { get => GetValue ("ArtistSort") ?? GetValue ("ARTISTSORT"); - set => SetOrRemove ("ArtistSort", value); + set => SetOrRemoveProperty ("ArtistSort", value, ArtistSort); } /// public override string? AlbumSort { get => GetValue ("AlbumSort") ?? GetValue ("ALBUMSORT"); - set => SetOrRemove ("AlbumSort", value); + set => SetOrRemoveProperty ("AlbumSort", value, AlbumSort); } /// public override string? AlbumArtistSort { get => GetValue ("AlbumArtistSort") ?? GetValue ("ALBUMARTISTSORT"); - set => SetOrRemove ("AlbumArtistSort", value); + set => SetOrRemoveProperty ("AlbumArtistSort", value, AlbumArtistSort); } /// public override string? ComposerSort { get => GetValue ("ComposerSort") ?? GetValue ("COMPOSERSORT"); - set => SetOrRemove ("ComposerSort", value); + set => SetOrRemoveProperty ("ComposerSort", value, ComposerSort); } // ═══════════════════════════════════════════════════════════════ @@ -911,6 +917,24 @@ public void SetBinaryItem (string key, string filename, byte[] data) _items[key] = ApeTagItem.CreateBinary (key, filename, data); } + /// + /// Writes a single-value property. Writing back the value its getter returned is a no-op, so a + /// text item that holds several values (APEv2 items separate them with a zero byte), an empty item, + /// or the alias item the getter read stays as it is. Any other value goes through . + /// + void SetOrRemoveProperty (string key, string? value, string? current, string? alias = null) + { + if (!IsUnchanged (value, current)) + SetOrRemove (key, value, alias); + } + + /// + /// True when is exactly what the getter returned, including an empty string. + /// A null value is always a clear. + /// + static bool IsUnchanged (string? value, string? current) => + value is not null && string.Equals (value, current, StringComparison.Ordinal); + /// /// Removes an item by key. /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 3b443ac6..040e49b9 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -202,19 +202,19 @@ public PictureFrame? CoverArt { /// public override string? Title { get => GetTextFrame ("TIT2"); - set => SetTextFrame ("TIT2", value); + set => SetTextFrameProperty ("TIT2", value, Title); } /// public override string? Artist { get => GetTextFrame ("TPE1"); - set => SetTextFrame ("TPE1", value); + set => SetTextFrameProperty ("TPE1", value, Artist); } /// public override string? Album { get => GetTextFrame ("TALB"); - set => SetTextFrame ("TALB", value); + set => SetTextFrameProperty ("TALB", value, Album); } /// @@ -247,30 +247,30 @@ private protected override string? CopyableDate { /// /// In ID3v2.4, uses the TDOR (Original Release Time) frame. /// In ID3v2.3, uses the TORY (Original Release Year) frame. - /// When reading, falls back to the other version's frame if the primary is not found. - /// Setting or clearing removes both frames, then writes the frame for this version. + /// When reading, falls back to the other version's frame if the primary is missing or holds no date. + /// Writing back the value already read changes nothing. Any other set, or a clear, removes both + /// frames, then writes the frame for this version. /// public override string? OriginalReleaseDate { get { // TDOR is an ID3v2.4 timestamp. TORY uses the four-digit TYER form. - if (Version == 4) { - var tdor = GetTextFrame ("TDOR"); - if (tdor is not null) - return NormalizeReleaseTimestamp (tdor); - return NormalizeYear (GetTextFrame ("TORY")); - } + // A primary frame that holds no date (empty or invalid) does not hide the other one, + // so a write-back of the value read cannot clear a date that is still there. + if (Version == 4) + return NormalizeReleaseTimestamp (GetTextFrame ("TDOR")) ?? NormalizeYear (GetTextFrame ("TORY")); - var tory = GetTextFrame ("TORY"); - if (tory is not null) - return NormalizeYear (tory); - return NormalizeReleaseTimestamp (GetTextFrame ("TDOR")); + return NormalizeYear (GetTextFrame ("TORY")) ?? NormalizeReleaseTimestamp (GetTextFrame ("TDOR")); + } + set { + if (IsUnchanged (value, OriginalReleaseDate)) + return; + SetDateFrame ( + Version == 4 ? "TDOR" : "TORY", + value, + Version == 4, + keepMatchingYear: false, + alsoClear: Version == 4 ? "TORY" : "TDOR"); } - set => SetDateFrame ( - Version == 4 ? "TDOR" : "TORY", - value, - Version == 4, - keepMatchingYear: false, - alsoClear: Version == 4 ? "TORY" : "TDOR"); } /// @@ -500,8 +500,12 @@ public void SetUserUrl (string description, string? url) /// public override string? Genre { - get => ResolveGenreDisplay (GetTextFrame ("TCON"), Version); - set => SetTextFrame ("TCON", value); + get { + // An empty first value reads "", like every other text frame, so writing it back keeps the frame. + var raw = GetTextFrame ("TCON"); + return raw is { Length: 0 } ? raw : ResolveGenreDisplay (raw, Version); + } + set => SetTextFrameProperty ("TCON", value, Genre); } /// @@ -538,7 +542,7 @@ public override uint? Track { /// public override string? AlbumArtist { get => GetTextFrame ("TPE2"); - set => SetTextFrame ("TPE2", value); + set => SetTextFrameProperty ("TPE2", value, AlbumArtist); } /// @@ -575,7 +579,7 @@ public override uint? DiscNumber { /// public override string? Composer { get => GetTextFrame ("TCOM"); - set => SetTextFrame ("TCOM", value); + set => SetTextFrameProperty ("TCOM", value, Composer); } /// @@ -592,13 +596,13 @@ public override uint? BeatsPerMinute { /// public override string? Conductor { get => GetTextFrame ("TPE3"); - set => SetTextFrame ("TPE3", value); + set => SetTextFrameProperty ("TPE3", value, Conductor); } /// public override string? Copyright { get => GetTextFrame ("TCOP"); - set => SetTextFrame ("TCOP", value); + set => SetTextFrameProperty ("TCOP", value, Copyright); } /// @@ -624,109 +628,109 @@ public override string? PodcastFeedUrl { /// public override string? Isrc { get => GetTextFrame ("TSRC"); - set => SetTextFrame ("TSRC", value); + set => SetTextFrameProperty ("TSRC", value, Isrc); } /// public override string? Publisher { get => GetTextFrame ("TPUB"); - set => SetTextFrame ("TPUB", value); + set => SetTextFrameProperty ("TPUB", value, Publisher); } /// public override string? EncodedBy { get => GetTextFrame ("TENC"); - set => SetTextFrame ("TENC", value); + set => SetTextFrameProperty ("TENC", value, EncodedBy); } /// public override string? EncoderSettings { get => GetTextFrame ("TSSE"); - set => SetTextFrame ("TSSE", value); + set => SetTextFrameProperty ("TSSE", value, EncoderSettings); } /// public override string? Grouping { get => GetTextFrame ("TIT1"); - set => SetTextFrame ("TIT1", value); + set => SetTextFrameProperty ("TIT1", value, Grouping); } /// public override string? Subtitle { get => GetTextFrame ("TIT3"); - set => SetTextFrame ("TIT3", value); + set => SetTextFrameProperty ("TIT3", value, Subtitle); } /// public override string? DiscSubtitle { get => GetTextFrame ("TSST"); - set => SetTextFrame ("TSST", value); + set => SetTextFrameProperty ("TSST", value, DiscSubtitle); } /// public override string? Remixer { get => GetTextFrame ("TPE4"); - set => SetTextFrame ("TPE4", value); + set => SetTextFrameProperty ("TPE4", value, Remixer); } /// public override string? InitialKey { get => GetTextFrame ("TKEY"); - set => SetTextFrame ("TKEY", value); + set => SetTextFrameProperty ("TKEY", value, InitialKey); } /// public override string? Mood { get => GetTextFrame ("TMOO"); - set => SetTextFrame ("TMOO", value); + set => SetTextFrameProperty ("TMOO", value, Mood); } /// public override string? MediaType { get => GetTextFrame ("TMED"); - set => SetTextFrame ("TMED", value); + set => SetTextFrameProperty ("TMED", value, MediaType); } /// public override string? Language { get => GetTextFrame ("TLAN"); - set => SetTextFrame ("TLAN", value); + set => SetTextFrameProperty ("TLAN", value, Language); } /// public override string? Barcode { get => GetUserText ("BARCODE"); - set => SetUserText ("BARCODE", value); + set => SetUserTextProperty ("BARCODE", value, Barcode); } /// public override string? CatalogNumber { get => GetUserText ("CATALOGNUMBER"); - set => SetUserText ("CATALOGNUMBER", value); + set => SetUserTextProperty ("CATALOGNUMBER", value, CatalogNumber); } /// public override string? AlbumSort { get => GetTextFrame ("TSOA"); - set => SetTextFrame ("TSOA", value); + set => SetTextFrameProperty ("TSOA", value, AlbumSort); } /// public override string? ArtistSort { get => GetTextFrame ("TSOP"); - set => SetTextFrame ("TSOP", value); + set => SetTextFrameProperty ("TSOP", value, ArtistSort); } /// public override string? TitleSort { get => GetTextFrame ("TSOT"); - set => SetTextFrame ("TSOT", value); + set => SetTextFrameProperty ("TSOT", value, TitleSort); } /// public override string? AlbumArtistSort { get => GetTextFrame ("TSO2"); - set => SetTextFrame ("TSO2", value); + set => SetTextFrameProperty ("TSO2", value, AlbumArtistSort); } /// @@ -856,103 +860,103 @@ public override string? Lyrics { /// public override string? ReplayGainTrackGain { get => GetUserText ("REPLAYGAIN_TRACK_GAIN"); - set => SetUserText ("REPLAYGAIN_TRACK_GAIN", value); + set => SetUserTextProperty ("REPLAYGAIN_TRACK_GAIN", value, ReplayGainTrackGain); } /// public override string? ReplayGainTrackPeak { get => GetUserText ("REPLAYGAIN_TRACK_PEAK"); - set => SetUserText ("REPLAYGAIN_TRACK_PEAK", value); + set => SetUserTextProperty ("REPLAYGAIN_TRACK_PEAK", value, ReplayGainTrackPeak); } /// public override string? ReplayGainAlbumGain { get => GetUserText ("REPLAYGAIN_ALBUM_GAIN"); - set => SetUserText ("REPLAYGAIN_ALBUM_GAIN", value); + set => SetUserTextProperty ("REPLAYGAIN_ALBUM_GAIN", value, ReplayGainAlbumGain); } /// public override string? ReplayGainAlbumPeak { get => GetUserText ("REPLAYGAIN_ALBUM_PEAK"); - set => SetUserText ("REPLAYGAIN_ALBUM_PEAK", value); + set => SetUserTextProperty ("REPLAYGAIN_ALBUM_PEAK", value, ReplayGainAlbumPeak); } /// public override string? R128TrackGain { get => GetUserText ("R128_TRACK_GAIN"); - set => SetUserText ("R128_TRACK_GAIN", value); + set => SetUserTextProperty ("R128_TRACK_GAIN", value, R128TrackGain); } /// public override string? R128AlbumGain { get => GetUserText ("R128_ALBUM_GAIN"); - set => SetUserText ("R128_ALBUM_GAIN", value); + set => SetUserTextProperty ("R128_ALBUM_GAIN", value, R128AlbumGain); } /// public override string? MusicBrainzTrackId { get => GetUserText ("MUSICBRAINZ_TRACKID"); - set => SetUserText ("MUSICBRAINZ_TRACKID", value); + set => SetUserTextProperty ("MUSICBRAINZ_TRACKID", value, MusicBrainzTrackId); } /// public override string? MusicBrainzReleaseId { get => GetUserText ("MUSICBRAINZ_ALBUMID"); - set => SetUserText ("MUSICBRAINZ_ALBUMID", value); + set => SetUserTextProperty ("MUSICBRAINZ_ALBUMID", value, MusicBrainzReleaseId); } /// public override string? MusicBrainzArtistId { get => GetUserText ("MUSICBRAINZ_ARTISTID"); - set => SetUserText ("MUSICBRAINZ_ARTISTID", value); + set => SetUserTextProperty ("MUSICBRAINZ_ARTISTID", value, MusicBrainzArtistId); } /// public override string? MusicBrainzReleaseGroupId { get => GetUserText ("MUSICBRAINZ_RELEASEGROUPID"); - set => SetUserText ("MUSICBRAINZ_RELEASEGROUPID", value); + set => SetUserTextProperty ("MUSICBRAINZ_RELEASEGROUPID", value, MusicBrainzReleaseGroupId); } /// public override string? MusicBrainzAlbumArtistId { get => GetUserText ("MUSICBRAINZ_ALBUMARTISTID"); - set => SetUserText ("MUSICBRAINZ_ALBUMARTISTID", value); + set => SetUserTextProperty ("MUSICBRAINZ_ALBUMARTISTID", value, MusicBrainzAlbumArtistId); } /// public override string? MusicBrainzWorkId { get => GetUserText ("MusicBrainz Work Id"); - set => SetUserText ("MusicBrainz Work Id", value); + set => SetUserTextProperty ("MusicBrainz Work Id", value, MusicBrainzWorkId); } /// public override string? MusicBrainzDiscId { get => GetUserText ("MusicBrainz Disc Id"); - set => SetUserText ("MusicBrainz Disc Id", value); + set => SetUserTextProperty ("MusicBrainz Disc Id", value, MusicBrainzDiscId); } /// public override string? MusicBrainzReleaseStatus { get => GetUserText ("MusicBrainz Album Status"); - set => SetUserText ("MusicBrainz Album Status", value); + set => SetUserTextProperty ("MusicBrainz Album Status", value, MusicBrainzReleaseStatus); } /// public override string? MusicBrainzReleaseType { get => GetUserText ("MusicBrainz Album Type"); - set => SetUserText ("MusicBrainz Album Type", value); + set => SetUserTextProperty ("MusicBrainz Album Type", value, MusicBrainzReleaseType); } /// public override string? MusicBrainzReleaseCountry { get => GetUserText ("MusicBrainz Album Release Country"); - set => SetUserText ("MusicBrainz Album Release Country", value); + set => SetUserTextProperty ("MusicBrainz Album Release Country", value, MusicBrainzReleaseCountry); } /// public override string? ComposerSort { get => GetTextFrame ("TSOC"); - set => SetTextFrame ("TSOC", value); + set => SetTextFrameProperty ("TSOC", value, ComposerSort); } /// @@ -961,47 +965,56 @@ public override string? ComposerSort { /// public override string? DateTagged { get => GetTextFrame ("TDTG"); - set => SetTextFrame ("TDTG", value); + set => SetTextFrameProperty ("TDTG", value, DateTagged); } /// public override string? Description { get => GetUserText ("DESCRIPTION"); - set => SetUserText ("DESCRIPTION", value); + set => SetUserTextProperty ("DESCRIPTION", value, Description); } /// public override string? AmazonId { get => GetUserText ("ASIN"); - set => SetUserText ("ASIN", value); + set => SetUserTextProperty ("ASIN", value, AmazonId); } /// public override string? AcoustIdId { get => GetUserText ("ACOUSTID_ID"); - set => SetUserText ("ACOUSTID_ID", value); + set => SetUserTextProperty ("ACOUSTID_ID", value, AcoustIdId); } /// public override string? AcoustIdFingerprint { get => GetUserText ("ACOUSTID_FINGERPRINT"); - set => SetUserText ("ACOUSTID_FINGERPRINT", value); + set => SetUserTextProperty ("ACOUSTID_FINGERPRINT", value, AcoustIdFingerprint); } /// public override string? Work { get => GetUserText ("WORK"); - set => SetUserText ("WORK", value); + set => SetUserTextProperty ("WORK", value, Work); } /// /// - /// Reads from Apple's MVNM frame first, then falls back to TXXX:MOVEMENT. - /// A write stores the same value in both, and a clear removes both. + /// Reads from Apple's MVNM frame first, then falls back to TXXX:MOVEMENT when MVNM is missing or empty. + /// Writing back the value already read changes nothing. Any other write stores the same value in both, + /// and a clear removes both. /// public override string? Movement { - get => GetTextFrame ("MVNM") ?? GetUserText ("MOVEMENT"); + get { + var apple = GetTextFrame ("MVNM"); + if (!string.IsNullOrEmpty (apple)) + return apple; + var user = GetUserText ("MOVEMENT"); + return string.IsNullOrEmpty (user) ? apple ?? user : user; + } set { + if (IsUnchanged (value, Movement)) + return; SetTextFrame ("MVNM", value); SetUserText ("MOVEMENT", value); } @@ -1010,7 +1023,8 @@ public override string? Movement { /// /// /// Reads from Apple's MVIN frame first (index part), then falls back to TXXX:MOVEMENTNUMBER. - /// A write updates MVIN and the TXXX field together so the other half of MVIN is kept. + /// Writing back the value already read changes nothing. Any other write updates MVIN and the + /// TXXX field together so the other half of MVIN is kept. /// public override uint? MovementNumber { get { @@ -1026,6 +1040,8 @@ public override uint? MovementNumber { return uint.TryParse (value, out var result) ? result : null; } set { + if (value is not null && value == MovementNumber) + return; var total = MovementTotal; SetUserText ("MOVEMENTNUMBER", value?.ToString (CultureInfo.InvariantCulture)); if (total is not null) @@ -1037,7 +1053,8 @@ public override uint? MovementNumber { /// /// /// Reads from Apple's MVIN frame first (total part), then falls back to TXXX:MOVEMENTTOTAL. - /// A write updates MVIN and the TXXX field together so the index half of MVIN is kept. + /// Writing back the value already read changes nothing. Any other write updates MVIN and the + /// TXXX field together so the index half of MVIN is kept. /// public override uint? MovementTotal { get { @@ -1053,6 +1070,8 @@ public override uint? MovementTotal { return uint.TryParse (value, out var result) ? result : null; } set { + if (value is not null && value == MovementTotal) + return; var number = MovementNumber; SetUserText ("MOVEMENTTOTAL", value?.ToString (CultureInfo.InvariantCulture)); if (number is not null) @@ -1726,6 +1745,33 @@ void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatch SetTextFrame (frameId, normalized); } + /// + /// Writes a single-value text property. Writing back the value its getter returned is a no-op, + /// so the other values of a multi-value frame (ID3v2.4 §4.2, NUL-separated) and an empty + /// first value stay as they are. Any other value replaces the frame; null or empty removes it. + /// + void SetTextFrameProperty (string frameId, string? value, string? current) + { + if (!IsUnchanged (value, current)) + SetTextFrame (frameId, value); + } + + /// + /// Writes a single-value TXXX property, with the same write-back rule as . + /// + void SetUserTextProperty (string description, string? value, string? current) + { + if (!IsUnchanged (value, current)) + SetUserText (description, value); + } + + /// + /// True when is exactly what the getter returned, including an empty string. + /// A null value is always a clear. + /// + static bool IsUnchanged (string? value, string? current) => + value is not null && string.Equals (value, current, StringComparison.Ordinal); + /// /// Sets or creates a text frame. /// diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index b1a77af3..6955c33b 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -83,13 +83,13 @@ public override IPicture[] Pictures { /// public override string? Title { get => GetValue ("TITLE"); - set => SetValue ("TITLE", value); + set => SetValueProperty ("TITLE", value, Title); } /// public override string? Artist { get => GetValue ("ARTIST"); - set => SetValue ("ARTIST", value); + set => SetValueProperty ("ARTIST", value, Artist); } /// @@ -115,32 +115,32 @@ public override string[] Performers { /// public override string? Album { get => GetValue ("ALBUM"); - set => SetValue ("ALBUM", value); + set => SetValueProperty ("ALBUM", value, Album); } /// public override string? Year { get => GetValue ("DATE"); - set => SetValue ("DATE", value); + set => SetValueProperty ("DATE", value, Year); } /// /// - /// Uses ORIGINALDATE field. Falls back to ORIGINALYEAR if ORIGINALDATE is not found. + /// Uses ORIGINALDATE field. Falls back to ORIGINALYEAR if ORIGINALDATE is missing or empty. /// Writing back the value already read changes nothing. A new value is written to ORIGINALDATE, /// and an existing ORIGINALYEAR is rewritten to its four-digit year (MusicBrainz Picard keeps /// both: https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). /// Clearing removes both. /// public override string? OriginalReleaseDate { - get => GetValue ("ORIGINALDATE") ?? GetValue ("ORIGINALYEAR"); + get => GetValueOrFallback ("ORIGINALDATE", "ORIGINALYEAR"); set => SetValueWithFallback ("ORIGINALDATE", value, "ORIGINALYEAR", LeadingYear); } /// public override string? Genre { get => GetValue ("GENRE"); - set => SetValue ("GENRE", value); + set => SetValueProperty ("GENRE", value, Genre); } /// @@ -179,13 +179,13 @@ public override uint? Track { /// public override string? Comment { get => GetValue ("COMMENT"); - set => SetValue ("COMMENT", value); + set => SetValueProperty ("COMMENT", value, Comment); } /// public override string? AlbumArtist { get => GetValue ("ALBUMARTIST"); - set => SetValue ("ALBUMARTIST", value); + set => SetValueProperty ("ALBUMARTIST", value, AlbumArtist); } /// @@ -224,7 +224,7 @@ public override uint? DiscNumber { /// public override string? Composer { get => GetValue ("COMPOSER"); - set => SetValue ("COMPOSER", value); + set => SetValueProperty ("COMPOSER", value, Composer); } /// @@ -261,24 +261,24 @@ public override uint? BeatsPerMinute { /// public override string? Conductor { get => GetValue ("CONDUCTOR"); - set => SetValue ("CONDUCTOR", value); + set => SetValueProperty ("CONDUCTOR", value, Conductor); } /// public override string? Work { get => GetValue ("WORK"); - set => SetValue ("WORK", value); + set => SetValueProperty ("WORK", value, Work); } /// /// - /// Uses the MOVEMENT field. Falls back to MOVEMENTNAME for compatibility. + /// Uses the MOVEMENT field. Falls back to MOVEMENTNAME when MOVEMENT is missing or empty. /// Writing back the value already read changes nothing, so a MOVEMENTNAME that Picard or Mp3tag /// wrote beside a MOVEMENT number is kept. A new value is written to MOVEMENT and to an existing /// MOVEMENTNAME. Clearing removes both. /// public override string? Movement { - get => GetValue ("MOVEMENT") ?? GetValue ("MOVEMENTNAME"); + get => GetValueOrFallback ("MOVEMENT", "MOVEMENTNAME"); set => SetValueWithFallback ("MOVEMENT", value, "MOVEMENTNAME", static v => v); } @@ -307,7 +307,7 @@ public override uint? MovementTotal { /// public override string? Copyright { get => GetValue ("COPYRIGHT"); - set => SetValue ("COPYRIGHT", value); + set => SetValueProperty ("COPYRIGHT", value, Copyright); } /// @@ -324,103 +324,103 @@ public override bool IsCompilation { /// public override string? Isrc { get => GetValue ("ISRC"); - set => SetValue ("ISRC", value); + set => SetValueProperty ("ISRC", value, Isrc); } /// public override string? Publisher { get => GetValue ("LABEL"); - set => SetValue ("LABEL", value); + set => SetValueProperty ("LABEL", value, Publisher); } /// public override string? EncodedBy { get => GetValue ("ENCODED-BY"); - set => SetValue ("ENCODED-BY", value); + set => SetValueProperty ("ENCODED-BY", value, EncodedBy); } /// public override string? EncoderSettings { get => GetValue ("ENCODER"); - set => SetValue ("ENCODER", value); + set => SetValueProperty ("ENCODER", value, EncoderSettings); } /// public override string? Grouping { get => GetValue ("GROUPING"); - set => SetValue ("GROUPING", value); + set => SetValueProperty ("GROUPING", value, Grouping); } /// public override string? Subtitle { get => GetValue ("SUBTITLE"); - set => SetValue ("SUBTITLE", value); + set => SetValueProperty ("SUBTITLE", value, Subtitle); } /// public override string? Remixer { get => GetValue ("REMIXER"); - set => SetValue ("REMIXER", value); + set => SetValueProperty ("REMIXER", value, Remixer); } /// public override string? InitialKey { get => GetValue ("KEY"); - set => SetValue ("KEY", value); + set => SetValueProperty ("KEY", value, InitialKey); } /// public override string? Mood { get => GetValue ("MOOD"); - set => SetValue ("MOOD", value); + set => SetValueProperty ("MOOD", value, Mood); } /// public override string? MediaType { get => GetValue ("MEDIA"); - set => SetValue ("MEDIA", value); + set => SetValueProperty ("MEDIA", value, MediaType); } /// public override string? Language { get => GetValue ("LANGUAGE"); - set => SetValue ("LANGUAGE", value); + set => SetValueProperty ("LANGUAGE", value, Language); } /// public override string? Barcode { get => GetValue ("BARCODE"); - set => SetValue ("BARCODE", value); + set => SetValueProperty ("BARCODE", value, Barcode); } /// public override string? CatalogNumber { get => GetValue ("CATALOGNUMBER"); - set => SetValue ("CATALOGNUMBER", value); + set => SetValueProperty ("CATALOGNUMBER", value, CatalogNumber); } /// public override string? AlbumSort { get => GetValue ("ALBUMSORT"); - set => SetValue ("ALBUMSORT", value); + set => SetValueProperty ("ALBUMSORT", value, AlbumSort); } /// public override string? ArtistSort { get => GetValue ("ARTISTSORT"); - set => SetValue ("ARTISTSORT", value); + set => SetValueProperty ("ARTISTSORT", value, ArtistSort); } /// public override string? TitleSort { get => GetValue ("TITLESORT"); - set => SetValue ("TITLESORT", value); + set => SetValueProperty ("TITLESORT", value, TitleSort); } /// public override string? AlbumArtistSort { get => GetValue ("ALBUMARTISTSORT"); - set => SetValue ("ALBUMARTISTSORT", value); + set => SetValueProperty ("ALBUMARTISTSORT", value, AlbumArtistSort); } /// @@ -488,49 +488,49 @@ public override string[]? ComposersSort { /// public override string? Lyrics { get => GetValue ("LYRICS"); - set => SetValue ("LYRICS", value); + set => SetValueProperty ("LYRICS", value, Lyrics); } /// public override string? ReplayGainTrackGain { get => GetValue ("REPLAYGAIN_TRACK_GAIN"); - set => SetValue ("REPLAYGAIN_TRACK_GAIN", value); + set => SetValueProperty ("REPLAYGAIN_TRACK_GAIN", value, ReplayGainTrackGain); } /// public override string? ReplayGainTrackPeak { get => GetValue ("REPLAYGAIN_TRACK_PEAK"); - set => SetValue ("REPLAYGAIN_TRACK_PEAK", value); + set => SetValueProperty ("REPLAYGAIN_TRACK_PEAK", value, ReplayGainTrackPeak); } /// public override string? ReplayGainAlbumGain { get => GetValue ("REPLAYGAIN_ALBUM_GAIN"); - set => SetValue ("REPLAYGAIN_ALBUM_GAIN", value); + set => SetValueProperty ("REPLAYGAIN_ALBUM_GAIN", value, ReplayGainAlbumGain); } /// public override string? ReplayGainAlbumPeak { get => GetValue ("REPLAYGAIN_ALBUM_PEAK"); - set => SetValue ("REPLAYGAIN_ALBUM_PEAK", value); + set => SetValueProperty ("REPLAYGAIN_ALBUM_PEAK", value, ReplayGainAlbumPeak); } /// public override string? R128TrackGain { get => GetValue ("R128_TRACK_GAIN"); - set => SetValue ("R128_TRACK_GAIN", value); + set => SetValueProperty ("R128_TRACK_GAIN", value, R128TrackGain); } /// public override string? R128AlbumGain { get => GetValue ("R128_ALBUM_GAIN"); - set => SetValue ("R128_ALBUM_GAIN", value); + set => SetValueProperty ("R128_ALBUM_GAIN", value, R128AlbumGain); } /// public override string? MusicBrainzTrackId { get => GetValue ("MUSICBRAINZ_TRACKID"); - set => SetValue ("MUSICBRAINZ_TRACKID", value); + set => SetValueProperty ("MUSICBRAINZ_TRACKID", value, MusicBrainzTrackId); } /// @@ -540,103 +540,103 @@ public override string? MusicBrainzTrackId { /// public override string? MusicBrainzRecordingId { get => GetValue ("MUSICBRAINZ_TRACKID"); - set => SetValue ("MUSICBRAINZ_TRACKID", value); + set => SetValueProperty ("MUSICBRAINZ_TRACKID", value, MusicBrainzRecordingId); } /// public override string? MusicBrainzReleaseId { get => GetValue ("MUSICBRAINZ_ALBUMID"); - set => SetValue ("MUSICBRAINZ_ALBUMID", value); + set => SetValueProperty ("MUSICBRAINZ_ALBUMID", value, MusicBrainzReleaseId); } /// public override string? MusicBrainzArtistId { get => GetValue ("MUSICBRAINZ_ARTISTID"); - set => SetValue ("MUSICBRAINZ_ARTISTID", value); + set => SetValueProperty ("MUSICBRAINZ_ARTISTID", value, MusicBrainzArtistId); } /// public override string? MusicBrainzReleaseGroupId { get => GetValue ("MUSICBRAINZ_RELEASEGROUPID"); - set => SetValue ("MUSICBRAINZ_RELEASEGROUPID", value); + set => SetValueProperty ("MUSICBRAINZ_RELEASEGROUPID", value, MusicBrainzReleaseGroupId); } /// public override string? MusicBrainzAlbumArtistId { get => GetValue ("MUSICBRAINZ_ALBUMARTISTID"); - set => SetValue ("MUSICBRAINZ_ALBUMARTISTID", value); + set => SetValueProperty ("MUSICBRAINZ_ALBUMARTISTID", value, MusicBrainzAlbumArtistId); } /// public override string? MusicBrainzWorkId { get => GetValue ("MUSICBRAINZ_WORKID"); - set => SetValue ("MUSICBRAINZ_WORKID", value); + set => SetValueProperty ("MUSICBRAINZ_WORKID", value, MusicBrainzWorkId); } /// public override string? MusicBrainzDiscId { get => GetValue ("MUSICBRAINZ_DISCID"); - set => SetValue ("MUSICBRAINZ_DISCID", value); + set => SetValueProperty ("MUSICBRAINZ_DISCID", value, MusicBrainzDiscId); } /// public override string? MusicBrainzReleaseStatus { get => GetValue ("RELEASESTATUS"); - set => SetValue ("RELEASESTATUS", value); + set => SetValueProperty ("RELEASESTATUS", value, MusicBrainzReleaseStatus); } /// public override string? MusicBrainzReleaseType { get => GetValue ("RELEASETYPE"); - set => SetValue ("RELEASETYPE", value); + set => SetValueProperty ("RELEASETYPE", value, MusicBrainzReleaseType); } /// public override string? MusicBrainzReleaseCountry { get => GetValue ("RELEASECOUNTRY"); - set => SetValue ("RELEASECOUNTRY", value); + set => SetValueProperty ("RELEASECOUNTRY", value, MusicBrainzReleaseCountry); } /// public override string? ComposerSort { get => GetValue ("COMPOSERSORT"); - set => SetValue ("COMPOSERSORT", value); + set => SetValueProperty ("COMPOSERSORT", value, ComposerSort); } /// public override string? DateTagged { get => GetValue ("DATETAGGED"); - set => SetValue ("DATETAGGED", value); + set => SetValueProperty ("DATETAGGED", value, DateTagged); } /// public override string? Description { get => GetValue ("DESCRIPTION"); - set => SetValue ("DESCRIPTION", value); + set => SetValueProperty ("DESCRIPTION", value, Description); } /// public override string? AmazonId { get => GetValue ("ASIN"); - set => SetValue ("ASIN", value); + set => SetValueProperty ("ASIN", value, AmazonId); } /// public override string? AcoustIdId { get => GetValue ("ACOUSTID_ID"); - set => SetValue ("ACOUSTID_ID", value); + set => SetValueProperty ("ACOUSTID_ID", value, AcoustIdId); } /// public override string? AcoustIdFingerprint { get => GetValue ("ACOUSTID_FINGERPRINT"); - set => SetValue ("ACOUSTID_FINGERPRINT", value); + set => SetValueProperty ("ACOUSTID_FINGERPRINT", value, AcoustIdFingerprint); } /// public override string? PodcastFeedUrl { get => GetValue ("PODCASTFEEDURL"); - set => SetValue ("PODCASTFEEDURL", value); + set => SetValueProperty ("PODCASTFEEDURL", value, PodcastFeedUrl); } /// @@ -712,7 +712,7 @@ public override uint? TotalDiscs { /// public override string? DiscSubtitle { get => GetValue ("DISCSUBTITLE"); - set => SetValue ("DISCSUBTITLE", value); + set => SetValueProperty ("DISCSUBTITLE", value, DiscSubtitle); } /// @@ -919,25 +919,53 @@ public void SetValue (string name, string? value) AddField (name, value); } + /// + /// Writes a single-value property. Writing back the value its getter returned is a no-op, so + /// a field that appears more than once (https://xiph.org/vorbis/doc/v-comment.html allows + /// repeated names) keeps every value. Any other value replaces them all; null removes them. + /// + void SetValueProperty (string name, string? value, string? current) + { + if (value is not null && string.Equals (value, current, StringComparison.Ordinal)) + return; + SetValue (name, value); + } + + /// + /// The first value of , or of when the first is + /// missing or empty. An empty field is a valid comment (https://xiph.org/vorbis/doc/v-comment.html), + /// but it must not hide a filled fallback. Returns "" when the only fields present are empty. + /// + string? GetValueOrFallback (string name, string fallback) + { + var primary = GetValue (name); + if (!string.IsNullOrEmpty (primary)) + return primary; + + var secondary = GetValue (fallback); + return string.IsNullOrEmpty (secondary) ? primary ?? secondary : secondary; + } + /// /// Sets a field whose getter falls back to . - /// A null or empty value clears the fallback too, so it cannot come back. - /// The value the getter already returns is a no-op, so neither field is lost. + /// The value the getter already returns is a no-op, so neither field is lost; that includes "", + /// which the getter returns only when every field present is empty. + /// Otherwise a null or empty value clears the fallback too, so it cannot come back. /// Any other value goes to , and to /// when that field exists and gives a value for it. /// void SetValueWithFallback (string name, string? value, string fallback, Func toFallback) { + var current = GetValueOrFallback (name, fallback); + if (value is not null && string.Equals (current, value, StringComparison.Ordinal)) + return; + if (string.IsNullOrEmpty (value)) { RemoveAll (fallback); SetValue (name, value); return; } - var current = GetValue (name) ?? GetValue (fallback); - if (string.Equals (current, value, StringComparison.Ordinal)) - return; - SetValue (name, value); if (GetValue (fallback) is null) return; diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs new file mode 100644 index 00000000..997c07ae --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs @@ -0,0 +1,170 @@ +// 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; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// An editor that writes back the value a property returned must not change the tag. +/// An APEv2 text item may hold several values separated by a zero byte, so a write-back +/// must not collapse or comma-join the list. +/// +[TestClass] +[TestCategory ("Unit")] +public class ApeTagWriteBackTests +{ + static readonly string[] ListFields = ["Artist", "AlbumArtist", "Composer", "Genre"]; + + static IEnumerable StringProperties () => + typeof (ApeTag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.PropertyType == typeof (string) && p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0); + + static ApeTag Reparse (ApeTag tag) + { + var result = ApeTag.Parse (tag.RenderWithOptions (includeHeader: true).Span); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } + + /// + /// The items of a rendered tag as key=raw value, in order. Item layout per APEv2: value size (4, LE), + /// flags (4), key (ASCII, NUL-terminated), value. + /// + static List Snapshot (ApeTag tag) + { + var data = tag.Render ().ToArray (); + var rows = new List (); + var pos = 0; + var end = data.Length - 32; + while (pos < end) { + var size = BitConverter.ToInt32 (data, pos); + var flags = BitConverter.ToInt32 (data, pos + 4); + var keyEnd = Array.IndexOf (data, (byte)0, pos + 8); + var key = Encoding.ASCII.GetString (data, pos + 8, keyEnd - pos - 8); + var value = Encoding.UTF8.GetString (data, keyEnd + 1, size); + rows.Add ($"{key}/{flags}={value}"); + pos = keyEnd + 1 + size; + } + rows.Sort (StringComparer.Ordinal); + return rows; + } + + static string? SingleKey (ApeTag tag) + { + var rows = Snapshot (tag); + if (rows.Count != 1) + return null; + return rows[0].Substring (0, rows[0].IndexOf ('/', StringComparison.Ordinal)); + } + + [TestMethod] + [DataRow ("V1\0V2")] + [DataRow ("\0V2")] + [DataRow ("")] + public void EveryStringProperty_UnchangedWriteBack_KeepsTheItem (string raw) + { + var covered = new List (); + var failures = new List (); + foreach (var property in StringProperties ()) { + var probe = new ApeTag (); + property.SetValue (probe, "V1"); + var key = SingleKey (probe); + if (key is null || !Equals (property.GetValue (probe), "V1")) + continue; + covered.Add (property.Name); + + var tag = new ApeTag (); + tag.SetValue (key, raw); + tag = Reparse (tag); + var before = Snapshot (tag); + + property.SetValue (tag, property.GetValue (tag)); + var after = Snapshot (Reparse (tag)); + + if (!before.SequenceEqual (after)) + failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + } + + Assert.IsEmpty (failures, string.Join ("\n", failures).Replace ("\0", "\\0", StringComparison.Ordinal)); + foreach (var name in ListFields) + Assert.Contains (name, covered); + Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); + } + + [TestMethod] + public void ListFields_UnchangedWriteBack_KeepBothNames () + { + var tag = new ApeTag (); + tag.Performers = ["P1", "P2"]; + tag.AlbumArtists = ["A1", "A2"]; + tag.Composers = ["C1", "C2"]; + tag.Genres = ["Rock", "Pop"]; + tag = Reparse (tag); + + tag.Artist = tag.Artist; + tag.AlbumArtist = tag.AlbumArtist; + tag.Composer = tag.Composer; + tag.Genre = tag.Genre; + var reparsed = Reparse (tag); + + Assert.AreEqual ("P1|P2", string.Join ("|", reparsed.Performers)); + Assert.AreEqual ("A1|A2", string.Join ("|", reparsed.AlbumArtists)); + Assert.AreEqual ("C1|C2", string.Join ("|", reparsed.Composers)); + Assert.AreEqual ("Rock|Pop", string.Join ("|", reparsed.Genres)); + } + + [TestMethod] + public void AlbumArtist_WriteBackFromAliasItem_KeepsAliasList () + { + var tag = new ApeTag (); + tag.SetValue ("ALBUMARTIST", "A1\0A2"); + tag = Reparse (tag); + Assert.AreEqual ("A1", tag.AlbumArtist); + + tag.AlbumArtist = tag.AlbumArtist; + + var reparsed = Reparse (tag); + Assert.AreEqual ("A1|A2", string.Join ("|", reparsed.AlbumArtists)); + Assert.AreEqual ("A1, A2", reparsed.GetValue ("ALBUMARTIST")); + } + + [TestMethod] + public void ListFields_NewValueOrClear_StillReplacesTheList () + { + var tag = new ApeTag (); + tag.Performers = ["P1", "P2"]; + tag.Genres = ["Rock", "Pop"]; + tag.Composers = ["C1", "C2"]; + + tag.Artist = "P3"; + tag.Genre = null; + tag.Composer = ""; + + Assert.AreEqual ("P3", string.Join ("|", tag.Performers)); + Assert.IsEmpty (tag.Genres); + Assert.IsEmpty (tag.Composers); + } + + [TestMethod] + public void Year_EmptyYearItem_WriteBackKeepsDate () + { + var tag = new ApeTag (); + tag.SetValue ("Year", ""); + tag.SetValue ("Date", "2001-05-03"); + tag = Reparse (tag); + Assert.AreEqual ("2001-05-03", tag.Year); + + tag.Year = tag.Year; + + var reparsed = Reparse (tag); + Assert.AreEqual ("2001-05-03", reparsed.GetValue ("Date")); + Assert.AreEqual ("", reparsed.GetValue ("Year")); + + reparsed.Year = ""; + Assert.IsNull (reparsed.GetValue ("Year")); + Assert.IsNull (reparsed.GetValue ("Date")); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs new file mode 100644 index 00000000..66e0f405 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.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.Reflection; +using TagLibSharp2.Id3.Id3v2; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// An editor that writes back the value a property returned must not change the tag. +/// A single-value getter returns the first value of an ID3v2.4 multi-value text frame +/// (NUL-separated, ID3v2.4 §4.2), so a write-back must not collapse the list. +/// +[TestClass] +[TestCategory ("Unit")] +public class Id3v2WriteBackTests +{ + static readonly string[] ListFields = ["Artist", "AlbumArtist", "Composer", "Genre"]; + + /// + /// Every settable string property on . + /// + static IEnumerable StringProperties () => + typeof (Id3v2Tag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.PropertyType == typeof (string) && p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0); + + static Id3v2Tag Reparse (Id3v2Tag tag) + { + var result = Id3v2Tag.Read (tag.Render ().Span); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } + + static List Snapshot (Id3v2Tag tag) + { + var rows = new List (); + foreach (var f in tag.Frames) + rows.Add (f.Id + "=" + f.Text); + foreach (var f in tag.UserTextFrames) + rows.Add ("TXXX:" + f.Description + "=" + f.Value); + return rows; + } + + /// + /// Builds a tag in which every text and TXXX frame the property writes holds . + /// Returns null when the property does not store "V1" in a text or TXXX frame. + /// + static Id3v2Tag? BuildMultiValue (PropertyInfo property, Id3v2Version version, string raw) + { + var tag = new Id3v2Tag (version); + property.SetValue (tag, "V1"); + var touched = tag.Frames.Count + tag.UserTextFrames.Count; + if (touched == 0 || !Equals (property.GetValue (tag), "V1")) + return null; + + foreach (var f in tag.Frames) + f.Text = raw; + foreach (var f in tag.UserTextFrames) + f.Value = raw; + return Reparse (tag); + } + + [TestMethod] + [DataRow (Id3v2Version.V23, "V1\0V2")] + [DataRow (Id3v2Version.V24, "V1\0V2")] + [DataRow (Id3v2Version.V23, "\0V2")] + [DataRow (Id3v2Version.V24, "\0V2")] + public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue (Id3v2Version version, string raw) + { + var covered = new List (); + var failures = new List (); + foreach (var property in StringProperties ()) { + var tag = BuildMultiValue (property, version, raw); + if (tag is null) + continue; + covered.Add (property.Name); + + var before = Snapshot (tag); + property.SetValue (tag, property.GetValue (tag)); + var after = Snapshot (Reparse (tag)); + + if (!before.SequenceEqual (after)) + failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + } + + Assert.IsEmpty (failures, string.Join ("\n", failures).Replace ("\0", "\\0", StringComparison.Ordinal)); + foreach (var name in ListFields) + Assert.Contains (name, covered); + Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); + } + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void ListFields_UnchangedWriteBack_KeepBothNames (Id3v2Version version) + { + var tag = new Id3v2Tag (version); + tag.Performers = ["P1", "P2"]; + tag.AlbumArtists = ["A1", "A2"]; + tag.Composers = ["C1", "C2"]; + tag.Genres = ["Rock", "Pop"]; + tag = Reparse (tag); + + tag.Artist = tag.Artist; + tag.AlbumArtist = tag.AlbumArtist; + tag.Composer = tag.Composer; + tag.Genre = tag.Genre; + var reparsed = Reparse (tag); + + Assert.AreEqual ("P1|P2", string.Join ("|", reparsed.Performers)); + Assert.AreEqual ("A1|A2", string.Join ("|", reparsed.AlbumArtists)); + Assert.AreEqual ("C1|C2", string.Join ("|", reparsed.Composers)); + Assert.AreEqual ("Rock|Pop", string.Join ("|", reparsed.Genres)); + } + + [TestMethod] + public void Genre_WriteBackOfDisplayName_KeepsNumericGenreList () + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.SetTextFrameValues ("TCON", ["17", "Pop"]); + tag = Reparse (tag); + Assert.AreEqual ("Rock", tag.Genre); + + tag.Genre = tag.Genre; + + var reparsed = Reparse (tag); + Assert.AreEqual ("17|Pop", string.Join ("|", reparsed.GetTextFrameValues ("TCON").ToArray ())); + } + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void ListFields_NewValue_StillReplacesTheList (Id3v2Version version) + { + var tag = new Id3v2Tag (version); + tag.Performers = ["P1", "P2"]; + tag.Genres = ["Rock", "Pop"]; + + tag.Artist = "P3"; + tag.Genre = "Jazz"; + + var reparsed = Reparse (tag); + Assert.AreEqual ("P3", string.Join ("|", reparsed.Performers)); + Assert.AreEqual ("Jazz", string.Join ("|", reparsed.Genres)); + } + + [TestMethod] + public void ListFields_Clear_StillRemovesTheFrame () + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.Performers = ["P1", "P2"]; + tag.Composers = ["C1", "C2"]; + + tag.Artist = null; + tag.Composer = ""; + + Assert.IsNull (tag.GetTextFrame ("TPE1")); + Assert.IsNull (tag.GetTextFrame ("TCOM")); + } + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void MovementIndex_UnchangedWriteBack_DoesNotAddTxxxFrames (Id3v2Version version) + { + var result = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("MVIN", "2/4", (byte)version)); + Assert.IsTrue (result.IsSuccess, result.Error); + var tag = result.Tag!; + var before = Snapshot (tag); + + tag.MovementNumber = tag.MovementNumber; + tag.MovementTotal = tag.MovementTotal; + + CollectionAssert.AreEqual (before, Snapshot (tag)); + } + + [TestMethod] + public void Movement_WriteBackOfTxxxOnlyName_DoesNotAddAppleFrame () + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.SetUserText ("MOVEMENT", "Allegro"); + + tag.Movement = tag.Movement; + + Assert.IsNull (tag.GetTextFrame ("MVNM")); + Assert.AreEqual ("Allegro", tag.GetUserText ("MOVEMENT")); + } + + [TestMethod] + [DataRow ("\0Pop")] + [DataRow ("")] + public void Genre_EmptyFirstValue_ReadsEmptyAndWriteBackKeepsFrame (string raw) + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.Genre = "Rock"; + tag.Frames.First (f => f.Id == "TCON").Text = raw; + + Assert.AreEqual ("", tag.Genre); + tag.Genre = tag.Genre; + Assert.AreEqual (raw, tag.Frames.First (f => f.Id == "TCON").Text); + + tag.Genre = null; + Assert.IsNull (tag.GetTextFrame ("TCON")); + } + + [TestMethod] + public void Movement_EmptyAppleFrame_WriteBackKeepsTxxxName () + { + var tag = new Id3v2Tag (Id3v2Version.V24); + tag.Movement = "Allegro"; + tag.Frames.First (f => f.Id == "MVNM").Text = ""; + tag = Reparse (tag); + Assert.AreEqual ("Allegro", tag.Movement); + + tag.Movement = tag.Movement; + + var reparsed = Reparse (tag); + Assert.AreEqual ("Allegro", reparsed.GetUserText ("MOVEMENT")); + Assert.AreEqual ("Allegro", reparsed.Movement); + } + + [TestMethod] + [DataRow (Id3v2Version.V24, "TDOR", "", "TORY", "1999", "1999")] + [DataRow (Id3v2Version.V24, "TDOR", "abc", "TORY", "1999", "1999")] + [DataRow (Id3v2Version.V23, "TORY", "", "TDOR", "1999-05-01", "1999-05-01")] + [DataRow (Id3v2Version.V24, "TDOR", "1999-05-01", "TORY", "1999", "1999-05-01")] + public void OriginalReleaseDate_UnchangedWriteBack_KeepsBothFrames ( + Id3v2Version version, string primary, string primaryText, string other, string otherText, string expected) + { + var tag = new Id3v2Tag (version); + tag.SetTextFrameValues (primary, ["placeholder"]); + tag.SetTextFrameValues (other, [otherText]); + tag.Frames.First (f => f.Id == primary).Text = primaryText; + tag = Reparse (tag); + Assert.AreEqual (expected, tag.OriginalReleaseDate); + var before = Snapshot (tag); + + tag.OriginalReleaseDate = tag.OriginalReleaseDate; + + CollectionAssert.AreEqual (before, Snapshot (Reparse (tag))); + } +} diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs index c9833e79..6c88fc99 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -483,6 +483,51 @@ public void PicardTags_UnchangedWriteBack_KeepsEveryField () AssertSingle (tag, "ORIGINALYEAR", "1969"); } + [TestMethod] + [DataRow ("MOVEMENT", "MOVEMENTNAME", "Allegro")] + [DataRow ("ORIGINALDATE", "ORIGINALYEAR", "1969")] + public void EmptyPrimary_UnchangedWriteBack_KeepsBothFields (string primary, string fallback, string fallbackValue) + { + // An empty field is a valid comment (xiph.org/vorbis/doc/v-comment.html: NAME=value, any length), + // but it must not hide the filled fallback, and writing back what was read must not clear it. + var comment = new VorbisComment ("test"); + comment.AddField (primary, ""); + comment.AddField (fallback, fallbackValue); + var property = primary == "MOVEMENT" ? nameof (VorbisComment.Movement) : nameof (VorbisComment.OriginalReleaseDate); + var info = typeof (VorbisComment).GetProperty (property)!; + Assert.AreEqual (fallbackValue, info.GetValue (comment)); + + info.SetValue (comment, info.GetValue (comment)); + + var reparsed = VorbisComment.Read (comment.Render ().Span); + Assert.IsTrue (reparsed.IsSuccess, reparsed.Error); + AssertSingle (reparsed.Tag!, primary, ""); + AssertSingle (reparsed.Tag!, fallback, fallbackValue); + + // An explicit empty value is not what the getter returned, so it is still a clear. + info.SetValue (comment, ""); + AssertSingle (comment, primary, ""); + Assert.HasCount (0, comment.GetValues (fallback)); + } + + [TestMethod] + [DataRow ("MOVEMENT", "MOVEMENTNAME")] + [DataRow ("ORIGINALDATE", "ORIGINALYEAR")] + public void EmptyFieldsOnly_ReadEmptyAndWriteBackKeepsThem (string primary, string fallback) + { + var comment = new VorbisComment ("test"); + comment.AddField (primary, ""); + comment.AddField (fallback, ""); + var property = primary == "MOVEMENT" ? nameof (VorbisComment.Movement) : nameof (VorbisComment.OriginalReleaseDate); + var info = typeof (VorbisComment).GetProperty (property)!; + Assert.AreEqual ("", info.GetValue (comment)); + + info.SetValue (comment, info.GetValue (comment)); + + AssertSingle (comment, primary, ""); + AssertSingle (comment, fallback, ""); + } + [TestMethod] public void FallbackOnly_UnchangedWriteBack_KeepsFallbackField () { diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs new file mode 100644 index 00000000..fe0aa487 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs @@ -0,0 +1,83 @@ +// 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.Xiph; + +namespace TagLibSharp2.Tests.Xiph; + +/// +/// An editor that writes back the value a property returned must not change the comment. +/// A field name may repeat (https://xiph.org/vorbis/doc/v-comment.html), and the single-value +/// getter returns the first, so a write-back must not drop the others. +/// +[TestClass] +[TestCategory ("Unit")] +public class VorbisCommentWriteBackTests +{ + static readonly string[] ListFields = ["Artist", "AlbumArtist", "Composer", "Genre"]; + + static IEnumerable StringProperties () => + typeof (VorbisComment).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.PropertyType == typeof (string) && p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0); + + static VorbisComment Reparse (VorbisComment comment) + { + var result = VorbisComment.Read (comment.Render ().Span); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } + + static List Snapshot (VorbisComment comment) => + comment.Fields.Select (f => f.Name + "=" + f.Value).ToList (); + + [TestMethod] + [DataRow ("V1", "V2")] + [DataRow ("", "V2")] + public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField (string first, string second) + { + var covered = new List (); + var failures = new List (); + foreach (var property in StringProperties ()) { + var probe = new VorbisComment ("test"); + property.SetValue (probe, "V1"); + if (probe.Fields.Count != 1 || !Equals (property.GetValue (probe), "V1")) + continue; + var name = probe.Fields[0].Name; + covered.Add (property.Name); + + var comment = new VorbisComment ("test"); + comment.AddField (name, first); + comment.AddField (name, second); + comment = Reparse (comment); + var before = Snapshot (comment); + + property.SetValue (comment, property.GetValue (comment)); + var after = Snapshot (Reparse (comment)); + + if (!before.SequenceEqual (after)) + failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + } + + Assert.IsEmpty (failures, string.Join ("\n", failures)); + foreach (var name in ListFields) + Assert.Contains (name, covered); + Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); + } + + [TestMethod] + public void Genre_NewValueOrClear_StillReplacesEveryField () + { + var comment = new VorbisComment ("test"); + comment.AddField ("GENRE", "Rock"); + comment.AddField ("GENRE", "Pop"); + comment.AddField ("ARTIST", "P1"); + comment.AddField ("ARTIST", "P2"); + + comment.Genre = "Jazz"; + comment.Artist = null; + + Assert.AreEqual ("Jazz", string.Join ("|", comment.GetValues ("GENRE"))); + Assert.HasCount (0, comment.GetValues ("ARTIST")); + } +} From a5f248d8ccd1b358cdb74f4487be13efdc53bdd0 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 12:09:59 -0700 Subject: [PATCH 13/29] docs: Describe the write-back rule for single-value names --- CHANGELOG.md | 5 +++-- src/TagLibSharp2/Core/Tag.cs | 8 ++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f04c7e78..8901213f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,10 +39,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. +- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value, and an empty one stays. This covers every text and TXXX property in ID3v2 (artist, album artist, composer, genre, title, MusicBrainz IDs, ...), the ID3v2 movement number and total, every text property in APE, and every text field in Vorbis Comments. Any other value still replaces the list. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. -- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. +- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year`, `ORIGINALDATE`, or `MOVEMENT` no longer hides a filled `Date`, `ORIGINALYEAR`, or `MOVEMENTNAME`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. - An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. -- Setting or clearing an ID3v2 original release date removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. +- Setting a new ID3v2 original release date, or clearing it, removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. Writing back the date already read changes nothing. ## [0.6.0] - 2026-01-05 diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 63561b67..c8e29c3c 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -101,7 +101,8 @@ public abstract class Tag /// Gets or sets the primary artist/performer. /// /// - /// This returns the first performer. For multiple performers, use . + /// 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 replaces the list. /// Format-specific limitations: /// /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). @@ -197,7 +198,8 @@ public virtual string[] Performers { /// Gets or sets the genre name. /// /// - /// This returns the first genre. For multiple genres, use . + /// 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 replaces the list. /// Format-specific limitations: /// /// ID3v1: Single genre only, must match one of 192 predefined genres. Custom genres not supported. @@ -244,6 +246,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 replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? AlbumArtist { get => null; set { } } @@ -282,6 +285,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 replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? Composer { get => null; set { } } From 4c0a6d506aeeef558837a5ea3bb3bb42a8b1b753 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 13:07:37 -0700 Subject: [PATCH 14/29] fix: Let CopyTo replace a list and "" clear one with text The write-back no-op compared the copied value with the target's first value, so a copy into a Picard-style tag left the target's other labels, ISRCs, catalog numbers, artists, and genres in place. CopyTo now turns the no-op off on its thread while it writes, which also covers tags a wrapper forwards to, so the target holds exactly the source value. The rule lives in one place, Tag.IsWriteBack. An empty string counted as a write-back whenever the getter read "", so "" no longer cleared an ID3v2 frame or Vorbis field whose first value is empty and whose later values hold text. It is now a write-back only when no value holds text, which is when the APE getter reads "" too. The ID3v2 year, podcast feed URL, and MusicBrainz recording ID setters get the same guard, so a v2.3 year write-back no longer rewrites TYER as UTF-8. A case-only edit and a null over a field that reads null are pinned as writes. --- src/TagLibSharp2/Ape/ApeTag.cs | 15 +- src/TagLibSharp2/Core/Tag.cs | 41 +++- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 77 ++++-- src/TagLibSharp2/Xiph/VorbisComment.cs | 36 ++- .../Ape/ApeTagWriteBackTests.cs | 44 +++- .../Core/TagCopyReplacesListTests.cs | 222 ++++++++++++++++++ .../Id3/Id3v2/Id3v2WriteBackTests.cs | 122 +++++++++- .../Xiph/VorbisCommentWriteBackTests.cs | 50 +++- 8 files changed, 553 insertions(+), 54 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 3351bd58..c9d9124d 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -245,7 +245,7 @@ public override string? Year { return string.IsNullOrEmpty (date) ? year ?? date : date; } set { - if (IsUnchanged (value, Year)) + if (IsWriteBack (value, Year)) return; if (string.IsNullOrEmpty (value)) { @@ -920,21 +920,16 @@ public void SetBinaryItem (string key, string filename, byte[] data) /// /// Writes a single-value property. Writing back the value its getter returned is a no-op, so a /// text item that holds several values (APEv2 items separate them with a zero byte), an empty item, - /// or the alias item the getter read stays as it is. Any other value goes through . + /// or the alias item the getter read stays as it is (). + /// Any other value goes through . The getters skip empty values, so they return "" + /// only when no value holds text, and "" over a list with text is not a write-back. /// void SetOrRemoveProperty (string key, string? value, string? current, string? alias = null) { - if (!IsUnchanged (value, current)) + if (!IsWriteBack (value, current)) SetOrRemove (key, value, alias); } - /// - /// True when is exactly what the getter returned, including an empty string. - /// A null value is always a clear. - /// - static bool IsUnchanged (string? value, string? current) => - value is not null && string.Equals (value, current, StringComparison.Ordinal); - /// /// Removes an item by key. /// diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index c8e29c3c..34948826 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -80,6 +80,23 @@ public enum TagTypes /// public abstract class Tag { + [ThreadStatic] + static int t_copyDepth; + + /// + /// True when a setter is handed exactly the value its getter returned, compared ordinally, as when an + /// editor writes back what it read. The setter then leaves the tag alone, so the other values of a + /// multi-value field and any fallback field stay. Never true for null, which always clears, or while + /// runs on this thread: a copy replaces the target's value even when it equals the + /// target's first value. + /// + internal static bool IsWriteBack (string? value, string? current) => + t_copyDepth == 0 && value is not null && string.Equals (value, current, StringComparison.Ordinal); + + /// + internal static bool IsWriteBack (uint? value, uint? current) => + t_copyDepth == 0 && value is not null && value == current; + /// /// Gets the type of tag represented by this instance. /// @@ -102,7 +119,7 @@ public abstract class Tag /// /// /// 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 replaces the list. + /// 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. /// Format-specific limitations: /// /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). @@ -199,7 +216,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 replaces the list. + /// 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. /// Format-specific limitations: /// /// ID3v1: Single genre only, must match one of 192 predefined genres. Custom genres not supported. @@ -246,7 +263,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 replaces the list. + /// 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. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? AlbumArtist { get => null; set { } } @@ -285,7 +302,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 replaces the list. + /// 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. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? Composer { get => null; set { } } @@ -1162,7 +1179,9 @@ public virtual ValidationResult Validate () /// /// /// Only non-null values are copied. The target tag's existing values are overwritten - /// for any property that has a non-null value in the source. + /// for any property that has a non-null value in the source. A source value that equals the + /// target's first value still replaces the target's list: the setters' write-back no-op does not + /// apply during a copy. /// /// /// This is useful for converting between tag formats or synchronizing metadata @@ -1200,6 +1219,18 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) ArgumentNullException.ThrowIfNull (target); #endif + // A copy makes the target hold the source's value, so the write-back no-op in the setters + // (IsWriteBack) is off for the duration, also for tags a wrapper target forwards to. + t_copyDepth++; + try { + CopyValuesTo (target, options); + } finally { + t_copyDepth--; + } + } + + void CopyValuesTo (Tag target, TagCopyOptions options) + { // Basic metadata (always copied unless explicitly excluded) if ((options & TagCopyOptions.Basic) != 0) { if (Title is not null) diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 040e49b9..4b3eea15 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -220,7 +220,11 @@ public override string? Album { /// public override string? Year { get => NormalizeYear (Version == 4 ? GetTextFrame ("TDRC") : GetTextFrame ("TYER")); - set => SetDateFrame (Version == 4 ? "TDRC" : "TYER", value, Version == 4, keepMatchingYear: Version == 4); + set { + if (IsWriteBack (value, Year)) + return; + SetDateFrame (Version == 4 ? "TDRC" : "TYER", value, Version == 4, keepMatchingYear: Version == 4); + } } /// @@ -262,7 +266,7 @@ public override string? OriginalReleaseDate { return NormalizeYear (GetTextFrame ("TORY")) ?? NormalizeReleaseTimestamp (GetTextFrame ("TDOR")); } set { - if (IsUnchanged (value, OriginalReleaseDate)) + if (IsWriteBack (value, OriginalReleaseDate)) return; SetDateFrame ( Version == 4 ? "TDOR" : "TORY", @@ -622,7 +626,10 @@ public override bool IsCompilation { /// public override string? PodcastFeedUrl { get => GetUrl ("WFED"); - set => SetUrl ("WFED", value); + set { + if (!IsWriteBack (value, PodcastFeedUrl)) + SetUrl ("WFED", value); + } } /// @@ -1013,7 +1020,7 @@ public override string? Movement { return string.IsNullOrEmpty (user) ? apple ?? user : user; } set { - if (IsUnchanged (value, Movement)) + if (IsTextWriteBack (value, Movement, GetRawTextFrame ("MVNM"), GetRawUserText ("MOVEMENT"))) return; SetTextFrame ("MVNM", value); SetUserText ("MOVEMENT", value); @@ -1040,7 +1047,7 @@ public override uint? MovementNumber { return uint.TryParse (value, out var result) ? result : null; } set { - if (value is not null && value == MovementNumber) + if (IsWriteBack (value, MovementNumber)) return; var total = MovementTotal; SetUserText ("MOVEMENTNUMBER", value?.ToString (CultureInfo.InvariantCulture)); @@ -1070,7 +1077,7 @@ public override uint? MovementTotal { return uint.TryParse (value, out var result) ? result : null; } set { - if (value is not null && value == MovementTotal) + if (IsWriteBack (value, MovementTotal)) return; var number = MovementNumber; SetUserText ("MOVEMENTTOTAL", value?.ToString (CultureInfo.InvariantCulture)); @@ -1213,6 +1220,8 @@ public void RemoveInvolvedPeopleFrames (string? frameId = null) public override string? MusicBrainzRecordingId { get => GetUniqueFileId (UniqueFileIdFrame.MusicBrainzOwner)?.IdentifierString; set { + if (IsWriteBack (value, MusicBrainzRecordingId)) + return; RemoveUniqueFileIds (UniqueFileIdFrame.MusicBrainzOwner); if (!string.IsNullOrEmpty (value)) _uniqueFileIdFrames.Add (new UniqueFileIdFrame (UniqueFileIdFrame.MusicBrainzOwner, value!)); @@ -1746,13 +1755,14 @@ void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatch } /// - /// Writes a single-value text property. Writing back the value its getter returned is a no-op, - /// so the other values of a multi-value frame (ID3v2.4 §4.2, NUL-separated) and an empty - /// first value stay as they are. Any other value replaces the frame; null or empty removes it. + /// Writes a single-value text property. Writing back the value its getter returned is a no-op + /// (), so the other values of a multi-value frame + /// (ID3v2.4 §4.2, NUL-separated) stay as they are. Any other value replaces the frame. Null removes it, + /// and so does an empty string unless every value in the frame is already empty. /// void SetTextFrameProperty (string frameId, string? value, string? current) { - if (!IsUnchanged (value, current)) + if (!IsTextWriteBack (value, current, GetRawTextFrame (frameId))) SetTextFrame (frameId, value); } @@ -1761,16 +1771,53 @@ void SetTextFrameProperty (string frameId, string? value, string? current) /// void SetUserTextProperty (string description, string? value, string? current) { - if (!IsUnchanged (value, current)) + if (!IsTextWriteBack (value, current, GetRawUserText (description))) SetUserText (description, value); } /// - /// True when is exactly what the getter returned, including an empty string. - /// A null value is always a clear. + /// , except that an empty string is a write-back only + /// when none of holds text. A getter returns "" for an empty first value + /// ("\0V2"), and "" over such a frame still clears it. + /// + static bool IsTextWriteBack (string? value, string? current, params string?[] stored) + { + if (!IsWriteBack (value, current)) + return false; + if (value!.Length != 0) + return true; + foreach (var text in stored) { + if (HasText (text)) + return false; + } + return true; + } + + /// + /// True when the stored text holds any character other than a NUL value separator. /// - static bool IsUnchanged (string? value, string? current) => - value is not null && string.Equals (value, current, StringComparison.Ordinal); + static bool HasText (string? text) + { + if (text is null) + return false; + for (var i = 0; i < text.Length; i++) { + if (text[i] != '\0') + return true; + } + return false; + } + + /// + /// The stored value of the first TXXX frame with this description, including NUL separators. + /// + string? GetRawUserText (string description) + { + for (var i = 0; i < _userTextFrames.Count; i++) { + if (string.Equals (_userTextFrames[i].Description, description, StringComparison.OrdinalIgnoreCase)) + return _userTextFrames[i].Value; + } + return null; + } /// /// Sets or creates a text frame. diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 6955c33b..06c86a0e 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -922,13 +922,34 @@ public void SetValue (string name, string? value) /// /// Writes a single-value property. Writing back the value its getter returned is a no-op, so /// a field that appears more than once (https://xiph.org/vorbis/doc/v-comment.html allows - /// repeated names) keeps every value. Any other value replaces them all; null removes them. + /// repeated names) keeps every value (). Any other value + /// replaces them all. Null removes them, and so does an empty string unless every value is already empty. /// void SetValueProperty (string name, string? value, string? current) { - if (value is not null && string.Equals (value, current, StringComparison.Ordinal)) - return; - SetValue (name, value); + if (!IsFieldWriteBack (value, current, name)) + SetValue (name, value); + } + + /// + /// , except that an empty string is a write-back only when + /// no field named in holds text. The getter returns "" for an empty first field + /// even when a later one has text, and "" over such fields still clears them. + /// + bool IsFieldWriteBack (string? value, string? current, params string[] names) + { + if (!IsWriteBack (value, current)) + return false; + if (value!.Length != 0) + return true; + foreach (var name in names) { + var upper = name.ToUpperInvariant (); + for (var i = 0; i < _fields.Count; i++) { + if (_fields[i].Name == upper && _fields[i].Value.Length != 0) + return false; + } + } + return true; } /// @@ -948,16 +969,15 @@ void SetValueProperty (string name, string? value, string? current) /// /// Sets a field whose getter falls back to . - /// The value the getter already returns is a no-op, so neither field is lost; that includes "", - /// which the getter returns only when every field present is empty. + /// The value the getter already returns is a no-op, so neither field is lost; "" counts only when + /// no field of either name holds text. /// Otherwise a null or empty value clears the fallback too, so it cannot come back. /// Any other value goes to , and to /// when that field exists and gives a value for it. /// void SetValueWithFallback (string name, string? value, string fallback, Func toFallback) { - var current = GetValueOrFallback (name, fallback); - if (value is not null && string.Equals (current, value, StringComparison.Ordinal)) + if (IsFieldWriteBack (value, GetValueOrFallback (name, fallback), name, fallback)) return; if (string.IsNullOrEmpty (value)) { diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs index 997c07ae..f1890555 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs @@ -64,7 +64,7 @@ static List Snapshot (ApeTag tag) [DataRow ("V1\0V2")] [DataRow ("\0V2")] [DataRow ("")] - public void EveryStringProperty_UnchangedWriteBack_KeepsTheItem (string raw) + public void EveryStringProperty_UnchangedWriteBack_KeepsTheItem_AndAnEditReplaces (string raw) { var covered = new List (); var failures = new List (); @@ -80,12 +80,23 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsTheItem (string raw) tag.SetValue (key, raw); tag = Reparse (tag); var before = Snapshot (tag); - - property.SetValue (tag, property.GetValue (tag)); + var read = (string?)property.GetValue (tag); + property.SetValue (tag, read); var after = Snapshot (Reparse (tag)); - if (!before.SequenceEqual (after)) + // "" is a write-back only when no value holds text: an empty first value reads "", + // and "" over a list with text clears it. + var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); + if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + + // A case-only edit, or "" over a list whose later values hold text, is not a write-back. + var current = (string?)property.GetValue (tag); + var edit = string.IsNullOrEmpty (current) ? "" : current!.ToLowerInvariant (); + property.SetValue (tag, edit); + var edited = Snapshot (Reparse (tag)); + if (edited.Any (r => r.Contains ("V2", StringComparison.Ordinal)) || (edit.Length != 0 && !Equals (property.GetValue (tag), edit))) + failures.Add ($"{property.Name} edit {edit}: [{string.Join (" | ", edited)}]"); } Assert.IsEmpty (failures, string.Join ("\n", failures).Replace ("\0", "\\0", StringComparison.Ordinal)); @@ -148,6 +159,31 @@ public void ListFields_NewValueOrClear_StillReplacesTheList () Assert.IsEmpty (tag.Composers); } + [TestMethod] + public void Null_OverAnItemThatReadsNull_StillRemovesIt () + { + // A binary Title reads null. Writing null is a clear, not a write-back of that null. + var tag = new ApeTag (); + tag.SetBinaryItem ("Title", "cover.bin", [1, 2, 3]); + Assert.IsNull (tag.Title); + + tag.Title = null; + + Assert.AreEqual (0, tag.ItemCount); + } + + [TestMethod] + public void EmptyString_OverAListWithText_ClearsIt () + { + var tag = new ApeTag (); + tag.SetValue ("Artist", "\0V2"); + Assert.AreEqual ("V2", tag.Artist); + + tag.Artist = ""; + + Assert.AreEqual (0, tag.ItemCount); + } + [TestMethod] public void Year_EmptyYearItem_WriteBackKeepsDate () { diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs new file mode 100644 index 00000000..7b94e5a0 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -0,0 +1,222 @@ +// 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.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A copy makes the target hold the source's value. The setters' write-back no-op must not fire +/// during , even when the source value equals the target's first value, +/// or the target keeps values the source does not have. +/// +[TestClass] +[TestCategory ("Unit")] +public class TagCopyReplacesListTests +{ + const string Stale = "Zq2"; + + static readonly string[] BasicFields = ["Title", "Artist", "Album", "Genre"]; + + static IEnumerable StringProperties () => + typeof (Tag).GetProperties (BindingFlags.Public | BindingFlags.Instance) + .Where (p => p.PropertyType == typeof (string) && p.CanRead && p.CanWrite && p.GetIndexParameters ().Length == 0); + + /// + /// A target whose field for holds "V1" and then , + /// or null when the format does not store "V1" for that property in a text field. + /// + static Tag? BuildTarget (string format, PropertyInfo property) + { + switch (format) { + case "id3v23": + case "id3v24": { + var tag = new Id3v2Tag (format == "id3v23" ? Id3v2Version.V23 : Id3v2Version.V24); + property.SetValue (tag, "V1"); + if (tag.Frames.Count + tag.UserTextFrames.Count == 0 || !Equals (property.GetValue (tag), "V1")) + return null; + foreach (var f in tag.Frames) + f.Text = "V1\0" + Stale; + foreach (var f in tag.UserTextFrames) + f.Value = "V1\0" + Stale; + return Id3v2Tag.Read (tag.Render ().Span).Tag; + } + case "ape": { + var probe = new ApeTag (); + property.SetValue (probe, "V1"); + if (probe.ItemCount != 1 || !Equals (property.GetValue (probe), "V1")) + return null; + var tag = new ApeTag (); + tag.SetValue (ApeKey (probe), "V1\0" + Stale); + return ApeTag.Parse (tag.RenderWithOptions (includeHeader: true).Span).Tag; + } + case "vorbis": { + var probe = new VorbisComment ("test"); + property.SetValue (probe, "V1"); + if (probe.Fields.Count != 1 || !Equals (property.GetValue (probe), "V1")) + return null; + var tag = new VorbisComment ("test"); + tag.AddField (probe.Fields[0].Name, "V1"); + tag.AddField (probe.Fields[0].Name, Stale); + return VorbisComment.Read (tag.Render ().Span).Tag; + } + default: + throw new ArgumentOutOfRangeException (nameof (format)); + } + } + + static string ApeKey (ApeTag tag) + { + // One item: value size (4, LE), flags (4), key (ASCII, NUL-terminated), value. + var data = tag.Render ().ToArray (); + var keyEnd = Array.IndexOf (data, (byte)0, 8); + return Encoding.ASCII.GetString (data, 8, keyEnd - 8); + } + + static Tag NewSource (string format) => format switch { + "id3v24" => new Id3v2Tag (Id3v2Version.V24), + "ape" => new ApeTag (), + _ => new VorbisComment ("source"), + }; + + /// + /// Whether CopyTo (All) writes this property at all: a different source value must arrive. + /// + static bool IsCopied (string sourceFormat, string targetFormat, PropertyInfo property) + { + var source = NewSource (sourceFormat); + property.SetValue (source, "V9"); + var target = BuildTarget (targetFormat, property)!; + source.CopyTo (target, TagCopyOptions.All); + return Equals (property.GetValue (target), "V9"); + } + + 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; + } + return false; + } + + [TestMethod] + [DataRow ("id3v23")] + [DataRow ("id3v24")] + [DataRow ("ape")] + [DataRow ("vorbis")] + public void CopyAll_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) + { + var covered = new List (); + var failures = new List (); + foreach (var sourceFormat in new[] { "id3v24", "ape", "vorbis" }) { + foreach (var property in StringProperties ()) { + var source = NewSource (sourceFormat); + property.SetValue (source, "V1"); + if (!Equals (property.GetValue (source), "V1")) + continue; + var target = BuildTarget (targetFormat, property); + if (target is null || !IsCopied (sourceFormat, targetFormat, property)) + continue; + covered.Add (property.Name); + + source.CopyTo (target, TagCopyOptions.All); + + if (!Equals (property.GetValue (target), "V1") || RenderHolds (target, Stale)) + failures.Add ($"{sourceFormat}->{targetFormat} {property.Name}: read {property.GetValue (target)}, stale kept={RenderHolds (target, Stale)}"); + } + } + + Assert.IsEmpty (failures, string.Join ("\n", failures)); + foreach (var name in new[] { "Artist", "Genre", "Publisher", "Isrc", "CatalogNumber", "MusicBrainzArtistId" }) + Assert.Contains (name, covered); + } + + [TestMethod] + [DataRow ("id3v23")] + [DataRow ("id3v24")] + [DataRow ("ape")] + [DataRow ("vorbis")] + public void CopyBasic_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) + { + var failures = new List (); + foreach (var sourceFormat in new[] { "id3v24", "ape", "vorbis" }) { + foreach (var name in BasicFields) { + var property = typeof (Tag).GetProperty (name)!; + var source = NewSource (sourceFormat); + property.SetValue (source, "V1"); + var target = BuildTarget (targetFormat, property)!; + + source.CopyTo (target, TagCopyOptions.Basic); + + if (!Equals (property.GetValue (target), "V1") || RenderHolds (target, Stale)) + failures.Add ($"{sourceFormat}->{targetFormat} {name}"); + } + } + + Assert.IsEmpty (failures, string.Join ("\n", failures)); + } + + [TestMethod] + public void CopyBasic_IntoFlacFileTag_ReplacesTheList () + { + var file = FlacFile.Read (TestBuilders.Flac.CreateMinimal ()).File!; + var comment = new VorbisComment ("test"); + comment.AddField ("ARTIST", "P1"); + comment.AddField ("ARTIST", "P2"); + file.VorbisComment = comment; + var source = new Id3v2Tag (Id3v2Version.V24) { Artist = "P1" }; + + source.CopyTo (file.Tag!, TagCopyOptions.Basic); + + Assert.AreEqual ("P1", string.Join ("|", file.VorbisComment!.GetValues ("ARTIST"))); + } + + [TestMethod] + public void WriteBack_AfterACopy_IsANoOpAgain () + { + var target = new Id3v2Tag (Id3v2Version.V24); + target.SetTextFrameValues ("TPUB", ["Lab1", "Lab2"]); + new VorbisComment ("source") { Publisher = "Lab1" }.CopyTo (target, TagCopyOptions.All); + Assert.AreEqual ("Lab1", string.Join ("|", target.GetTextFrameValues ("TPUB"))); + + target.SetTextFrameValues ("TPUB", ["Lab1", "Lab2"]); + target.Publisher = target.Publisher; + + Assert.AreEqual ("Lab1|Lab2", string.Join ("|", target.GetTextFrameValues ("TPUB"))); + } + + [TestMethod] + public void CopyThatThrows_StillEndsTheCopyScope () + { + var source = new ThrowingTag (); + var target = new Id3v2Tag (Id3v2Version.V24); + + Assert.ThrowsExactly (() => source.CopyTo (target, TagCopyOptions.Basic)); + + target.SetTextFrameValues ("TPE1", ["P1", "P2"]); + target.Artist = target.Artist; + Assert.AreEqual ("P1|P2", string.Join ("|", target.GetTextFrameValues ("TPE1"))); + } + + sealed class ThrowingTag : Tag + { + public override TagTypes TagType => TagTypes.None; + public override string? Title { get => throw new InvalidOperationException (); set { } } + public override string? Artist { get => null; set { } } + public override string? Album { get => null; set { } } + public override string? Year { get => null; set { } } + public override string? Comment { get => null; set { } } + public override string? Genre { get => null; set { } } + public override uint? Track { get => null; set { } } + public override BinaryData Render () => BinaryData.Empty; + public override void Clear () { } + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs index 66e0f405..81b3ab68 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs @@ -65,7 +65,7 @@ static List Snapshot (Id3v2Tag tag) [DataRow (Id3v2Version.V24, "V1\0V2")] [DataRow (Id3v2Version.V23, "\0V2")] [DataRow (Id3v2Version.V24, "\0V2")] - public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue (Id3v2Version version, string raw) + public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue_AndAnEditReplaces (Id3v2Version version, string raw) { var covered = new List (); var failures = new List (); @@ -76,11 +76,23 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue (Id3v2Version covered.Add (property.Name); var before = Snapshot (tag); - property.SetValue (tag, property.GetValue (tag)); + var read = (string?)property.GetValue (tag); + property.SetValue (tag, read); var after = Snapshot (Reparse (tag)); - if (!before.SequenceEqual (after)) + // "" is a write-back only when no value holds text: the getter reports an empty first + // value as "", and "" over a list with text clears it, as in APE. + var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); + if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + + // A case-only edit, or "" over a list whose later values hold text, is not a write-back. + var current = (string?)property.GetValue (tag); + var edit = string.IsNullOrEmpty (current) ? "" : current!.ToLowerInvariant (); + property.SetValue (tag, edit); + var edited = Snapshot (Reparse (tag)); + if (edited.Any (r => r.Contains ("V2", StringComparison.Ordinal)) || (edit.Length != 0 && !Equals (property.GetValue (tag), edit))) + failures.Add ($"{property.Name} edit {edit}: [{string.Join (" | ", edited)}]"); } Assert.IsEmpty (failures, string.Join ("\n", failures).Replace ("\0", "\\0", StringComparison.Ordinal)); @@ -89,6 +101,95 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue (Id3v2Version Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); } + /// + /// Values a property may need before its getter reads them back: a name, a year, a date, a URL, an identifier. + /// + static readonly string[] Candidates = ["V1", "2001", "2001-05-03", "http://example.com/feed", "b10b5bd8-0000-4000-8000-000000000001"]; + + /// + /// COMM and USLT can hold several frames that differ by language and description; their single-value + /// setters replace that set and are outside the write-back rule. + /// + static readonly string[] NotWriteBackSafe = ["Comment", "Lyrics"]; + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void EveryStringProperty_WriteBackOfTheValueRead_IsByteIdentical (Id3v2Version version) + { + var failures = new List (); + var uncovered = new List (); + foreach (var property in StringProperties ()) { + Id3v2Tag? tag = null; + foreach (var candidate in Candidates) { + var probe = new Id3v2Tag (version); + property.SetValue (probe, candidate); + // A later frame, so a setter that rewrites its frame moves it and changes the bytes. + probe.SetTextFrameValues (property.Name == "Album" ? "TIT2" : "TALB", ["after"]); + probe = Reparse (probe); + if (Equals (property.GetValue (probe), candidate)) { + tag = probe; + break; + } + } + if (tag is null) { + uncovered.Add (property.Name); + continue; + } + if (NotWriteBackSafe.Contains (property.Name)) + continue; + + var before = tag.Render ().ToArray (); + property.SetValue (tag, property.GetValue (tag)); + if (!before.AsSpan ().SequenceEqual (tag.Render ().Span)) + failures.Add (property.Name); + } + + Assert.IsEmpty (failures, string.Join (",", failures)); + Assert.IsEmpty (uncovered, string.Join (",", uncovered)); + } + + [TestMethod] + public void Year_V23WriteBack_KeepsTheOriginalEncoding () + { + var result = Id3v2Tag.Read (TestBuilders.Id3v2.CreateTagWithTextFrame ("TYER", "2001", TestConstants.Id3v2.Version3)); + Assert.IsTrue (result.IsSuccess, result.Error); + var tag = result.Tag!; + var before = tag.Render ().ToArray (); + + tag.Year = tag.Year; + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + } + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void EmptyString_OverAListWithText_ClearsIt (Id3v2Version version) + { + var tag = new Id3v2Tag (version); + tag.Artist = "x"; + tag.Genre = "x"; + tag.Movement = "x"; + foreach (var f in tag.Frames) + f.Text = "\0V2"; + foreach (var f in tag.UserTextFrames) + f.Value = "\0V2"; + tag = Reparse (tag); + Assert.AreEqual ("", tag.Artist); + Assert.AreEqual ("", tag.Genre); + Assert.AreEqual ("", tag.Movement); + + tag.Artist = ""; + tag.Genre = ""; + tag.Movement = ""; + + Assert.IsNull (tag.GetTextFrame ("TPE1")); + Assert.IsNull (tag.GetTextFrame ("TCON")); + Assert.IsNull (tag.GetTextFrame ("MVNM")); + Assert.IsNull (tag.GetUserText ("MOVEMENT")); + } + [TestMethod] [DataRow (Id3v2Version.V23)] [DataRow (Id3v2Version.V24)] @@ -187,18 +288,23 @@ public void Movement_WriteBackOfTxxxOnlyName_DoesNotAddAppleFrame () } [TestMethod] - [DataRow ("\0Pop")] - [DataRow ("")] - public void Genre_EmptyFirstValue_ReadsEmptyAndWriteBackKeepsFrame (string raw) + public void Genre_EmptyFirstValue_ReadsEmpty () { + // An empty first value reads "", like every other text frame. Writing "" back keeps a frame + // whose values are all empty and clears one whose later values hold text. var tag = new Id3v2Tag (Id3v2Version.V24); tag.Genre = "Rock"; - tag.Frames.First (f => f.Id == "TCON").Text = raw; + tag.Frames.First (f => f.Id == "TCON").Text = ""; + Assert.AreEqual ("", tag.Genre); + tag.Genre = tag.Genre; + Assert.AreEqual ("", tag.Frames.First (f => f.Id == "TCON").Text); + tag.Frames.First (f => f.Id == "TCON").Text = "\0Pop"; Assert.AreEqual ("", tag.Genre); tag.Genre = tag.Genre; - Assert.AreEqual (raw, tag.Frames.First (f => f.Id == "TCON").Text); + Assert.IsNull (tag.GetTextFrame ("TCON")); + tag.Genre = "Rock"; tag.Genre = null; Assert.IsNull (tag.GetTextFrame ("TCON")); } diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs index fe0aa487..98fb8894 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs @@ -34,7 +34,7 @@ static List Snapshot (VorbisComment comment) => [TestMethod] [DataRow ("V1", "V2")] [DataRow ("", "V2")] - public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField (string first, string second) + public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField_AndAnEditReplaces (string first, string second) { var covered = new List (); var failures = new List (); @@ -51,12 +51,23 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField (string first comment.AddField (name, second); comment = Reparse (comment); var before = Snapshot (comment); - - property.SetValue (comment, property.GetValue (comment)); + var read = (string?)property.GetValue (comment); + property.SetValue (comment, read); var after = Snapshot (Reparse (comment)); - if (!before.SequenceEqual (after)) + // "" is a write-back only when no value holds text: an empty first value reads "", + // and "" over a list with text clears it. + var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); + if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); + + // A case-only edit, or "" over a list whose later values hold text, is not a write-back. + var current = (string?)property.GetValue (comment); + var edit = string.IsNullOrEmpty (current) ? "" : current!.ToLowerInvariant (); + property.SetValue (comment, edit); + var edited = Snapshot (Reparse (comment)); + if (edited.Any (r => r.Contains ("V2", StringComparison.Ordinal)) || (edit.Length != 0 && !Equals (property.GetValue (comment), edit))) + failures.Add ($"{property.Name} edit {edit}: [{string.Join (" | ", edited)}]"); } Assert.IsEmpty (failures, string.Join ("\n", failures)); @@ -65,6 +76,37 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField (string first Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); } + [TestMethod] + public void EmptyString_OverFieldsWithText_ClearsThem () + { + var comment = new VorbisComment ("test"); + comment.AddField ("ARTIST", ""); + comment.AddField ("ARTIST", "V2"); + comment.AddField ("MOVEMENT", ""); + comment.AddField ("MOVEMENT", "V2"); + comment.AddField ("MOVEMENTNAME", "N"); + Assert.AreEqual ("", comment.Artist); + + comment.Artist = ""; + comment.Movement = ""; + + Assert.AreEqual ("", string.Join ("|", comment.GetValues ("ARTIST"))); + Assert.AreEqual ("", string.Join ("|", comment.GetValues ("MOVEMENT"))); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + } + + [TestMethod] + public void EmptyString_OverEmptyFieldsOnly_IsAWriteBack () + { + var comment = new VorbisComment ("test"); + comment.AddField ("ARTIST", ""); + comment.AddField ("ARTIST", ""); + + comment.Artist = comment.Artist; + + Assert.HasCount (2, comment.GetValues ("ARTIST")); + } + [TestMethod] public void Genre_NewValueOrClear_StillReplacesEveryField () { From a971fade6a164ea2e199b8adfcc0fdc660ecf88b Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 13:07:37 -0700 Subject: [PATCH 15/29] docs: Say that CopyTo replaces and when an empty string clears --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8901213f..197e74e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,7 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value, and an empty one stays. This covers every text and TXXX property in ID3v2 (artist, album artist, composer, genre, title, MusicBrainz IDs, ...), the ID3v2 movement number and total, every text property in APE, and every text field in Vorbis Comments. Any other value still replaces the list. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. +- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value. The comparison is ordinal, so a case-only edit still writes. This covers every ID3v2 string property except `Comment` and `Lyrics` (COMM and USLT can hold several frames; their setters still replace them): every text and TXXX property including the year, the podcast feed URL, and the MusicBrainz recording ID, and the movement number and total. It also covers every text property in APE and every text field in Vorbis Comments. An empty string counts as the value read only when no value of the field holds text, so `= ""` still clears a list whose first value is empty. `null` always clears, and any other value still replaces the list. `CopyTo` always replaces: the target holds the source value afterwards, even when it equals the target's first value. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. - Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year`, `ORIGINALDATE`, or `MOVEMENT` no longer hides a filled `Date`, `ORIGINALYEAR`, or `MOVEMENTNAME`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. - An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. From a439d6591cd47d7eefb43b6820af868c81ee3a30 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 13:12:23 -0700 Subject: [PATCH 16/29] fix: Keep a fallback field when CopyTo writes the value it holds A copy of the value a Vorbis movement or original date already reads rewrote MOVEMENTNAME or ORIGINALYEAR to it, so copying one Picard tag into another set MOVEMENTNAME to the movement number. An APE year copy in the same way cut Date down to the year. The fallback is its own field, so a copy of the value read leaves it, as it did before the write-back rule, and only drops the other values of the primary field. --- src/TagLibSharp2/Ape/ApeTag.cs | 3 +- src/TagLibSharp2/Core/Tag.cs | 15 ++++++-- src/TagLibSharp2/Xiph/VorbisComment.cs | 25 ++++++++----- .../Core/TagCopyReplacesListTests.cs | 35 +++++++++++++++++++ 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index c9d9124d..02ed7f63 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -245,7 +245,8 @@ public override string? Year { return string.IsNullOrEmpty (date) ? year ?? date : date; } set { - if (IsWriteBack (value, Year)) + // The value read changes nothing, in a copy too: Date is its own item and keeps its full date. + if (IsValueRead (value, Year)) return; if (string.IsNullOrEmpty (value)) { diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 34948826..d871a28a 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -91,11 +91,22 @@ public abstract class Tag /// target's first value. /// internal static bool IsWriteBack (string? value, string? current) => - t_copyDepth == 0 && value is not null && string.Equals (value, current, StringComparison.Ordinal); + !IsCopying && IsValueRead (value, current); + + /// + /// True when is not null and equals ordinally. + /// + internal static bool IsValueRead (string? value, string? current) => + value is not null && string.Equals (value, current, StringComparison.Ordinal); + + /// + /// True while runs on this thread. + /// + internal static bool IsCopying => t_copyDepth > 0; /// internal static bool IsWriteBack (uint? value, uint? current) => - t_copyDepth == 0 && value is not null && value == current; + !IsCopying && value is not null && value == current; /// /// Gets the type of tag represented by this instance. diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 06c86a0e..7dc9d5b2 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -933,23 +933,25 @@ void SetValueProperty (string name, string? value, string? current) /// /// , except that an empty string is a write-back only when - /// no field named in holds text. The getter returns "" for an empty first field + /// no field named holds text. The getter returns "" for an empty first field /// even when a later one has text, and "" over such fields still clears them. /// - bool IsFieldWriteBack (string? value, string? current, params string[] names) + bool IsFieldWriteBack (string? value, string? current, string name) => + IsWriteBack (value, current) && (value!.Length != 0 || !HasText (name)); + + /// + /// True when any field with one of these names has a non-empty value. + /// + bool HasText (params string[] names) { - if (!IsWriteBack (value, current)) - return false; - if (value!.Length != 0) - return true; foreach (var name in names) { var upper = name.ToUpperInvariant (); for (var i = 0; i < _fields.Count; i++) { if (_fields[i].Name == upper && _fields[i].Value.Length != 0) - return false; + return true; } } - return true; + return false; } /// @@ -977,8 +979,13 @@ bool IsFieldWriteBack (string? value, string? current, params string[] names) /// void SetValueWithFallback (string name, string? value, string fallback, Func toFallback) { - if (IsFieldWriteBack (value, GetValueOrFallback (name, fallback), name, fallback)) + if (IsValueRead (value, GetValueOrFallback (name, fallback)) && (value!.Length != 0 || !HasText (name, fallback))) { + // The value read changes nothing, in a copy too: the fallback is its own field (Picard keeps + // MOVEMENTNAME beside a MOVEMENT number). A copy still drops the other values of name. + if (IsCopying && GetValues (name).Count > 1 && GetValue (name) == value) + SetValue (name, value); return; + } if (string.IsNullOrEmpty (value)) { RemoveAll (fallback); diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index 7b94e5a0..74e20cfc 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -179,6 +179,41 @@ public void CopyBasic_IntoFlacFileTag_ReplacesTheList () Assert.AreEqual ("P1", string.Join ("|", file.VorbisComment!.GetValues ("ARTIST"))); } + [TestMethod] + public void Copy_ValueEqualToTarget_KeepsTheTargetsFallbackFields () + { + // MOVEMENTNAME, ORIGINALYEAR, and APE Date are fields of their own beside the value the getter + // reads. A copy of that same value leaves them, and drops only other values of the primary field. + static VorbisComment Picard () + { + var c = new VorbisComment ("picard"); + c.AddField ("MOVEMENT", "2"); + c.AddField ("MOVEMENTNAME", "Allegro"); + c.AddField ("ORIGINALDATE", "1969-09-26"); + c.AddField ("ORIGINALYEAR", "1969"); + return c; + } + + var target = Picard (); + target.AddField ("MOVEMENT", "X"); + Picard ().CopyTo (target, TagCopyOptions.All); + Assert.AreEqual ("2", string.Join ("|", target.GetValues ("MOVEMENT"))); + Assert.AreEqual ("Allegro", string.Join ("|", target.GetValues ("MOVEMENTNAME"))); + Assert.AreEqual ("1969", string.Join ("|", target.GetValues ("ORIGINALYEAR"))); + + var nameOnly = new VorbisComment ("t"); + nameOnly.AddField ("MOVEMENTNAME", "Allegro"); + new VorbisComment ("s") { Movement = "Allegro" }.CopyTo (nameOnly, TagCopyOptions.All); + Assert.HasCount (0, nameOnly.GetValues ("MOVEMENT")); + Assert.AreEqual ("Allegro", nameOnly.GetValue ("MOVEMENTNAME")); + + var ape = new ApeTag (); + ape.SetValue ("Year", "2001"); + ape.SetValue ("Date", "2001-05-03"); + new ApeTag { Year = "2001" }.CopyTo (ape, TagCopyOptions.Basic); + Assert.AreEqual ("2001-05-03", ape.GetValue ("Date")); + } + [TestMethod] public void WriteBack_AfterACopy_IsANoOpAgain () { From 639267ca2645ff7ae44059b741e94b0ca18d3238 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 13:12:23 -0700 Subject: [PATCH 17/29] docs: Note that a copy keeps a fallback field of its own --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 197e74e0..0785071d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,7 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value. The comparison is ordinal, so a case-only edit still writes. This covers every ID3v2 string property except `Comment` and `Lyrics` (COMM and USLT can hold several frames; their setters still replace them): every text and TXXX property including the year, the podcast feed URL, and the MusicBrainz recording ID, and the movement number and total. It also covers every text property in APE and every text field in Vorbis Comments. An empty string counts as the value read only when no value of the field holds text, so `= ""` still clears a list whose first value is empty. `null` always clears, and any other value still replaces the list. `CopyTo` always replaces: the target holds the source value afterwards, even when it equals the target's first value. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. +- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value. The comparison is ordinal, so a case-only edit still writes. This covers every ID3v2 string property except `Comment` and `Lyrics` (COMM and USLT can hold several frames; their setters still replace them): every text and TXXX property including the year, the podcast feed URL, and the MusicBrainz recording ID, and the movement number and total. It also covers every text property in APE and every text field in Vorbis Comments. An empty string counts as the value read only when no value of the field holds text, so `= ""` still clears a list whose first value is empty. `null` always clears, and any other value still replaces the list. `CopyTo` always replaces: the target holds the source value afterwards, even when it equals the target's first value. A Vorbis `MOVEMENTNAME` or `ORIGINALYEAR` or an APE `Date` beside a value equal to the copied one is its own field and stays. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. - Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year`, `ORIGINALDATE`, or `MOVEMENT` no longer hides a filled `Date`, `ORIGINALYEAR`, or `MOVEMENTNAME`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. - An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. From c5762634a63ed8861ac40cf13f23001061645920 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 14:21:36 -0700 Subject: [PATCH 18/29] fix: Read the first non-empty value and copy from a snapshot A single-value getter read an empty first value as "", so writing it back counted as a clear and deleted the frame or field. ID3v2.4 stores several strings as a NUL-separated list and Vorbis field names repeat, so the getters now return the first non-empty value, and "" only when every value is empty. A write-back of what was read keeps the frame, and "" still clears it. This replaces reading a leading NUL as an empty first value. CopyTo now reads every source value before it writes any, skips a list the target already holds, and treats a copy from the target itself, or from a view that reads from it such as Mp3File.Tag or FlacFile.Tag, as a write-back. Before, the first write cut the lists the copy then read, so a file's view copied into its own tag kept only the first artist, genre, label, and catalog number. A copy of the original date a v2.3 tag already reads no longer drops the TDOR full date beside TORY. A Vorbis or APE movement laid out as Picard writes it, with the number in MOVEMENT beside MOVEMENTNAME, reads and writes the name in MOVEMENTNAME and the number in MOVEMENT, so a copy no longer writes the number over an ID3v2 MVNM. The ID3v2 comment and lyrics setters get the write-back guard, and the byte identity test now uses foreign frame layouts. --- src/TagLibSharp2/Ape/ApeTag.cs | 47 +++- src/TagLibSharp2/Core/CombinedTag.cs | 12 + src/TagLibSharp2/Core/Tag.cs | 207 +++++++++++------- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 89 +++----- src/TagLibSharp2/Xiph/FlacTag.cs | 4 + src/TagLibSharp2/Xiph/VorbisComment.cs | 85 +++---- .../Ape/ApeTagWriteBackTests.cs | 5 +- .../Core/TagCopyReplacesListTests.cs | 138 ++++++++++++ .../Id3/Id3v2/Id3v2TrailingTerminatorTests.cs | 19 +- .../Id3/Id3v2/Id3v2WriteBackTests.cs | 89 +++++--- .../Xiph/VorbisCommentWriteBackTests.cs | 14 +- 11 files changed, 480 insertions(+), 229 deletions(-) diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 02ed7f63..18d2c9be 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -127,6 +127,7 @@ private static class Keys public const string Work = "WORK"; public const string Movement = "MOVEMENT"; public const string MovementNumber = "MOVEMENTNUMBER"; + public const string MovementName = "MOVEMENTNAME"; public const string MovementTotal = "MOVEMENTTOTAL"; public const string Grouping = "Grouping"; public const string Remixer = "MixArtist"; @@ -674,24 +675,50 @@ public override string? Work { } /// + /// + /// Uses the MOVEMENT item. MusicBrainz Picard stores the name in MOVEMENTNAME and the number in + /// MOVEMENT (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). When MOVEMENT + /// is a number beside a MOVEMENTNAME, the name is read from and written to MOVEMENTNAME only, and + /// MOVEMENT is left to . + /// public override string? Movement { - get => GetValue (Keys.Movement); - set => SetOrRemoveProperty (Keys.Movement, value, Movement); + get => HasPicardMovement ? GetValue (Keys.MovementName) : GetValue (Keys.Movement); + set { + if (HasPicardMovement) + SetOrRemoveProperty (Keys.MovementName, value, Movement); + else + SetOrRemoveProperty (Keys.Movement, value, Movement); + } + } + + /// + /// True for the Picard layout: a non-empty MOVEMENTNAME beside a numeric MOVEMENT. + /// + bool HasPicardMovement => !string.IsNullOrEmpty (GetValue (Keys.MovementName)) && ParseMovementNumber (Keys.Movement) is not null; + + uint? ParseMovementNumber (string key) + { + var value = GetValue (key); + if (string.IsNullOrEmpty (value)) + return null; + return uint.TryParse (value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num) ? num : null; } /// + /// + /// Uses the MOVEMENTNUMBER item. In the Picard layout (see ) without one, + /// the number is read from and written to MOVEMENT, and clearing it removes MOVEMENT. + /// public override uint? MovementNumber { - get { - var value = GetValue (Keys.MovementNumber); - if (string.IsNullOrEmpty (value)) - return null; - return uint.TryParse (value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num) ? num : null; - } + get => ParseMovementNumber (Keys.MovementNumber) ?? (HasPicardMovement ? ParseMovementNumber (Keys.Movement) : null); set { + if (IsWriteBack (value, MovementNumber)) + return; + var key = HasPicardMovement && !_items.ContainsKey (Keys.MovementNumber) ? Keys.Movement : Keys.MovementNumber; if (value.HasValue) - SetValue (Keys.MovementNumber, value.Value.ToString (CultureInfo.InvariantCulture)); + SetValue (key, value.Value.ToString (CultureInfo.InvariantCulture)); else - _items.Remove (Keys.MovementNumber); + _items.Remove (key); } } diff --git a/src/TagLibSharp2/Core/CombinedTag.cs b/src/TagLibSharp2/Core/CombinedTag.cs index 6a44f8cd..7b93e551 100644 --- a/src/TagLibSharp2/Core/CombinedTag.cs +++ b/src/TagLibSharp2/Core/CombinedTag.cs @@ -157,6 +157,18 @@ public override string? Year { private protected override string? CopyableDate => FirstNonEmptyString (tag => tag.ReadCopyableDate ()); + /// + internal override bool ReadsFrom (Tag tag) + { + if (base.ReadsFrom (tag)) + return true; + foreach (var inner in _tags) { + if (inner is not null && inner.ReadsFrom (tag)) + return true; + } + return false; + } + /// public override string? Comment { get => FirstNonEmptyString (t => t.Comment); diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index d871a28a..979974ff 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -1189,10 +1189,16 @@ public virtual ValidationResult Validate () /// Thrown if target is null. /// /// - /// Only non-null values are copied. The target tag's existing values are overwritten - /// for any property that has a non-null value in the source. A source value that equals the - /// target's first value still replaces the target's list: the setters' write-back no-op does not - /// apply during a copy. + /// Only non-null values are copied. Every source value is read before any is written. The target's + /// existing values are overwritten for any property that has a non-null value in the source, and a + /// source value that equals the target's first value still replaces the target's list; a list the + /// target already holds is left as it is. + /// + /// + /// When the source is the target or reads from it (a file's combined Tag copied into one of its + /// own tags), the copy only adds values the target does not show. A fallback field of its own beside a + /// value equal to the copied one stays: Vorbis MOVEMENTNAME or ORIGINALYEAR, APE Date, and an + /// ID3v2.3 TDOR beside TORY. /// /// /// This is useful for converting between tag formats or synchronizing metadata @@ -1230,196 +1236,237 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) ArgumentNullException.ThrowIfNull (target); #endif - // A copy makes the target hold the source's value, so the write-back no-op in the setters - // (IsWriteBack) is off for the duration, also for tags a wrapper target forwards to. + if (ReferenceEquals (this, target)) + return; + + var writes = SnapshotCopyWrites (options); + + // A source that reads from the target, or a target that forwards to the source, already shows + // the target's values. Each is then a write-back and changes nothing (IsWriteBack), so only + // values the target does not hold arrive and its lists stay whole. + if (ReadsFrom (target) || target.ReadsFrom (this)) { + foreach (var write in writes) + write (target); + return; + } + + // Otherwise a copy makes the target hold the source's value, so the write-back no-op in the + // setters is off for the duration, also for tags a wrapper target forwards to. t_copyDepth++; try { - CopyValuesTo (target, options); + foreach (var write in writes) + write (target); } finally { t_copyDepth--; } } - void CopyValuesTo (Tag target, TagCopyOptions options) + /// + /// True when this tag is or reads its values from it, as a file's combined + /// view reads from the tags it combines. + /// + internal virtual bool ReadsFrom (Tag tag) => ReferenceEquals (this, tag); + + /// + /// Reads every value to copy before writing any, so a source that reads from the target (a file's + /// combined view copied into one of its tags) sees the target as it was, not half-written. + /// + List> SnapshotCopyWrites (TagCopyOptions options) { + var writes = new List> (); + // Basic metadata (always copied unless explicitly excluded) if ((options & TagCopyOptions.Basic) != 0) { if (Title is not null) - target.Title = Title; + Queue (writes, Title, static (t, v) => t.Title = v); if (Artist is not null) - target.Artist = Artist; + Queue (writes, Artist, static (t, v) => t.Artist = v); if (Album is not null) - target.Album = Album; + Queue (writes, Album, static (t, v) => t.Album = v); var copyableDate = CopyableDate; if (copyableDate is not null) - target.Year = copyableDate; + Queue (writes, copyableDate, static (t, v) => t.Year = v); if (Comment is not null) - target.Comment = Comment; + Queue (writes, Comment, static (t, v) => t.Comment = v); if (Genre is not null) - target.Genre = Genre; + Queue (writes, Genre, static (t, v) => t.Genre = v); if (Track.HasValue) - target.Track = Track; + Queue (writes, Track, static (t, v) => t.Track = v); } // Extended metadata if ((options & TagCopyOptions.Extended) != 0) { // Arrays if (Performers is { Length: > 0 }) - target.Performers = Performers; + QueueList (writes, Performers, static t => t.Performers, static (t, v) => t.Performers = v); if (AlbumArtists is { Length: > 0 }) - target.AlbumArtists = AlbumArtists; + QueueList (writes, AlbumArtists, static t => t.AlbumArtists, static (t, v) => t.AlbumArtists = v); if (Composers is { Length: > 0 }) - target.Composers = Composers; + QueueList (writes, Composers, static t => t.Composers, static (t, v) => t.Composers = v); if (Genres is { Length: > 0 }) - target.Genres = Genres; + QueueList (writes, Genres, static t => t.Genres, static (t, v) => t.Genres = v); // Extended single values // The singular value is the first entry. Writing it after the array // replaces the whole list with that one name. if (AlbumArtist is not null && AlbumArtists is not { Length: > 0 }) - target.AlbumArtist = AlbumArtist; + Queue (writes, AlbumArtist, static (t, v) => t.AlbumArtist = v); if (Composer is not null && Composers is not { Length: > 0 }) - target.Composer = Composer; + Queue (writes, Composer, static (t, v) => t.Composer = v); if (Conductor is not null) - target.Conductor = Conductor; + Queue (writes, Conductor, static (t, v) => t.Conductor = v); if (Copyright is not null) - target.Copyright = Copyright; + Queue (writes, Copyright, static (t, v) => t.Copyright = v); if (DiscNumber.HasValue) - target.DiscNumber = DiscNumber; + Queue (writes, DiscNumber, static (t, v) => t.DiscNumber = v); if (TotalDiscs.HasValue) - target.TotalDiscs = TotalDiscs; + Queue (writes, TotalDiscs, static (t, v) => t.TotalDiscs = v); if (DiscSubtitle is not null) - target.DiscSubtitle = DiscSubtitle; + Queue (writes, DiscSubtitle, static (t, v) => t.DiscSubtitle = v); if (TotalTracks.HasValue) - target.TotalTracks = TotalTracks; + Queue (writes, TotalTracks, static (t, v) => t.TotalTracks = v); if (BeatsPerMinute.HasValue) - target.BeatsPerMinute = BeatsPerMinute; + Queue (writes, BeatsPerMinute, static (t, v) => t.BeatsPerMinute = v); if (Lyrics is not null) - target.Lyrics = Lyrics; + Queue (writes, Lyrics, static (t, v) => t.Lyrics = v); if (Isrc is not null) - target.Isrc = Isrc; + Queue (writes, Isrc, static (t, v) => t.Isrc = v); if (Publisher is not null) - target.Publisher = Publisher; + Queue (writes, Publisher, static (t, v) => t.Publisher = v); if (EncodedBy is not null) - target.EncodedBy = EncodedBy; + Queue (writes, EncodedBy, static (t, v) => t.EncodedBy = v); if (EncoderSettings is not null) - target.EncoderSettings = EncoderSettings; + Queue (writes, EncoderSettings, static (t, v) => t.EncoderSettings = v); if (Grouping is not null) - target.Grouping = Grouping; + Queue (writes, Grouping, static (t, v) => t.Grouping = v); if (Subtitle is not null) - target.Subtitle = Subtitle; + Queue (writes, Subtitle, static (t, v) => t.Subtitle = v); if (Remixer is not null) - target.Remixer = Remixer; + Queue (writes, Remixer, static (t, v) => t.Remixer = v); if (InitialKey is not null) - target.InitialKey = InitialKey; + Queue (writes, InitialKey, static (t, v) => t.InitialKey = v); if (Mood is not null) - target.Mood = Mood; + Queue (writes, Mood, static (t, v) => t.Mood = v); if (MediaType is not null) - target.MediaType = MediaType; + Queue (writes, MediaType, static (t, v) => t.MediaType = v); if (Language is not null) - target.Language = Language; + Queue (writes, Language, static (t, v) => t.Language = v); if (Barcode is not null) - target.Barcode = Barcode; + Queue (writes, Barcode, static (t, v) => t.Barcode = v); if (CatalogNumber is not null) - target.CatalogNumber = CatalogNumber; + Queue (writes, CatalogNumber, static (t, v) => t.CatalogNumber = v); if (OriginalReleaseDate is not null) - target.OriginalReleaseDate = OriginalReleaseDate; + Queue (writes, OriginalReleaseDate, static (t, v) => t.OriginalReleaseDate = v); if (Description is not null) - target.Description = Description; + Queue (writes, Description, static (t, v) => t.Description = v); if (DateTagged is not null) - target.DateTagged = DateTagged; + Queue (writes, DateTagged, static (t, v) => t.DateTagged = v); if (AmazonId is not null) - target.AmazonId = AmazonId; + Queue (writes, AmazonId, static (t, v) => t.AmazonId = v); if (IsCompilation) - target.IsCompilation = true; + Queue (writes, true, static (t, v) => t.IsCompilation = v); // Classical music metadata if (Work is not null) - target.Work = Work; + Queue (writes, Work, static (t, v) => t.Work = v); if (Movement is not null) - target.Movement = Movement; + Queue (writes, Movement, static (t, v) => t.Movement = v); if (MovementNumber.HasValue) - target.MovementNumber = MovementNumber; + Queue (writes, MovementNumber, static (t, v) => t.MovementNumber = v); if (MovementTotal.HasValue) - target.MovementTotal = MovementTotal; + Queue (writes, MovementTotal, static (t, v) => t.MovementTotal = v); // Performers role if (PerformersRole is { Length: > 0 }) - target.PerformersRole = PerformersRole; + QueueList (writes, PerformersRole, static t => t.PerformersRole, static (t, v) => t.PerformersRole = v); } // Sort order if ((options & TagCopyOptions.SortOrder) != 0) { if (AlbumSort is not null) - target.AlbumSort = AlbumSort; + Queue (writes, AlbumSort, static (t, v) => t.AlbumSort = v); if (ArtistSort is not null) - target.ArtistSort = ArtistSort; + Queue (writes, ArtistSort, static (t, v) => t.ArtistSort = v); if (TitleSort is not null) - target.TitleSort = TitleSort; + Queue (writes, TitleSort, static (t, v) => t.TitleSort = v); if (AlbumArtistSort is not null) - target.AlbumArtistSort = AlbumArtistSort; + Queue (writes, AlbumArtistSort, static (t, v) => t.AlbumArtistSort = v); if (ComposerSort is not null) - target.ComposerSort = ComposerSort; + Queue (writes, ComposerSort, static (t, v) => t.ComposerSort = v); if (PerformersSort is { Length: > 0 }) - target.PerformersSort = PerformersSort; + QueueList (writes, PerformersSort, static t => t.PerformersSort, static (t, v) => t.PerformersSort = v); if (AlbumArtistsSort is { Length: > 0 }) - target.AlbumArtistsSort = AlbumArtistsSort; + QueueList (writes, AlbumArtistsSort, static t => t.AlbumArtistsSort, static (t, v) => t.AlbumArtistsSort = v); if (ComposersSort is { Length: > 0 }) - target.ComposersSort = ComposersSort; + QueueList (writes, ComposersSort, static t => t.ComposersSort, static (t, v) => t.ComposersSort = v); } // ReplayGain and R128 if ((options & TagCopyOptions.ReplayGain) != 0) { if (ReplayGainTrackGain is not null) - target.ReplayGainTrackGain = ReplayGainTrackGain; + Queue (writes, ReplayGainTrackGain, static (t, v) => t.ReplayGainTrackGain = v); if (ReplayGainTrackPeak is not null) - target.ReplayGainTrackPeak = ReplayGainTrackPeak; + Queue (writes, ReplayGainTrackPeak, static (t, v) => t.ReplayGainTrackPeak = v); if (ReplayGainAlbumGain is not null) - target.ReplayGainAlbumGain = ReplayGainAlbumGain; + Queue (writes, ReplayGainAlbumGain, static (t, v) => t.ReplayGainAlbumGain = v); if (ReplayGainAlbumPeak is not null) - target.ReplayGainAlbumPeak = ReplayGainAlbumPeak; + Queue (writes, ReplayGainAlbumPeak, static (t, v) => t.ReplayGainAlbumPeak = v); if (R128TrackGain is not null) - target.R128TrackGain = R128TrackGain; + Queue (writes, R128TrackGain, static (t, v) => t.R128TrackGain = v); if (R128AlbumGain is not null) - target.R128AlbumGain = R128AlbumGain; + Queue (writes, R128AlbumGain, static (t, v) => t.R128AlbumGain = v); } // MusicBrainz IDs if ((options & TagCopyOptions.MusicBrainz) != 0) { if (MusicBrainzTrackId is not null) - target.MusicBrainzTrackId = MusicBrainzTrackId; + Queue (writes, MusicBrainzTrackId, static (t, v) => t.MusicBrainzTrackId = v); if (MusicBrainzReleaseId is not null) - target.MusicBrainzReleaseId = MusicBrainzReleaseId; + Queue (writes, MusicBrainzReleaseId, static (t, v) => t.MusicBrainzReleaseId = v); if (MusicBrainzArtistId is not null) - target.MusicBrainzArtistId = MusicBrainzArtistId; + Queue (writes, MusicBrainzArtistId, static (t, v) => t.MusicBrainzArtistId = v); if (MusicBrainzReleaseGroupId is not null) - target.MusicBrainzReleaseGroupId = MusicBrainzReleaseGroupId; + Queue (writes, MusicBrainzReleaseGroupId, static (t, v) => t.MusicBrainzReleaseGroupId = v); if (MusicBrainzAlbumArtistId is not null) - target.MusicBrainzAlbumArtistId = MusicBrainzAlbumArtistId; + Queue (writes, MusicBrainzAlbumArtistId, static (t, v) => t.MusicBrainzAlbumArtistId = v); if (MusicBrainzRecordingId is not null) - target.MusicBrainzRecordingId = MusicBrainzRecordingId; + Queue (writes, MusicBrainzRecordingId, static (t, v) => t.MusicBrainzRecordingId = v); if (MusicBrainzWorkId is not null) - target.MusicBrainzWorkId = MusicBrainzWorkId; + Queue (writes, MusicBrainzWorkId, static (t, v) => t.MusicBrainzWorkId = v); if (MusicBrainzDiscId is not null) - target.MusicBrainzDiscId = MusicBrainzDiscId; + Queue (writes, MusicBrainzDiscId, static (t, v) => t.MusicBrainzDiscId = v); if (MusicBrainzReleaseStatus is not null) - target.MusicBrainzReleaseStatus = MusicBrainzReleaseStatus; + Queue (writes, MusicBrainzReleaseStatus, static (t, v) => t.MusicBrainzReleaseStatus = v); if (MusicBrainzReleaseType is not null) - target.MusicBrainzReleaseType = MusicBrainzReleaseType; + Queue (writes, MusicBrainzReleaseType, static (t, v) => t.MusicBrainzReleaseType = v); if (MusicBrainzReleaseCountry is not null) - target.MusicBrainzReleaseCountry = MusicBrainzReleaseCountry; + Queue (writes, MusicBrainzReleaseCountry, static (t, v) => t.MusicBrainzReleaseCountry = v); if (AcoustIdId is not null) - target.AcoustIdId = AcoustIdId; + Queue (writes, AcoustIdId, static (t, v) => t.AcoustIdId = v); if (AcoustIdFingerprint is not null) - target.AcoustIdFingerprint = AcoustIdFingerprint; + Queue (writes, AcoustIdFingerprint, static (t, v) => t.AcoustIdFingerprint = v); } // Pictures if ((options & TagCopyOptions.Pictures) != 0) { if (Pictures is { Length: > 0 }) - target.Pictures = Pictures; + Queue (writes, Pictures, static (t, v) => t.Pictures = v); } + return writes; } + + static void Queue (List> writes, T value, Action set) => + writes.Add (t => set (t, value)); + + /// + /// Queues a list write that is skipped when the target already holds exactly that list, so a copy + /// of a list the target shows leaves its frames, items, or fields as they are. + /// + static void QueueList (List> writes, string[] value, Func get, Action set) => + writes.Add (t => { + if (get (t) is not { } current || !current.AsSpan ().SequenceEqual (value)) + set (t, value); + }); } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 4b3eea15..186dce5b 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -266,7 +266,9 @@ public override string? OriginalReleaseDate { return NormalizeYear (GetTextFrame ("TORY")) ?? NormalizeReleaseTimestamp (GetTextFrame ("TDOR")); } set { - if (IsWriteBack (value, OriginalReleaseDate)) + // The value read changes nothing, in a copy too: in a v2.3 tag, TDOR beside TORY is the only + // place the month and day live (TORY holds the year, ID3v2.3 §4.2.1). + if (IsValueRead (value, OriginalReleaseDate)) return; SetDateFrame ( Version == 4 ? "TDOR" : "TORY", @@ -280,7 +282,10 @@ public override string? OriginalReleaseDate { /// public override string? Comment { get => GetComment (); - set => SetComment (value); + set { + if (!IsWriteBack (value, Comment)) + SetComment (value); + } } /// @@ -861,7 +866,10 @@ public override uint? TotalDiscs { /// public override string? Lyrics { get => GetLyrics (); - set => SetLyrics (value); + set { + if (!IsWriteBack (value, Lyrics)) + SetLyrics (value); + } } /// @@ -1020,7 +1028,7 @@ public override string? Movement { return string.IsNullOrEmpty (user) ? apple ?? user : user; } set { - if (IsTextWriteBack (value, Movement, GetRawTextFrame ("MVNM"), GetRawUserText ("MOVEMENT"))) + if (IsWriteBack (value, Movement)) return; SetTextFrame ("MVNM", value); SetUserText ("MOVEMENT", value); @@ -1517,8 +1525,8 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) /// /// The frame ID (e.g., TIT2, TPE1). /// - /// The first value, even when that value is empty, or null when the frame is absent. - /// A NUL separates further values and is not included. A slash is not a separator here. + /// The first non-empty value, "" when every value is empty, or null when the frame is absent. + /// A NUL separates values and is not included. A slash is not a separator here. /// public string? GetTextFrame (string frameId) { @@ -1543,16 +1551,23 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) } /// - /// Returns the text before the first NUL. A leading NUL is an empty value, not a reason to skip ahead. + /// Returns the first non-empty value of NUL-separated text, or "" when every value is empty. + /// ID3v2.4 §4.2 stores several strings as a NUL-separated list, so after an empty first value the + /// next one is still a value. Reading it means a write-back of what was read keeps the frame, + /// and "" is only read back when no value holds text. /// static string FirstTextValue (string text) { - for (var i = 0; i < text.Length; i++) { - if (text[i] == '\0') - return text.Substring (0, i); + var start = 0; + for (var i = 0; i <= text.Length; i++) { + if (i == text.Length || text[i] == '\0') { + if (i > start) + return text.Substring (start, i - start); + start = i + 1; + } } - return text; + return ""; } /// @@ -1762,7 +1777,7 @@ void SetDateFrame (string frameId, string? value, bool timestamp, bool keepMatch /// void SetTextFrameProperty (string frameId, string? value, string? current) { - if (!IsTextWriteBack (value, current, GetRawTextFrame (frameId))) + if (!IsWriteBack (value, current)) SetTextFrame (frameId, value); } @@ -1770,53 +1785,9 @@ void SetTextFrameProperty (string frameId, string? value, string? current) /// Writes a single-value TXXX property, with the same write-back rule as . /// void SetUserTextProperty (string description, string? value, string? current) - { - if (!IsTextWriteBack (value, current, GetRawUserText (description))) - SetUserText (description, value); - } - - /// - /// , except that an empty string is a write-back only - /// when none of holds text. A getter returns "" for an empty first value - /// ("\0V2"), and "" over such a frame still clears it. - /// - static bool IsTextWriteBack (string? value, string? current, params string?[] stored) { if (!IsWriteBack (value, current)) - return false; - if (value!.Length != 0) - return true; - foreach (var text in stored) { - if (HasText (text)) - return false; - } - return true; - } - - /// - /// True when the stored text holds any character other than a NUL value separator. - /// - static bool HasText (string? text) - { - if (text is null) - return false; - for (var i = 0; i < text.Length; i++) { - if (text[i] != '\0') - return true; - } - return false; - } - - /// - /// The stored value of the first TXXX frame with this description, including NUL separators. - /// - string? GetRawUserText (string description) - { - for (var i = 0; i < _userTextFrames.Count; i++) { - if (string.Equals (_userTextFrames[i].Description, description, StringComparison.OrdinalIgnoreCase)) - return _userTextFrames[i].Value; - } - return null; + SetUserText (description, value); } /// @@ -2239,8 +2210,8 @@ public void RemoveComments (string? language = null, string? description = null) /// /// The description (key) of the TXXX frame. /// - /// The first value, even when that value is empty, or null when the frame is absent. - /// An embedded NUL is not included. The frame still stores the rest of the text. + /// The first non-empty value, "" when every value is empty, or null when the frame is absent. + /// An embedded NUL separates values and is not included. The frame still stores the rest of the text. /// public string? GetUserText (string description) { diff --git a/src/TagLibSharp2/Xiph/FlacTag.cs b/src/TagLibSharp2/Xiph/FlacTag.cs index 4bd64bf3..cb702e00 100644 --- a/src/TagLibSharp2/Xiph/FlacTag.cs +++ b/src/TagLibSharp2/Xiph/FlacTag.cs @@ -112,6 +112,10 @@ public override string? Movement { set => EnsureVorbisComment ().Movement = value; } + /// + internal override bool ReadsFrom (Tag tag) => + base.ReadsFrom (tag) || (_file.VorbisComment?.ReadsFrom (tag) ?? false); + /// public override string? Copyright { get => _file.VorbisComment?.Copyright; diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 7dc9d5b2..0b217498 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -273,22 +273,48 @@ public override string? Work { /// /// /// Uses the MOVEMENT field. Falls back to MOVEMENTNAME when MOVEMENT is missing or empty. - /// Writing back the value already read changes nothing, so a MOVEMENTNAME that Picard or Mp3tag - /// wrote beside a MOVEMENT number is kept. A new value is written to MOVEMENT and to an existing - /// MOVEMENTNAME. Clearing removes both. + /// Writing back the value already read changes nothing. A new value is written to MOVEMENT and to + /// an existing MOVEMENTNAME. Clearing removes both. + /// MusicBrainz Picard and Mp3tag store the name in MOVEMENTNAME and the number in MOVEMENT + /// (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). When MOVEMENT is a + /// number beside a MOVEMENTNAME, the name is read from and written to MOVEMENTNAME only, and + /// MOVEMENT is left to . /// public override string? Movement { - get => GetValueOrFallback ("MOVEMENT", "MOVEMENTNAME"); - set => SetValueWithFallback ("MOVEMENT", value, "MOVEMENTNAME", static v => v); + get => HasPicardMovement ? GetValue ("MOVEMENTNAME") : GetValueOrFallback ("MOVEMENT", "MOVEMENTNAME"); + set { + if (HasPicardMovement) + SetValueProperty ("MOVEMENTNAME", value, Movement); + else + SetValueWithFallback ("MOVEMENT", value, "MOVEMENTNAME", static v => v); + } } + /// + /// True for the Picard layout: a non-empty MOVEMENTNAME beside a numeric MOVEMENT. + /// + bool HasPicardMovement => !string.IsNullOrEmpty (GetValue ("MOVEMENTNAME")) && TryParseUInt (GetValue ("MOVEMENT"), out _); + /// + /// + /// Uses the MOVEMENTNUMBER field. In the Picard layout (see ) without one, + /// the number is read from and written to MOVEMENT, and clearing it removes MOVEMENT. + /// public override uint? MovementNumber { get { - var value = GetValue ("MOVEMENTNUMBER"); - return TryParseUInt (value, out var num) ? num : null; + if (TryParseUInt (GetValue ("MOVEMENTNUMBER"), out var num)) + return num; + return HasPicardMovement && TryParseUInt (GetValue ("MOVEMENT"), out num) ? num : null; + } + set { + if (IsWriteBack (value, MovementNumber)) + return; + var text = value?.ToString (System.Globalization.CultureInfo.InvariantCulture); + if (HasPicardMovement && GetValue ("MOVEMENTNUMBER") is null) + SetValue ("MOVEMENT", text); + else + SetValue ("MOVEMENTNUMBER", text); } - set => SetValue ("MOVEMENTNUMBER", value?.ToString (System.Globalization.CultureInfo.InvariantCulture)); } /// @@ -746,10 +772,14 @@ public void AddField (string name, string value) } /// - /// Gets the first value for a field name. + /// Gets the first non-empty value for a field name. /// /// The field name (case-insensitive). - /// The first value, or null if not found. + /// + /// The first non-empty value, "" when every field with this name is empty, or null if not found. + /// Field names may repeat (https://xiph.org/vorbis/doc/v-comment.html), so an empty first field does + /// not hide a later value, and a write-back of the value read keeps every field. + /// /// Thrown when is null. public string? GetValue (string name) { @@ -763,11 +793,15 @@ public void AddField (string name, string value) // Use explicit check instead of relying on struct default behavior. // When no match is found, FirstOrDefault returns default(VorbisCommentField) // which has null properties - but we make this explicit for clarity. + string? empty = null; for (var i = 0; i < _fields.Count; i++) { - if (_fields[i].Name == upperName) + if (_fields[i].Name != upperName) + continue; + if (_fields[i].Value.Length != 0) return _fields[i].Value; + empty = ""; } - return null; + return empty; } /// @@ -927,33 +961,10 @@ public void SetValue (string name, string? value) /// void SetValueProperty (string name, string? value, string? current) { - if (!IsFieldWriteBack (value, current, name)) + if (!IsWriteBack (value, current)) SetValue (name, value); } - /// - /// , except that an empty string is a write-back only when - /// no field named holds text. The getter returns "" for an empty first field - /// even when a later one has text, and "" over such fields still clears them. - /// - bool IsFieldWriteBack (string? value, string? current, string name) => - IsWriteBack (value, current) && (value!.Length != 0 || !HasText (name)); - - /// - /// True when any field with one of these names has a non-empty value. - /// - bool HasText (params string[] names) - { - foreach (var name in names) { - var upper = name.ToUpperInvariant (); - for (var i = 0; i < _fields.Count; i++) { - if (_fields[i].Name == upper && _fields[i].Value.Length != 0) - return true; - } - } - return false; - } - /// /// The first value of , or of when the first is /// missing or empty. An empty field is a valid comment (https://xiph.org/vorbis/doc/v-comment.html), @@ -979,7 +990,7 @@ bool HasText (params string[] names) /// void SetValueWithFallback (string name, string? value, string fallback, Func toFallback) { - if (IsValueRead (value, GetValueOrFallback (name, fallback)) && (value!.Length != 0 || !HasText (name, fallback))) { + if (IsValueRead (value, GetValueOrFallback (name, fallback))) { // The value read changes nothing, in a copy too: the fallback is its own field (Picard keeps // MOVEMENTNAME beside a MOVEMENT number). A copy still drops the other values of name. if (IsCopying && GetValues (name).Count > 1 && GetValue (name) == value) diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs index f1890555..0f6fc9d1 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs @@ -84,10 +84,7 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsTheItem_AndAnEditReplace property.SetValue (tag, read); var after = Snapshot (Reparse (tag)); - // "" is a write-back only when no value holds text: an empty first value reads "", - // and "" over a list with text clears it. - var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); - if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) + if (!before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); // A case-only edit, or "" over a list whose later values hold text, is not a write-back. diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index 74e20cfc..e68d7a19 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -6,6 +6,7 @@ using TagLibSharp2.Ape; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; using TagLibSharp2.Xiph; namespace TagLibSharp2.Tests.Core; @@ -214,6 +215,143 @@ static VorbisComment Picard () Assert.AreEqual ("2001-05-03", ape.GetValue ("Date")); } + static Id3v2Tag PicardId3 (Id3v2Version version) + { + var tag = new Id3v2Tag (version); + tag.Performers = ["P1", "P2"]; + tag.Genres = ["Rock", "Pop"]; + tag.SetTextFrameValues ("TPUB", ["Lab1", "Lab2"]); + tag.AddUserTextFrame (new TagLibSharp2.Id3.Id3v2.Frames.UserTextFrame ("CATALOGNUMBER", "CAT1\0CAT2")); + return Id3v2Tag.Read (tag.Render ().Span).Tag!; + } + + static List Frames (Id3v2Tag tag) => + [.. tag.Frames.Select (f => f.Id + "=" + f.Text), .. tag.UserTextFrames.Select (f => f.Description + "=" + f.Value)]; + + [TestMethod] + [DataRow (Id3v2Version.V23)] + [DataRow (Id3v2Version.V24)] + public void Copy_FromAViewOverTheTarget_KeepsEveryList (Id3v2Version version) + { + var tag = PicardId3 (version); + var before = Frames (tag); + + new CombinedTag (tag, null).CopyTo (tag, TagCopyOptions.All); + CollectionAssert.AreEqual (before, Frames (tag)); + + tag.CopyTo (tag, TagCopyOptions.All); + CollectionAssert.AreEqual (before, Frames (tag)); + + // Mp3File.Tag is a CombinedTag over the file's ID3v2 and ID3v1 tags. + byte[] mpeg = [0xFF, 0xFB, 0x90, 0x00, .. new byte[413]]; + var mp3 = Mp3File.Read ([.. tag.Render ().Span, .. mpeg]).File!; + var fileBefore = Frames (mp3.Id3v2Tag!); + mp3.Tag!.CopyTo (mp3.Id3v2Tag!, TagCopyOptions.All); + CollectionAssert.AreEqual (fileBefore, Frames (mp3.Id3v2Tag!)); + } + + [TestMethod] + public void Copy_FromAViewOverTheTarget_KeepsEveryList_FlacAndApe () + { + var file = FlacFile.Read (TestBuilders.Flac.CreateMinimal ()).File!; + var comment = new VorbisComment ("test"); + foreach (var (name, value) in new[] { ("ARTIST", "P1"), ("ARTIST", "P2"), ("GENRE", "Rock"), ("GENRE", "Pop"), ("LABEL", "Lab1"), ("LABEL", "Lab2") }) + comment.AddField (name, value); + file.VorbisComment = comment; + var before = string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value)); + + file.Tag!.CopyTo (comment, TagCopyOptions.All); + comment.CopyTo (file.Tag!, TagCopyOptions.All); + + Assert.AreEqual (before, string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value))); + + var ape = new ApeTag (); + ape.SetValue ("Artist", "P1\0P2"); + ape.SetValue ("Genre", "Rock\0Pop"); + ape.SetValue ("Publisher", "Lab1\0Lab2"); + ape.CopyTo (ape, TagCopyOptions.All); + Assert.AreEqual ("P1|P2", string.Join ("|", ape.Performers)); + Assert.AreEqual ("Rock|Pop", string.Join ("|", ape.Genres)); + Assert.AreEqual ("Lab1, Lab2", ape.GetValue ("Publisher")); + } + + [TestMethod] + public void Copy_FromAnUndetectedView_ReadsTheSourceBeforeWriting () + { + // A view this library does not know about. CopyTo reads every source value before it writes, + // so the Artist write cannot shorten the Performers list the copy reads afterwards. + var inner = PicardId3 (Id3v2Version.V24); + var view = new ForwardingTag (inner); + + view.CopyTo (inner, TagCopyOptions.All); + + Assert.AreEqual ("P1|P2", string.Join ("|", inner.Performers)); + Assert.AreEqual ("Rock|Pop", string.Join ("|", inner.Genres)); + } + + [TestMethod] + public void Copy_OfTheOriginalDateAV23TagReads_KeepsTdor () + { + // In ID3v2.3, TORY holds only the year (ID3v2.3 §4.2.1); a TDOR beside it carries the full date. + var tdorOnly = new Id3v2Tag (Id3v2Version.V23); + tdorOnly.SetTextFrameValues ("TDOR", ["1969-09-26"]); + new VorbisComment ("s") { OriginalReleaseDate = "1969-09-26" }.CopyTo (tdorOnly, TagCopyOptions.All); + Assert.AreEqual ("1969-09-26", tdorOnly.GetTextFrame ("TDOR")); + Assert.IsNull (tdorOnly.GetTextFrame ("TORY")); + + var both = new Id3v2Tag (Id3v2Version.V23); + both.SetTextFrameValues ("TORY", ["1969"]); + both.SetTextFrameValues ("TDOR", ["1969-09-26"]); + new VorbisComment ("s") { OriginalReleaseDate = "1969" }.CopyTo (both, TagCopyOptions.All); + Assert.AreEqual ("1969", both.GetTextFrame ("TORY")); + Assert.AreEqual ("1969-09-26", both.GetTextFrame ("TDOR")); + + new VorbisComment ("s") { OriginalReleaseDate = "1970-01-02" }.CopyTo (both, TagCopyOptions.All); + Assert.AreEqual ("1970", both.OriginalReleaseDate); + Assert.IsNull (both.GetTextFrame ("TDOR")); + } + + [TestMethod] + public void Copy_FromAPicardMovementLayout_KeepsTheAppleName () + { + var source = new VorbisComment ("picard"); + source.AddField ("MOVEMENTNAME", "Allegro"); + source.AddField ("MOVEMENT", "2"); + source.AddField ("MOVEMENTTOTAL", "4"); + var target = new Id3v2Tag (Id3v2Version.V24); + target.SetTextFrameValues ("MVNM", ["Allegro"]); + target.SetTextFrameValues ("MVIN", ["2/4"]); + + source.CopyTo (target, TagCopyOptions.All); + + Assert.AreEqual ("Allegro", target.GetTextFrame ("MVNM")); + Assert.AreEqual ("2/4", target.GetTextFrame ("MVIN")); + + var ape = new ApeTag (); + ape.SetValue ("MOVEMENTNAME", "Allegro"); + ape.SetValue ("MOVEMENT", "2"); + var fromApe = new Id3v2Tag (Id3v2Version.V24); + ape.CopyTo (fromApe, TagCopyOptions.All); + Assert.AreEqual ("Allegro", fromApe.GetTextFrame ("MVNM")); + Assert.AreEqual (2u, fromApe.MovementNumber); + } + + sealed class ForwardingTag (Id3v2Tag inner) : Tag + { + public override TagTypes TagType => inner.TagType; + public override string? Title { get => inner.Title; set => inner.Title = value; } + public override string? Artist { get => inner.Artist; set => inner.Artist = value; } + public override string[] Performers { get => inner.Performers; set => inner.Performers = value; } + public override string? Album { get => inner.Album; set => inner.Album = value; } + public override string? Year { get => inner.Year; set => inner.Year = value; } + public override string? Comment { get => inner.Comment; set => inner.Comment = value; } + public override string? Genre { get => inner.Genre; set => inner.Genre = value; } + public override string[] Genres { get => inner.Genres; set => inner.Genres = value; } + public override uint? Track { get => inner.Track; set => inner.Track = value; } + public override BinaryData Render () => inner.Render (); + public override void Clear () => inner.Clear (); + } + [TestMethod] public void WriteBack_AfterACopy_IsANoOpAgain () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs index 3862cc59..c24ec065 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -386,7 +386,7 @@ public void Title_Utf16OddLength_DoesNotDropLastCharacter () } [TestMethod] - public void Text_LeadingNul_FirstValueIsEmpty () + public void Text_LeadingNul_ReadsTheFirstNonEmptyValue () { using var builder = new BinaryDataBuilder (); builder.Add ((byte)TextEncodingType.Latin1); @@ -394,14 +394,14 @@ public void Text_LeadingNul_FirstValueIsEmpty () var leading = builder.ToBinaryData ().ToArray (); var v23 = ReadFrame (TestConstants.Id3v2.Version3, "TIT2", leading); - Assert.AreEqual ("", v23.GetTextFrame ("TIT2")); + Assert.AreEqual ("b", v23.GetTextFrame ("TIT2")); Assert.AreEqual ("\0b", v23.Frames[0].Text); var values23 = v23.GetTextFrameValues ("TIT2"); Assert.HasCount (1, values23); Assert.AreEqual ("b", values23[0]); var v24 = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", leading); - Assert.AreEqual ("", v24.GetTextFrame ("TIT2")); + Assert.AreEqual ("b", v24.GetTextFrame ("TIT2")); var values24 = v24.GetTextFrameValues ("TIT2"); Assert.HasCount (1, values24); Assert.AreEqual ("b", values24[0]); @@ -410,7 +410,12 @@ public void Text_LeadingNul_FirstValueIsEmpty () skipped.Add ((byte)TextEncodingType.Latin1); skipped.Add (0, 0, (byte)'T'); var allEmpty = ReadFrame (TestConstants.Id3v2.Version3, "TIT2", skipped.ToBinaryData ().ToArray ()); - Assert.AreEqual ("", allEmpty.GetTextFrame ("TIT2")); + Assert.AreEqual ("T", allEmpty.GetTextFrame ("TIT2")); + + using var empties = new BinaryDataBuilder (); + empties.Add ((byte)TextEncodingType.Latin1); + empties.Add (0, 0); + Assert.AreEqual ("", ReadFrame (TestConstants.Id3v2.Version4, "TIT2", empties.ToBinaryData ().ToArray ()).GetTextFrame ("TIT2")); Assert.AreEqual ("T", allEmpty.GetTextFrameValues ("TIT2")[0]); Assert.IsNull (new Id3v2Tag ().GetTextFrame ("TIT2")); } @@ -536,7 +541,7 @@ public void Performers_Utf16WithoutBom_KeepsBothNames () } [TestMethod] - public void Performers_Utf16LeadingNul_FirstValueIsEmpty () + public void Performers_Utf16LeadingNul_SingleValueIsTheFirstName () { using var builder = new BinaryDataBuilder (); builder.Add ((byte)TextEncodingType.Utf16WithBom); @@ -546,8 +551,8 @@ public void Performers_Utf16LeadingNul_FirstValueIsEmpty () var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); Assert.AreEqual ("\0b", tag.Frames[0].Text); - Assert.AreEqual ("", tag.GetTextFrame ("TPE1")); - Assert.AreEqual ("", tag.Artist); + Assert.AreEqual ("b", tag.GetTextFrame ("TPE1")); + Assert.AreEqual ("b", tag.Artist); var values = tag.GetTextFrameValues ("TPE1"); Assert.HasCount (1, values); Assert.AreEqual ("b", values[0]); diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs index 81b3ab68..98cc7d71 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs @@ -80,10 +80,7 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue_AndAnEditRepl property.SetValue (tag, read); var after = Snapshot (Reparse (tag)); - // "" is a write-back only when no value holds text: the getter reports an empty first - // value as "", and "" over a list with text clears it, as in APE. - var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); - if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) + if (!before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); // A case-only edit, or "" over a list whose later values hold text, is not a write-back. @@ -107,28 +104,62 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryValue_AndAnEditRepl static readonly string[] Candidates = ["V1", "2001", "2001-05-03", "http://example.com/feed", "b10b5bd8-0000-4000-8000-000000000001"]; /// - /// COMM and USLT can hold several frames that differ by language and description; their single-value - /// setters replace that set and are outside the write-back rule. + /// Content in a layout this library's setters never write: UTF-16 with a BOM on every value, + /// a second value, a non-default language, a second COMM frame. /// - static readonly string[] NotWriteBackSafe = ["Comment", "Lyrics"]; + static byte[] Utf16 (string text) => [0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (text)]; + + static byte[] Join (params byte[][] parts) => parts.SelectMany (p => p).ToArray (); + + static readonly byte[] Nul16 = [0, 0]; + + /// + /// Rebuilds every frame the setter wrote for in a foreign layout, holding + /// , and parses the result. + /// + static Id3v2Tag BuildForeign (Id3v2Tag probe, byte version, string value) + { + var frames = new List (); + foreach (var f in probe.Frames) + frames.Add (TestBuilders.Id3v2.CreateFrame (f.Id, Join ([0x01], Utf16 (value), Nul16, Utf16 ("V2")), version)); + foreach (var f in probe.UserTextFrames) + frames.Add (TestBuilders.Id3v2.CreateFrame ("TXXX", Join ([0x01], Utf16 (f.Description), Nul16, Utf16 (value), Nul16, Utf16 ("V2")), version)); + if (probe.Comments.Count > 0) { + frames.Add (TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "deu"u8.ToArray (), [0x00], System.Text.Encoding.Latin1.GetBytes (value)), version)); + frames.Add (TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), "note"u8.ToArray (), [0x00], "other"u8.ToArray ()), version)); + } + foreach (var _ in probe.LyricsFrames) + frames.Add (TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x01], "deu"u8.ToArray (), Utf16 (""), Nul16, Utf16 (value)), version)); + foreach (var f in probe.UrlFrames) + frames.Add (TestBuilders.Id3v2.CreateFrame (f.Id, System.Text.Encoding.Latin1.GetBytes (value), version)); + foreach (var f in probe.UniqueFileIdFrames) + frames.Add (TestBuilders.Id3v2.CreateFrame ("UFID", Join (System.Text.Encoding.Latin1.GetBytes (f.Owner), [0x00], System.Text.Encoding.ASCII.GetBytes (value)), version)); + // A frame after the property's frames, so a setter that rewrites them moves them. + frames.Add (TestBuilders.Id3v2.CreateFrame (probe.Frames.Any (f => f.Id == "TALB") ? "TIT2" : "TALB", Join ([0x01], Utf16 ("after")), version)); + + var body = Join ([.. frames]); + var result = Id3v2Tag.Read (Join (TestBuilders.Id3v2.CreateHeader (version, (uint)body.Length), body)); + Assert.IsTrue (result.IsSuccess, result.Error); + return result.Tag!; + } [TestMethod] - [DataRow (Id3v2Version.V23)] - [DataRow (Id3v2Version.V24)] - public void EveryStringProperty_WriteBackOfTheValueRead_IsByteIdentical (Id3v2Version version) + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void EveryStringProperty_WriteBackOverForeignFrames_IsByteIdentical (byte version) { var failures = new List (); var uncovered = new List (); foreach (var property in StringProperties ()) { Id3v2Tag? tag = null; foreach (var candidate in Candidates) { - var probe = new Id3v2Tag (version); + var probe = new Id3v2Tag ((Id3v2Version)version); property.SetValue (probe, candidate); - // A later frame, so a setter that rewrites its frame moves it and changes the bytes. - probe.SetTextFrameValues (property.Name == "Album" ? "TIT2" : "TALB", ["after"]); - probe = Reparse (probe); - if (Equals (property.GetValue (probe), candidate)) { - tag = probe; + if (!Equals (property.GetValue (probe), candidate)) + continue; + var foreign = BuildForeign (probe, version, candidate); + if (Equals (property.GetValue (foreign), candidate)) { + tag = foreign; break; } } @@ -136,8 +167,6 @@ public void EveryStringProperty_WriteBackOfTheValueRead_IsByteIdentical (Id3v2Ve uncovered.Add (property.Name); continue; } - if (NotWriteBackSafe.Contains (property.Name)) - continue; var before = tag.Render ().ToArray (); property.SetValue (tag, property.GetValue (tag)); @@ -165,7 +194,7 @@ public void Year_V23WriteBack_KeepsTheOriginalEncoding () [TestMethod] [DataRow (Id3v2Version.V23)] [DataRow (Id3v2Version.V24)] - public void EmptyString_OverAListWithText_ClearsIt (Id3v2Version version) + public void LeadingEmptyValue_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClears (Id3v2Version version) { var tag = new Id3v2Tag (version); tag.Artist = "x"; @@ -176,9 +205,15 @@ public void EmptyString_OverAListWithText_ClearsIt (Id3v2Version version) foreach (var f in tag.UserTextFrames) f.Value = "\0V2"; tag = Reparse (tag); - Assert.AreEqual ("", tag.Artist); - Assert.AreEqual ("", tag.Genre); - Assert.AreEqual ("", tag.Movement); + Assert.AreEqual ("V2", tag.Artist); + Assert.AreEqual ("V2", tag.Genre); + Assert.AreEqual ("V2", tag.Movement); + var before = Snapshot (tag); + + tag.Artist = tag.Artist; + tag.Genre = tag.Genre; + tag.Movement = tag.Movement; + CollectionAssert.AreEqual (before, Snapshot (Reparse (tag))); tag.Artist = ""; tag.Genre = ""; @@ -288,10 +323,10 @@ public void Movement_WriteBackOfTxxxOnlyName_DoesNotAddAppleFrame () } [TestMethod] - public void Genre_EmptyFirstValue_ReadsEmpty () + public void Genre_EmptyValues_ReadTheFirstNonEmptyValue () { - // An empty first value reads "", like every other text frame. Writing "" back keeps a frame - // whose values are all empty and clears one whose later values hold text. + // Like every other text frame, the genre is the first non-empty value, and "" only when + // every value is empty. Writing back what was read keeps the frame either way. var tag = new Id3v2Tag (Id3v2Version.V24); tag.Genre = "Rock"; tag.Frames.First (f => f.Id == "TCON").Text = ""; @@ -300,8 +335,10 @@ public void Genre_EmptyFirstValue_ReadsEmpty () Assert.AreEqual ("", tag.Frames.First (f => f.Id == "TCON").Text); tag.Frames.First (f => f.Id == "TCON").Text = "\0Pop"; - Assert.AreEqual ("", tag.Genre); + Assert.AreEqual ("Pop", tag.Genre); tag.Genre = tag.Genre; + Assert.AreEqual ("\0Pop", tag.Frames.First (f => f.Id == "TCON").Text); + tag.Genre = ""; Assert.IsNull (tag.GetTextFrame ("TCON")); tag.Genre = "Rock"; diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs index 98fb8894..ecc8aa34 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs @@ -55,10 +55,7 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField_AndAnEditRepl property.SetValue (comment, read); var after = Snapshot (Reparse (comment)); - // "" is a write-back only when no value holds text: an empty first value reads "", - // and "" over a list with text clears it. - var clears = read == "" && before.Any (r => r.Contains ("V2", StringComparison.Ordinal)); - if (clears ? after.Any (r => r.Contains ("V2", StringComparison.Ordinal)) : !before.SequenceEqual (after)) + if (!before.SequenceEqual (after)) failures.Add ($"{property.Name}: [{string.Join (" | ", before)}] -> [{string.Join (" | ", after)}]"); // A case-only edit, or "" over a list whose later values hold text, is not a write-back. @@ -77,7 +74,7 @@ public void EveryStringProperty_UnchangedWriteBack_KeepsEveryField_AndAnEditRepl } [TestMethod] - public void EmptyString_OverFieldsWithText_ClearsThem () + public void LeadingEmptyField_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClears () { var comment = new VorbisComment ("test"); comment.AddField ("ARTIST", ""); @@ -85,7 +82,12 @@ public void EmptyString_OverFieldsWithText_ClearsThem () comment.AddField ("MOVEMENT", ""); comment.AddField ("MOVEMENT", "V2"); comment.AddField ("MOVEMENTNAME", "N"); - Assert.AreEqual ("", comment.Artist); + Assert.AreEqual ("V2", comment.Artist); + Assert.AreEqual ("V2", comment.Movement); + var before = string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value)); + comment.Artist = comment.Artist; + comment.Movement = comment.Movement; + Assert.AreEqual (before, string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value))); comment.Artist = ""; comment.Movement = ""; From 5722d54b6bb0ee7bfd12fcadf4e4a38204b21f33 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 14:21:36 -0700 Subject: [PATCH 19/29] docs: State the first-value, copy, and Picard movement rules --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0785071d..2a927649 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,7 +39,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- Writing back the value a single-value ID3v2, APE, or Vorbis Comment property returned changes nothing, so a multi-value frame, item, or repeated field keeps every value. The comparison is ordinal, so a case-only edit still writes. This covers every ID3v2 string property except `Comment` and `Lyrics` (COMM and USLT can hold several frames; their setters still replace them): every text and TXXX property including the year, the podcast feed URL, and the MusicBrainz recording ID, and the movement number and total. It also covers every text property in APE and every text field in Vorbis Comments. An empty string counts as the value read only when no value of the field holds text, so `= ""` still clears a list whose first value is empty. `null` always clears, and any other value still replaces the list. `CopyTo` always replaces: the target holds the source value afterwards, even when it equals the target's first value. A Vorbis `MOVEMENTNAME` or `ORIGINALYEAR` or an APE `Date` beside a value equal to the copied one is its own field and stays. An ID3v2 genre whose first value is empty now reads as an empty string, not null, like the other text frames. +- A single-value ID3v2, APE, or Vorbis Comment getter returns the first non-empty value, and an empty string only when every value is empty. 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`. This replaces the earlier reading of a leading NUL as an empty first value. Writing back the value read changes nothing, so a multi-value frame, item, or repeated field keeps every value, and `= ""` clears it. The comparison is ordinal, so a case-only edit still writes, and `null` always clears. 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. A copy (`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, and it skips a list the target already holds. Two exceptions keep what the target holds. A source that is the target, or reads from it (a file's combined `Tag` copied into one of its own tags), only adds values the target does not show. A fallback field of its own beside a value equal to the copied one stays: Vorbis `MOVEMENTNAME` or `ORIGINALYEAR`, APE `Date`, and the ID3v2.3 `TDOR` beside `TORY`. +- A Vorbis or APE tag laid out as MusicBrainz Picard writes it, with the movement number in `MOVEMENT` beside `MOVEMENTNAME`, reads and writes the movement name in `MOVEMENTNAME` and the number in `MOVEMENT`. Such a movement is no longer read as the name "2", so a copy from a Picard FLAC no longer writes "2" over an ID3v2 `MVNM`. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. - Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year`, `ORIGINALDATE`, or `MOVEMENT` no longer hides a filled `Date`, `ORIGINALYEAR`, or `MOVEMENTNAME`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. - An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. From 12ccf12469921e8034f72f9a86df0c4ec3907023 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 15:21:26 -0700 Subject: [PATCH 20/29] fix: Match views by their tags and map movements as Picard does Mp3File.Tag builds a new combined view on every read, so a copy from one read into another was not seen as a copy between views over the same tag, and its single-value lists were cut. Tags now expose the tags they read from, and a copy between two that share one skips every value the target already shows. A copy with Extended carries the artist and genre in their lists, so a list the target holds keeps its frames. The ID3v2 comment and lyrics read the first non-empty frame, as text frames do, so a write-back of what is shown changes nothing and "" clears the frames without a description. Vorbis and APE movements follow Picard's tag mapping: the name is MOVEMENTNAME and the number is MOVEMENT. A MOVEMENT that is not a number is still read as the name when no MOVEMENTNAME exists. Clearing one half no longer changes how the other half reads. --- src/TagLibSharp2/Ape/ApeTag.cs | 76 ++++-- src/TagLibSharp2/Core/CombinedTag.cs | 12 +- src/TagLibSharp2/Core/Tag.cs | 227 +++++++++++------- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 29 ++- src/TagLibSharp2/Xiph/FlacTag.cs | 10 +- src/TagLibSharp2/Xiph/VorbisComment.cs | 62 +++-- .../Core/PicardMovementMappingTests.cs | 126 ++++++++++ .../Core/TagCopyReplacesListTests.cs | 60 +++++ .../CrossTaggerCompatibilityTests.cs | 6 +- .../Id3/Id3v2/Id3v2WriteBackTests.cs | 45 +++- .../VorbisCommentExtendedMetadataTests.cs | 38 ++- .../Xiph/VorbisCommentWriteBackTests.cs | 6 +- 12 files changed, 537 insertions(+), 160 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/PicardMovementMappingTests.cs diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 18d2c9be..fa5e57e8 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -676,25 +676,52 @@ public override string? Work { /// /// - /// Uses the MOVEMENT item. MusicBrainz Picard stores the name in MOVEMENTNAME and the number in - /// MOVEMENT (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). When MOVEMENT - /// is a number beside a MOVEMENTNAME, the name is read from and written to MOVEMENTNAME only, and - /// MOVEMENT is left to . + /// Follows MusicBrainz Picard's tag mapping (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html): + /// the movement name is MOVEMENTNAME and the movement number is MOVEMENT. A MOVEMENT that is not a + /// number is still read as the name when there is no MOVEMENTNAME, as earlier versions wrote it. + /// Writing back the value read changes nothing. A new name goes to MOVEMENTNAME, and also to MOVEMENT + /// when MOVEMENT holds a name. Clearing removes MOVEMENTNAME and a MOVEMENT that holds a name; a + /// numeric MOVEMENT stays the number, so a clear never changes how the other half reads. /// public override string? Movement { - get => HasPicardMovement ? GetValue (Keys.MovementName) : GetValue (Keys.Movement); + get { + var name = GetValue (Keys.MovementName); + if (!string.IsNullOrEmpty (name)) + return name; + var legacy = LegacyMovementName; + return string.IsNullOrEmpty (legacy) ? name ?? legacy : legacy; + } set { - if (HasPicardMovement) - SetOrRemoveProperty (Keys.MovementName, value, Movement); - else - SetOrRemoveProperty (Keys.Movement, value, Movement); + if (IsWriteBack (value, Movement)) + return; + var legacy = LegacyMovementName; + if (string.IsNullOrEmpty (value)) { + _items.Remove (Keys.MovementName); + if (legacy is not null) + _items.Remove (Keys.Movement); + return; + } + SetValue (Keys.MovementName, value!); + // A name in MOVEMENT is kept in step, unless the new name is a number, which MOVEMENT would + // turn into the movement number. + if (legacy is not null) { + if (uint.TryParse (value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) + _items.Remove (Keys.Movement); + else + SetValue (Keys.Movement, value!); + } } } /// - /// True for the Picard layout: a non-empty MOVEMENTNAME beside a numeric MOVEMENT. + /// MOVEMENT when it holds a movement name (it is not a number), as earlier versions wrote it; otherwise null. /// - bool HasPicardMovement => !string.IsNullOrEmpty (GetValue (Keys.MovementName)) && ParseMovementNumber (Keys.Movement) is not null; + string? LegacyMovementName { + get { + var value = GetValue (Keys.Movement); + return value is not null && ParseMovementNumber (Keys.Movement) is null ? value : null; + } + } uint? ParseMovementNumber (string key) { @@ -706,22 +733,33 @@ public override string? Movement { /// /// - /// Uses the MOVEMENTNUMBER item. In the Picard layout (see ) without one, - /// the number is read from and written to MOVEMENT, and clearing it removes MOVEMENT. + /// Reads the MOVEMENTNUMBER item, then a numeric MOVEMENT (Picard's movement number). A write goes to MOVEMENT, + /// and to an existing MOVEMENTNUMBER, unless MOVEMENT holds a movement name; then it goes to + /// MOVEMENTNUMBER. Clearing removes MOVEMENTNUMBER and a numeric MOVEMENT. /// public override uint? MovementNumber { - get => ParseMovementNumber (Keys.MovementNumber) ?? (HasPicardMovement ? ParseMovementNumber (Keys.Movement) : null); + get => ParseMovementNumber (Keys.MovementNumber) ?? ParseMovementNumber (Keys.Movement); set { if (IsWriteBack (value, MovementNumber)) return; - var key = HasPicardMovement && !_items.ContainsKey (Keys.MovementNumber) ? Keys.Movement : Keys.MovementNumber; - if (value.HasValue) - SetValue (key, value.Value.ToString (CultureInfo.InvariantCulture)); - else - _items.Remove (key); + if (LegacyMovementName is not null) { + SetNumber (Keys.MovementNumber, value); + return; + } + SetNumber (Keys.Movement, value); + if (value is null || _items.ContainsKey (Keys.MovementNumber)) + SetNumber (Keys.MovementNumber, value); } } + void SetNumber (string key, uint? value) + { + if (value.HasValue) + SetValue (key, value.Value.ToString (CultureInfo.InvariantCulture)); + else + _items.Remove (key); + } + /// public override uint? MovementTotal { get { diff --git a/src/TagLibSharp2/Core/CombinedTag.cs b/src/TagLibSharp2/Core/CombinedTag.cs index 7b93e551..03bc347c 100644 --- a/src/TagLibSharp2/Core/CombinedTag.cs +++ b/src/TagLibSharp2/Core/CombinedTag.cs @@ -158,15 +158,15 @@ public override string? Year { FirstNonEmptyString (tag => tag.ReadCopyableDate ()); /// - internal override bool ReadsFrom (Tag tag) + internal override IEnumerable Leaves () { - if (base.ReadsFrom (tag)) - return true; + yield return this; foreach (var inner in _tags) { - if (inner is not null && inner.ReadsFrom (tag)) - return true; + if (inner is null) + continue; + foreach (var leaf in inner.Leaves ()) + yield return leaf; } - return false; } /// diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 979974ff..3d067ef9 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -376,8 +376,8 @@ public virtual string[] Composers { /// /// In ID3v2, this is read from Apple's MVNM frame, then a TXXX frame with description "MOVEMENT". /// A write stores the name in both, and a clear removes both. - /// In Vorbis Comments, this is stored as MOVEMENT or MOVEMENTNAME; a new value also replaces an - /// existing MOVEMENTNAME, and writing back the value already read changes nothing. + /// In Vorbis Comments and APE, this is MOVEMENTNAME (MusicBrainz Picard's mapping); a MOVEMENT that + /// is not a number is also read as the name when there is no MOVEMENTNAME. /// Not all tag formats support this field. Default implementation returns null. /// /// @@ -394,7 +394,7 @@ public virtual string[] Composers { /// /// In ID3v2, this is read from the index half of Apple's MVIN frame ("2/4"), then a TXXX frame /// with description "MOVEMENTNUMBER". A write updates both and keeps the total half of MVIN. - /// In Vorbis Comments, this is stored as MOVEMENTNUMBER. + /// In Vorbis Comments and APE, this is MOVEMENTNUMBER or a numeric MOVEMENT (Picard's mapping). /// Not all tag formats support this field. Default implementation returns null. /// /// @@ -1191,14 +1191,17 @@ public virtual ValidationResult Validate () /// /// Only non-null values are copied. Every source value is read before any is written. The target's /// existing values are overwritten for any property that has a non-null value in the source, and a - /// source value that equals the target's first value still replaces the target's list; a list the - /// target already holds is left as it is. + /// source value that equals the target's first value still replaces the target's list. A list + /// (Performers, AlbumArtists, Composers, Genres and the sort and role lists) that the target already + /// holds is left as it is; with , Artist and Genre are carried by + /// those lists, so a Basic copy alone is what writes the single name over a list. /// /// - /// When the source is the target or reads from it (a file's combined Tag copied into one of its - /// own tags), the copy only adds values the target does not show. A fallback field of its own beside a - /// value equal to the copied one stays: Vorbis MOVEMENTNAME or ORIGINALYEAR, APE Date, and an - /// ID3v2.3 TDOR beside TORY. + /// 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), the copy only adds + /// values the target does not show. A fallback field of its own beside a value equal to the copied one + /// stays: Vorbis ORIGINALYEAR, APE Date, and an ID3v2.3 TDOR beside TORY. Pictures are outside both + /// rules: a non-empty source picture list always replaces the target's. /// /// /// This is useful for converting between tag formats or synchronizing metadata @@ -1241,12 +1244,15 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) var writes = SnapshotCopyWrites (options); - // A source that reads from the target, or a target that forwards to the source, already shows - // the target's values. Each is then a write-back and changes nothing (IsWriteBack), so only - // values the target does not hold arrive and its lists stay whole. - if (ReadsFrom (target) || target.ReadsFrom (this)) { - foreach (var write in writes) - write (target); + // A source and target that read from a common tag (a tag copied into itself, or a file's view + // copied into one of its tags or into another view over them) already show the target's values. + // A value the target already shows is skipped, and any other one is written as a write-back + // (no copy scope), so only values the target does not hold arrive and its lists stay whole. + if (SharesTagWith (target)) { + foreach (var write in writes) { + if (!write.Shows (target)) + write.Write (target); + } return; } @@ -1255,43 +1261,65 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) t_copyDepth++; try { foreach (var write in writes) - write (target); + write.Write (target); } finally { t_copyDepth--; } } /// - /// True when this tag is or reads its values from it, as a file's combined - /// view reads from the tags it combines. + /// This tag and every tag it reads its values from. A view, such as a file's combined tag, yields + /// itself and the leaves of the tags it combines. /// - internal virtual bool ReadsFrom (Tag tag) => ReferenceEquals (this, tag); + internal virtual IEnumerable Leaves () + { + yield return this; + } + + /// + /// True when this tag and read from a common tag. Two views over the same + /// tags share leaves even when they are different objects, as two reads of Mp3File.Tag are. + /// + internal bool SharesTagWith (Tag other) + { + var mine = new List (Leaves ()); + foreach (var leaf in other.Leaves ()) { + for (var i = 0; i < mine.Count; i++) { + if (ReferenceEquals (mine[i], leaf)) + return true; + } + } + return false; + } /// /// Reads every value to copy before writing any, so a source that reads from the target (a file's /// combined view copied into one of its tags) sees the target as it was, not half-written. /// - List> SnapshotCopyWrites (TagCopyOptions options) + List SnapshotCopyWrites (TagCopyOptions options) { - var writes = new List> (); + var writes = new List (); // Basic metadata (always copied unless explicitly excluded) if ((options & TagCopyOptions.Basic) != 0) { if (Title is not null) - Queue (writes, Title, static (t, v) => t.Title = v); - if (Artist is not null) - Queue (writes, Artist, static (t, v) => t.Artist = v); + Queue (writes, Title, static t => t.Title, static (t, v) => t.Title = v); + // With Extended, the Performers and Genres lists below carry these names; writing the first + // name here too would replace a list the target already holds before the list write. + var listsFollow = (options & TagCopyOptions.Extended) != 0; + if (Artist is not null && !(listsFollow && Performers is { Length: > 0 })) + Queue (writes, Artist, static t => t.Artist, static (t, v) => t.Artist = v); if (Album is not null) - Queue (writes, Album, static (t, v) => t.Album = v); + Queue (writes, Album, static t => t.Album, static (t, v) => t.Album = v); var copyableDate = CopyableDate; if (copyableDate is not null) - Queue (writes, copyableDate, static (t, v) => t.Year = v); + Queue (writes, copyableDate, static t => t.ReadCopyableDate (), static (t, v) => t.Year = v); if (Comment is not null) - Queue (writes, Comment, static (t, v) => t.Comment = v); - if (Genre is not null) - Queue (writes, Genre, static (t, v) => t.Genre = v); + Queue (writes, Comment, static t => t.Comment, static (t, v) => t.Comment = v); + if (Genre is not null && !(listsFollow && Genres is { Length: > 0 })) + Queue (writes, Genre, static t => t.Genre, static (t, v) => t.Genre = v); if (Track.HasValue) - Queue (writes, Track, static (t, v) => t.Track = v); + Queue (writes, Track, static t => t.Track, static (t, v) => t.Track = v); } // Extended metadata @@ -1310,71 +1338,71 @@ List> SnapshotCopyWrites (TagCopyOptions options) // The singular value is the first entry. Writing it after the array // replaces the whole list with that one name. if (AlbumArtist is not null && AlbumArtists is not { Length: > 0 }) - Queue (writes, AlbumArtist, static (t, v) => t.AlbumArtist = v); + Queue (writes, AlbumArtist, static t => t.AlbumArtist, static (t, v) => t.AlbumArtist = v); if (Composer is not null && Composers is not { Length: > 0 }) - Queue (writes, Composer, static (t, v) => t.Composer = v); + Queue (writes, Composer, static t => t.Composer, static (t, v) => t.Composer = v); if (Conductor is not null) - Queue (writes, Conductor, static (t, v) => t.Conductor = v); + Queue (writes, Conductor, static t => t.Conductor, static (t, v) => t.Conductor = v); if (Copyright is not null) - Queue (writes, Copyright, static (t, v) => t.Copyright = v); + Queue (writes, Copyright, static t => t.Copyright, static (t, v) => t.Copyright = v); if (DiscNumber.HasValue) - Queue (writes, DiscNumber, static (t, v) => t.DiscNumber = v); + Queue (writes, DiscNumber, static t => t.DiscNumber, static (t, v) => t.DiscNumber = v); if (TotalDiscs.HasValue) - Queue (writes, TotalDiscs, static (t, v) => t.TotalDiscs = v); + Queue (writes, TotalDiscs, static t => t.TotalDiscs, static (t, v) => t.TotalDiscs = v); if (DiscSubtitle is not null) - Queue (writes, DiscSubtitle, static (t, v) => t.DiscSubtitle = v); + Queue (writes, DiscSubtitle, static t => t.DiscSubtitle, static (t, v) => t.DiscSubtitle = v); if (TotalTracks.HasValue) - Queue (writes, TotalTracks, static (t, v) => t.TotalTracks = v); + Queue (writes, TotalTracks, static t => t.TotalTracks, static (t, v) => t.TotalTracks = v); if (BeatsPerMinute.HasValue) - Queue (writes, BeatsPerMinute, static (t, v) => t.BeatsPerMinute = v); + Queue (writes, BeatsPerMinute, static t => t.BeatsPerMinute, static (t, v) => t.BeatsPerMinute = v); if (Lyrics is not null) - Queue (writes, Lyrics, static (t, v) => t.Lyrics = v); + Queue (writes, Lyrics, static t => t.Lyrics, static (t, v) => t.Lyrics = v); if (Isrc is not null) - Queue (writes, Isrc, static (t, v) => t.Isrc = v); + Queue (writes, Isrc, static t => t.Isrc, static (t, v) => t.Isrc = v); if (Publisher is not null) - Queue (writes, Publisher, static (t, v) => t.Publisher = v); + Queue (writes, Publisher, static t => t.Publisher, static (t, v) => t.Publisher = v); if (EncodedBy is not null) - Queue (writes, EncodedBy, static (t, v) => t.EncodedBy = v); + Queue (writes, EncodedBy, static t => t.EncodedBy, static (t, v) => t.EncodedBy = v); if (EncoderSettings is not null) - Queue (writes, EncoderSettings, static (t, v) => t.EncoderSettings = v); + Queue (writes, EncoderSettings, static t => t.EncoderSettings, static (t, v) => t.EncoderSettings = v); if (Grouping is not null) - Queue (writes, Grouping, static (t, v) => t.Grouping = v); + Queue (writes, Grouping, static t => t.Grouping, static (t, v) => t.Grouping = v); if (Subtitle is not null) - Queue (writes, Subtitle, static (t, v) => t.Subtitle = v); + Queue (writes, Subtitle, static t => t.Subtitle, static (t, v) => t.Subtitle = v); if (Remixer is not null) - Queue (writes, Remixer, static (t, v) => t.Remixer = v); + Queue (writes, Remixer, static t => t.Remixer, static (t, v) => t.Remixer = v); if (InitialKey is not null) - Queue (writes, InitialKey, static (t, v) => t.InitialKey = v); + Queue (writes, InitialKey, static t => t.InitialKey, static (t, v) => t.InitialKey = v); if (Mood is not null) - Queue (writes, Mood, static (t, v) => t.Mood = v); + Queue (writes, Mood, static t => t.Mood, static (t, v) => t.Mood = v); if (MediaType is not null) - Queue (writes, MediaType, static (t, v) => t.MediaType = v); + Queue (writes, MediaType, static t => t.MediaType, static (t, v) => t.MediaType = v); if (Language is not null) - Queue (writes, Language, static (t, v) => t.Language = v); + Queue (writes, Language, static t => t.Language, static (t, v) => t.Language = v); if (Barcode is not null) - Queue (writes, Barcode, static (t, v) => t.Barcode = v); + Queue (writes, Barcode, static t => t.Barcode, static (t, v) => t.Barcode = v); if (CatalogNumber is not null) - Queue (writes, CatalogNumber, static (t, v) => t.CatalogNumber = v); + Queue (writes, CatalogNumber, static t => t.CatalogNumber, static (t, v) => t.CatalogNumber = v); if (OriginalReleaseDate is not null) - Queue (writes, OriginalReleaseDate, static (t, v) => t.OriginalReleaseDate = v); + Queue (writes, OriginalReleaseDate, static t => t.OriginalReleaseDate, static (t, v) => t.OriginalReleaseDate = v); if (Description is not null) - Queue (writes, Description, static (t, v) => t.Description = v); + Queue (writes, Description, static t => t.Description, static (t, v) => t.Description = v); if (DateTagged is not null) - Queue (writes, DateTagged, static (t, v) => t.DateTagged = v); + Queue (writes, DateTagged, static t => t.DateTagged, static (t, v) => t.DateTagged = v); if (AmazonId is not null) - Queue (writes, AmazonId, static (t, v) => t.AmazonId = v); + Queue (writes, AmazonId, static t => t.AmazonId, static (t, v) => t.AmazonId = v); if (IsCompilation) - Queue (writes, true, static (t, v) => t.IsCompilation = v); + Queue (writes, true, static t => t.IsCompilation, static (t, v) => t.IsCompilation = v); // Classical music metadata if (Work is not null) - Queue (writes, Work, static (t, v) => t.Work = v); + Queue (writes, Work, static t => t.Work, static (t, v) => t.Work = v); if (Movement is not null) - Queue (writes, Movement, static (t, v) => t.Movement = v); + Queue (writes, Movement, static t => t.Movement, static (t, v) => t.Movement = v); if (MovementNumber.HasValue) - Queue (writes, MovementNumber, static (t, v) => t.MovementNumber = v); + Queue (writes, MovementNumber, static t => t.MovementNumber, static (t, v) => t.MovementNumber = v); if (MovementTotal.HasValue) - Queue (writes, MovementTotal, static (t, v) => t.MovementTotal = v); + Queue (writes, MovementTotal, static t => t.MovementTotal, static (t, v) => t.MovementTotal = v); // Performers role if (PerformersRole is { Length: > 0 }) @@ -1384,15 +1412,15 @@ List> SnapshotCopyWrites (TagCopyOptions options) // Sort order if ((options & TagCopyOptions.SortOrder) != 0) { if (AlbumSort is not null) - Queue (writes, AlbumSort, static (t, v) => t.AlbumSort = v); + Queue (writes, AlbumSort, static t => t.AlbumSort, static (t, v) => t.AlbumSort = v); if (ArtistSort is not null) - Queue (writes, ArtistSort, static (t, v) => t.ArtistSort = v); + Queue (writes, ArtistSort, static t => t.ArtistSort, static (t, v) => t.ArtistSort = v); if (TitleSort is not null) - Queue (writes, TitleSort, static (t, v) => t.TitleSort = v); + Queue (writes, TitleSort, static t => t.TitleSort, static (t, v) => t.TitleSort = v); if (AlbumArtistSort is not null) - Queue (writes, AlbumArtistSort, static (t, v) => t.AlbumArtistSort = v); + Queue (writes, AlbumArtistSort, static t => t.AlbumArtistSort, static (t, v) => t.AlbumArtistSort = v); if (ComposerSort is not null) - Queue (writes, ComposerSort, static (t, v) => t.ComposerSort = v); + Queue (writes, ComposerSort, static t => t.ComposerSort, static (t, v) => t.ComposerSort = v); if (PerformersSort is { Length: > 0 }) QueueList (writes, PerformersSort, static t => t.PerformersSort, static (t, v) => t.PerformersSort = v); if (AlbumArtistsSort is { Length: > 0 }) @@ -1404,69 +1432,82 @@ List> SnapshotCopyWrites (TagCopyOptions options) // ReplayGain and R128 if ((options & TagCopyOptions.ReplayGain) != 0) { if (ReplayGainTrackGain is not null) - Queue (writes, ReplayGainTrackGain, static (t, v) => t.ReplayGainTrackGain = v); + Queue (writes, ReplayGainTrackGain, static t => t.ReplayGainTrackGain, static (t, v) => t.ReplayGainTrackGain = v); if (ReplayGainTrackPeak is not null) - Queue (writes, ReplayGainTrackPeak, static (t, v) => t.ReplayGainTrackPeak = v); + Queue (writes, ReplayGainTrackPeak, static t => t.ReplayGainTrackPeak, static (t, v) => t.ReplayGainTrackPeak = v); if (ReplayGainAlbumGain is not null) - Queue (writes, ReplayGainAlbumGain, static (t, v) => t.ReplayGainAlbumGain = v); + Queue (writes, ReplayGainAlbumGain, static t => t.ReplayGainAlbumGain, static (t, v) => t.ReplayGainAlbumGain = v); if (ReplayGainAlbumPeak is not null) - Queue (writes, ReplayGainAlbumPeak, static (t, v) => t.ReplayGainAlbumPeak = v); + Queue (writes, ReplayGainAlbumPeak, static t => t.ReplayGainAlbumPeak, static (t, v) => t.ReplayGainAlbumPeak = v); if (R128TrackGain is not null) - Queue (writes, R128TrackGain, static (t, v) => t.R128TrackGain = v); + Queue (writes, R128TrackGain, static t => t.R128TrackGain, static (t, v) => t.R128TrackGain = v); if (R128AlbumGain is not null) - Queue (writes, R128AlbumGain, static (t, v) => t.R128AlbumGain = v); + Queue (writes, R128AlbumGain, static t => t.R128AlbumGain, static (t, v) => t.R128AlbumGain = v); } // MusicBrainz IDs if ((options & TagCopyOptions.MusicBrainz) != 0) { if (MusicBrainzTrackId is not null) - Queue (writes, MusicBrainzTrackId, static (t, v) => t.MusicBrainzTrackId = v); + Queue (writes, MusicBrainzTrackId, static t => t.MusicBrainzTrackId, static (t, v) => t.MusicBrainzTrackId = v); if (MusicBrainzReleaseId is not null) - Queue (writes, MusicBrainzReleaseId, static (t, v) => t.MusicBrainzReleaseId = v); + Queue (writes, MusicBrainzReleaseId, static t => t.MusicBrainzReleaseId, static (t, v) => t.MusicBrainzReleaseId = v); if (MusicBrainzArtistId is not null) - Queue (writes, MusicBrainzArtistId, static (t, v) => t.MusicBrainzArtistId = v); + Queue (writes, MusicBrainzArtistId, static t => t.MusicBrainzArtistId, static (t, v) => t.MusicBrainzArtistId = v); if (MusicBrainzReleaseGroupId is not null) - Queue (writes, MusicBrainzReleaseGroupId, static (t, v) => t.MusicBrainzReleaseGroupId = v); + Queue (writes, MusicBrainzReleaseGroupId, static t => t.MusicBrainzReleaseGroupId, static (t, v) => t.MusicBrainzReleaseGroupId = v); if (MusicBrainzAlbumArtistId is not null) - Queue (writes, MusicBrainzAlbumArtistId, static (t, v) => t.MusicBrainzAlbumArtistId = v); + Queue (writes, MusicBrainzAlbumArtistId, static t => t.MusicBrainzAlbumArtistId, static (t, v) => t.MusicBrainzAlbumArtistId = v); if (MusicBrainzRecordingId is not null) - Queue (writes, MusicBrainzRecordingId, static (t, v) => t.MusicBrainzRecordingId = v); + Queue (writes, MusicBrainzRecordingId, static t => t.MusicBrainzRecordingId, static (t, v) => t.MusicBrainzRecordingId = v); if (MusicBrainzWorkId is not null) - Queue (writes, MusicBrainzWorkId, static (t, v) => t.MusicBrainzWorkId = v); + Queue (writes, MusicBrainzWorkId, static t => t.MusicBrainzWorkId, static (t, v) => t.MusicBrainzWorkId = v); if (MusicBrainzDiscId is not null) - Queue (writes, MusicBrainzDiscId, static (t, v) => t.MusicBrainzDiscId = v); + Queue (writes, MusicBrainzDiscId, static t => t.MusicBrainzDiscId, static (t, v) => t.MusicBrainzDiscId = v); if (MusicBrainzReleaseStatus is not null) - Queue (writes, MusicBrainzReleaseStatus, static (t, v) => t.MusicBrainzReleaseStatus = v); + Queue (writes, MusicBrainzReleaseStatus, static t => t.MusicBrainzReleaseStatus, static (t, v) => t.MusicBrainzReleaseStatus = v); if (MusicBrainzReleaseType is not null) - Queue (writes, MusicBrainzReleaseType, static (t, v) => t.MusicBrainzReleaseType = v); + Queue (writes, MusicBrainzReleaseType, static t => t.MusicBrainzReleaseType, static (t, v) => t.MusicBrainzReleaseType = v); if (MusicBrainzReleaseCountry is not null) - Queue (writes, MusicBrainzReleaseCountry, static (t, v) => t.MusicBrainzReleaseCountry = v); + Queue (writes, MusicBrainzReleaseCountry, static t => t.MusicBrainzReleaseCountry, static (t, v) => t.MusicBrainzReleaseCountry = v); if (AcoustIdId is not null) - Queue (writes, AcoustIdId, static (t, v) => t.AcoustIdId = v); + Queue (writes, AcoustIdId, static t => t.AcoustIdId, static (t, v) => t.AcoustIdId = v); if (AcoustIdFingerprint is not null) - Queue (writes, AcoustIdFingerprint, static (t, v) => t.AcoustIdFingerprint = v); + Queue (writes, AcoustIdFingerprint, static t => t.AcoustIdFingerprint, static (t, v) => t.AcoustIdFingerprint = v); } // Pictures if ((options & TagCopyOptions.Pictures) != 0) { if (Pictures is { Length: > 0 }) - Queue (writes, Pictures, static (t, v) => t.Pictures = v); + Queue (writes, Pictures, static t => t.Pictures, static (t, v) => t.Pictures = v); } return writes; } - static void Queue (List> writes, T value, Action set) => - writes.Add (t => set (t, value)); + /// + /// Queues a write of . reads what the target shows for + /// the same property, so a copy between tags that share a tag can skip a value the target already + /// shows. Arrays compare by reference here, so a picture list is always written. + /// + static void Queue (List writes, T value, Func get, Action set) => + writes.Add (new CopyWrite (t => EqualityComparer.Default.Equals (get (t), value), t => set (t, value))); /// /// Queues a list write that is skipped when the target already holds exactly that list, so a copy /// of a list the target shows leaves its frames, items, or fields as they are. /// - static void QueueList (List> writes, string[] value, Func get, Action set) => - writes.Add (t => { - if (get (t) is not { } current || !current.AsSpan ().SequenceEqual (value)) + static void QueueList (List writes, string[] value, Func get, Action set) + { + bool Holds (Tag t) => get (t) is { } current && current.AsSpan ().SequenceEqual (value); + writes.Add (new CopyWrite (Holds, t => { + if (!Holds (t)) set (t, value); - }); + })); + } + + /// + /// One queued copy write, and whether the target already shows its value. + /// + readonly record struct CopyWrite (Func Shows, Action Write); } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 186dce5b..dbc2c451 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -2129,20 +2129,28 @@ void InvalidatePerformersRoleCache () if (_comments.Count == 0) return null; - // Prefer comments with empty description (the user-facing comment). + // The first non-empty comment without a description (the user-facing comment, in any language), + // as for text frames. ffprobe and TagLib# show the same frame. + string? empty = null; for (var i = 0; i < _comments.Count; i++) { - if (string.IsNullOrEmpty (_comments[i].Description)) + if (!string.IsNullOrEmpty (_comments[i].Description)) + continue; + if (_comments[i].Text.Length != 0) return _comments[i].Text; + empty = ""; } // iTunes stores gapless and normalization data in COM frames. Those are // not the comment. Any other described comment can still be shown. for (var i = 0; i < _comments.Count; i++) { - if (!IsToolPrivateComment (_comments[i].Description)) + if (IsToolPrivateComment (_comments[i].Description)) + continue; + if (_comments[i].Text.Length != 0) return _comments[i].Text; + empty = ""; } - return null; + return empty; } static bool IsToolPrivateComment (string? description) => @@ -2271,14 +2279,19 @@ public void RemoveUserTextFrames (string description) if (_lyricsFrames.Count == 0) return null; - // Prefer lyrics with empty description (default lyrics) + // The first non-empty lyrics without a description (the default lyrics, in any language), + // then the first non-empty lyrics of any description, and "" when every frame is empty. + for (var i = 0; i < _lyricsFrames.Count; i++) { + if (string.IsNullOrEmpty (_lyricsFrames[i].Description) && _lyricsFrames[i].Text.Length != 0) + return _lyricsFrames[i].Text; + } + for (var i = 0; i < _lyricsFrames.Count; i++) { - if (string.IsNullOrEmpty (_lyricsFrames[i].Description)) + if (_lyricsFrames[i].Text.Length != 0) return _lyricsFrames[i].Text; } - // Fall back to first lyrics - return _lyricsFrames[0].Text; + return ""; } /// diff --git a/src/TagLibSharp2/Xiph/FlacTag.cs b/src/TagLibSharp2/Xiph/FlacTag.cs index cb702e00..ce6e7bd8 100644 --- a/src/TagLibSharp2/Xiph/FlacTag.cs +++ b/src/TagLibSharp2/Xiph/FlacTag.cs @@ -113,8 +113,14 @@ public override string? Movement { } /// - internal override bool ReadsFrom (Tag tag) => - base.ReadsFrom (tag) || (_file.VorbisComment?.ReadsFrom (tag) ?? false); + internal override IEnumerable Leaves () + { + yield return this; + if (_file.VorbisComment is { } comment) { + foreach (var leaf in comment.Leaves ()) + yield return leaf; + } + } /// public override string? Copyright { diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 0b217498..8107a795 100644 --- a/src/TagLibSharp2/Xiph/VorbisComment.cs +++ b/src/TagLibSharp2/Xiph/VorbisComment.cs @@ -272,47 +272,69 @@ public override string? Work { /// /// - /// Uses the MOVEMENT field. Falls back to MOVEMENTNAME when MOVEMENT is missing or empty. - /// Writing back the value already read changes nothing. A new value is written to MOVEMENT and to - /// an existing MOVEMENTNAME. Clearing removes both. - /// MusicBrainz Picard and Mp3tag store the name in MOVEMENTNAME and the number in MOVEMENT - /// (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html). When MOVEMENT is a - /// number beside a MOVEMENTNAME, the name is read from and written to MOVEMENTNAME only, and - /// MOVEMENT is left to . + /// Follows MusicBrainz Picard's tag mapping (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html): + /// the movement name is MOVEMENTNAME and the movement number is MOVEMENT. A MOVEMENT that is not a + /// number is still read as the name when there is no MOVEMENTNAME, as earlier versions wrote it. + /// Writing back the value read changes nothing. A new name goes to MOVEMENTNAME, and also to MOVEMENT + /// when MOVEMENT holds a name. Clearing removes MOVEMENTNAME and a MOVEMENT that holds a name; a + /// numeric MOVEMENT stays the number, so a clear never changes how the other half reads. /// public override string? Movement { - get => HasPicardMovement ? GetValue ("MOVEMENTNAME") : GetValueOrFallback ("MOVEMENT", "MOVEMENTNAME"); + get { + var name = GetValue ("MOVEMENTNAME"); + if (!string.IsNullOrEmpty (name)) + return name; + var legacy = LegacyMovementName; + return string.IsNullOrEmpty (legacy) ? name ?? legacy : legacy; + } set { - if (HasPicardMovement) - SetValueProperty ("MOVEMENTNAME", value, Movement); - else - SetValueWithFallback ("MOVEMENT", value, "MOVEMENTNAME", static v => v); + if (IsWriteBack (value, Movement)) + return; + // A name in MOVEMENT is kept in step with a new name, and removed by a clear ("" leaves an + // empty MOVEMENTNAME, as "" does for any field) or by a numeric name, which MOVEMENT would + // turn into the movement number. + if (LegacyMovementName is not null) { + if (string.IsNullOrEmpty (value) || TryParseUInt (value, out _)) + RemoveAll ("MOVEMENT"); + else + SetValue ("MOVEMENT", value); + } + SetValue ("MOVEMENTNAME", value); } } /// - /// True for the Picard layout: a non-empty MOVEMENTNAME beside a numeric MOVEMENT. + /// MOVEMENT when it holds a movement name (it is not a number), as earlier versions wrote it; otherwise null. /// - bool HasPicardMovement => !string.IsNullOrEmpty (GetValue ("MOVEMENTNAME")) && TryParseUInt (GetValue ("MOVEMENT"), out _); + string? LegacyMovementName { + get { + var value = GetValue ("MOVEMENT"); + return value is not null && !TryParseUInt (value, out _) ? value : null; + } + } /// /// - /// Uses the MOVEMENTNUMBER field. In the Picard layout (see ) without one, - /// the number is read from and written to MOVEMENT, and clearing it removes MOVEMENT. + /// Reads MOVEMENTNUMBER, then a numeric MOVEMENT (Picard's movement number). A write goes to MOVEMENT, + /// and to an existing MOVEMENTNUMBER, unless MOVEMENT holds a movement name; then it goes to + /// MOVEMENTNUMBER. Clearing removes MOVEMENTNUMBER and a numeric MOVEMENT. /// public override uint? MovementNumber { get { if (TryParseUInt (GetValue ("MOVEMENTNUMBER"), out var num)) return num; - return HasPicardMovement && TryParseUInt (GetValue ("MOVEMENT"), out num) ? num : null; + return TryParseUInt (GetValue ("MOVEMENT"), out num) ? num : null; } set { if (IsWriteBack (value, MovementNumber)) return; var text = value?.ToString (System.Globalization.CultureInfo.InvariantCulture); - if (HasPicardMovement && GetValue ("MOVEMENTNUMBER") is null) - SetValue ("MOVEMENT", text); - else + if (LegacyMovementName is not null) { + SetValue ("MOVEMENTNUMBER", text); + return; + } + SetValue ("MOVEMENT", text); + if (text is null || GetValue ("MOVEMENTNUMBER") is not null) SetValue ("MOVEMENTNUMBER", text); } } diff --git a/tests/TagLibSharp2.Tests/Core/PicardMovementMappingTests.cs b/tests/TagLibSharp2.Tests/Core/PicardMovementMappingTests.cs new file mode 100644 index 00000000..c5b77619 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/PicardMovementMappingTests.cs @@ -0,0 +1,126 @@ +// 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.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// Vorbis and APE movements follow MusicBrainz Picard's tag mapping +/// (https://picard-docs.musicbrainz.org/en/v3.0/appendices/tag_mapping.html): the name is +/// MOVEMENTNAME and the number is MOVEMENT. Setting or clearing one half never changes how the +/// other half reads, in any layout. +/// +[TestClass] +[TestCategory ("Unit")] +public class PicardMovementMappingTests +{ + static readonly (string Name, (string Key, string Value)[] Fields)[] Layouts = [ + ("picard", [("MOVEMENT", "2"), ("MOVEMENTNAME", "Allegro")]), + ("picard number only", [("MOVEMENT", "2")]), + ("picard name only", [("MOVEMENTNAME", "Allegro")]), + ("picard + MOVEMENTNUMBER", [("MOVEMENT", "2"), ("MOVEMENTNAME", "Allegro"), ("MOVEMENTNUMBER", "3")]), + ("legacy name", [("MOVEMENT", "Allegro")]), + ("legacy name + number", [("MOVEMENT", "Allegro"), ("MOVEMENTNUMBER", "2")]), + ("numeric name", [("MOVEMENTNAME", "1812"), ("MOVEMENT", "4")]), + ("empty", []), + ]; + + static Tag Build (string format, (string Key, string Value)[] fields) + { + if (format == "vorbis") { + var comment = new VorbisComment ("test"); + foreach (var (key, value) in fields) + comment.AddField (key, value); + return VorbisComment.Read (comment.Render ().Span).Tag!; + } + + var ape = new ApeTag (); + foreach (var (key, value) in fields) + ape.SetValue (key, value); + return ApeTag.Parse (ape.RenderWithOptions (includeHeader: true).Span).Tag!; + } + + static Tag Reparse (Tag tag) => tag is VorbisComment + ? VorbisComment.Read (tag.Render ().Span).Tag! + : ApeTag.Parse (((ApeTag)tag).RenderWithOptions (includeHeader: true).Span).Tag!; + + [TestMethod] + [DataRow ("vorbis")] + [DataRow ("ape")] + public void SetOrClearOneHalf_LeavesTheOtherHalfAsItRead (string format) + { + var failures = new List (); + foreach (var (layout, fields) in Layouts) { + var ops = new (string Name, Action Apply, bool Name_, object? Expected)[] { + ("Movement = null", t => t.Movement = null, true, null), + ("Movement = X", t => t.Movement = "X", true, "X"), + ("Movement = 99", t => t.Movement = "99", true, "99"), + ("MovementNumber = null", t => t.MovementNumber = null, false, null), + ("MovementNumber = 7", t => t.MovementNumber = 7, false, 7u), + }; + foreach (var (op, apply, nameHalf, expected) in ops) { + var tag = Build (format, fields); + var name = tag.Movement; + var number = tag.MovementNumber; + + apply (tag); + foreach (var (side, t) in new[] { ("live", tag), ("reparsed", Reparse (tag)) }) { + var gotName = t.Movement; + var gotNumber = t.MovementNumber; + var ok = nameHalf + ? Equals (gotName, expected) && gotNumber == number + : gotNumber == (uint?)expected && gotName == name; + if (!ok) + failures.Add ($"{layout} {op} {side}: name {name} -> {gotName}, number {number} -> {gotNumber}"); + } + } + } + + Assert.IsEmpty (failures, string.Join ("\n", failures)); + } + + [TestMethod] + [DataRow ("vorbis")] + [DataRow ("ape")] + public void PicardLayout_ReadsNameAndNumber_AndWritesThePicardKeys (string format) + { + var tag = Build (format, [("MOVEMENT", "2"), ("MOVEMENTNAME", "Allegro"), ("MOVEMENTTOTAL", "4")]); + Assert.AreEqual ("Allegro", tag.Movement); + Assert.AreEqual (2u, tag.MovementNumber); + Assert.AreEqual (4u, tag.MovementTotal); + + tag.Movement = tag.Movement; + tag.MovementNumber = tag.MovementNumber; + Assert.AreEqual ("MOVEMENT=2|MOVEMENTNAME=Allegro|MOVEMENTNUMBER=", Raw (tag)); + + tag.MovementNumber = 5; + tag.Movement = "Adagio"; + Assert.AreEqual ("MOVEMENT=5|MOVEMENTNAME=Adagio|MOVEMENTNUMBER=", Raw (tag)); + + tag.MovementNumber = null; + Assert.AreEqual ("MOVEMENT=|MOVEMENTNAME=Adagio|MOVEMENTNUMBER=", Raw (tag)); + Assert.AreEqual ("Adagio", tag.Movement); + } + + [TestMethod] + [DataRow ("vorbis")] + [DataRow ("ape")] + public void MovementNumber_WriteBack_KeepsTheStoredText (string format) + { + var tag = Build (format, [("MOVEMENTNUMBER", "03"), ("MOVEMENT", "Allegro")]); + Assert.AreEqual (3u, tag.MovementNumber); + + tag.MovementNumber = tag.MovementNumber; + + Assert.AreEqual ("MOVEMENT=Allegro|MOVEMENTNAME=|MOVEMENTNUMBER=03", Raw (tag)); + } + + static string Raw (Tag tag) + { + string Get (string key) => tag is VorbisComment c ? string.Join (",", c.GetValues (key)) : ((ApeTag)tag).GetValue (key) ?? ""; + return $"MOVEMENT={Get ("MOVEMENT")}|MOVEMENTNAME={Get ("MOVEMENTNAME")}|MOVEMENTNUMBER={Get ("MOVEMENTNUMBER")}"; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index e68d7a19..e1e09cd3 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -221,6 +221,7 @@ static Id3v2Tag PicardId3 (Id3v2Version version) tag.Performers = ["P1", "P2"]; tag.Genres = ["Rock", "Pop"]; tag.SetTextFrameValues ("TPUB", ["Lab1", "Lab2"]); + tag.SetTextFrameValues ("TSRC", ["ISRC1", "ISRC2"]); tag.AddUserTextFrame (new TagLibSharp2.Id3.Id3v2.Frames.UserTextFrame ("CATALOGNUMBER", "CAT1\0CAT2")); return Id3v2Tag.Read (tag.Render ().Span).Tag!; } @@ -242,12 +243,23 @@ public void Copy_FromAViewOverTheTarget_KeepsEveryList (Id3v2Version version) tag.CopyTo (tag, TagCopyOptions.All); CollectionAssert.AreEqual (before, Frames (tag)); + // Two different views over the same tag share it, though they are different objects. + new CombinedTag (tag, null).CopyTo (new CombinedTag (tag, null), TagCopyOptions.All); + CollectionAssert.AreEqual (before, Frames (tag)); + // Mp3File.Tag is a CombinedTag over the file's ID3v2 and ID3v1 tags. byte[] mpeg = [0xFF, 0xFB, 0x90, 0x00, .. new byte[413]]; var mp3 = Mp3File.Read ([.. tag.Render ().Span, .. mpeg]).File!; var fileBefore = Frames (mp3.Id3v2Tag!); mp3.Tag!.CopyTo (mp3.Id3v2Tag!, TagCopyOptions.All); CollectionAssert.AreEqual (fileBefore, Frames (mp3.Id3v2Tag!)); + + // Mp3File.Tag builds a new view on every read. + var source = mp3.Tag!; + var target = mp3.Tag!; + Assert.AreNotSame (source, target); + source.CopyTo (target, TagCopyOptions.All); + CollectionAssert.AreEqual (fileBefore, Frames (mp3.Id3v2Tag!)); } [TestMethod] @@ -352,6 +364,54 @@ sealed class ForwardingTag (Id3v2Tag inner) : Tag public override void Clear () => inner.Clear (); } + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void CopyAll_ListTheTargetHolds_KeepsItsFrames (byte version) + { + // UTF-16 frames the setters would not write. With Extended, the names travel in the lists, + // so a target that already holds them keeps its frames, encoding and order included. + static byte[] Utf16List (string a, string b) => + [0x01, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (a), 0, 0, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (b)]; + byte[] body = [ + .. TestBuilders.Id3v2.CreateFrame ("TPE1", Utf16List ("P1", "P2"), version), + .. TestBuilders.Id3v2.CreateFrame ("TCON", Utf16List ("Rock", "Pop"), version), + .. TestBuilders.Id3v2.CreateFrame ("TALB", Utf16List ("A", "B"), version), + ]; + var target = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader (version, (uint)body.Length), .. body]).Tag!; + var before = target.Render ().ToArray (); + var source = new VorbisComment ("s"); + foreach (var (name, value) in new[] { ("ARTIST", "P1"), ("ARTIST", "P2"), ("GENRE", "Rock"), ("GENRE", "Pop") }) + source.AddField (name, value); + + source.CopyTo (target, TagCopyOptions.All); + + CollectionAssert.AreEqual (before, target.Render ().ToArray ()); + } + + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void Copy_BetweenViewsOverOneTag_IsByteIdentical (byte version) + { + // Numbers and dates in a layout their setters would rewrite ("05/12" becomes "5/12"); a view + // copy skips every value the target already shows, so none of them is rewritten. + static byte[] Utf16 (string text) => [0x01, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (text)]; + byte[] body = [ + .. TestBuilders.Id3v2.CreateFrame ("TRCK", Utf16 ("05/12"), version), + .. TestBuilders.Id3v2.CreateFrame ("TPOS", Utf16 ("1/2"), version), + .. TestBuilders.Id3v2.CreateFrame (version == 4 ? "TDRC" : "TYER", Utf16 (version == 4 ? "2001-05-03" : "2001"), version), + .. TestBuilders.Id3v2.CreateFrame ("TBPM", Utf16 ("0120"), version), + .. TestBuilders.Id3v2.CreateFrame ("TPUB", Utf16 ("Lab1\0Lab2"), version), + ]; + var tag = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader (version, (uint)body.Length), .. body]).Tag!; + var before = tag.Render ().ToArray (); + + new CombinedTag (tag, null).CopyTo (new CombinedTag (tag, null), TagCopyOptions.All); + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + } + [TestMethod] public void WriteBack_AfterACopy_IsANoOpAgain () { diff --git a/tests/TagLibSharp2.Tests/CrossTaggerCompatibilityTests.cs b/tests/TagLibSharp2.Tests/CrossTaggerCompatibilityTests.cs index e3960df8..72ca721c 100644 --- a/tests/TagLibSharp2.Tests/CrossTaggerCompatibilityTests.cs +++ b/tests/TagLibSharp2.Tests/CrossTaggerCompatibilityTests.cs @@ -173,8 +173,10 @@ public void VorbisComment_ClassicalMusic_UsesStandardNames () Assert.IsTrue (parsed.IsSuccess); Assert.AreEqual ("Symphony No. 9", parsed.Tag!.GetValue ("WORK")); - Assert.AreEqual ("Allegro", parsed.Tag.GetValue ("MOVEMENT")); - Assert.AreEqual ("1", parsed.Tag.GetValue ("MOVEMENTNUMBER")); + // MusicBrainz Picard's mapping: the name is MOVEMENTNAME, the number MOVEMENT. + Assert.AreEqual ("Allegro", parsed.Tag.GetValue ("MOVEMENTNAME")); + Assert.AreEqual ("1", parsed.Tag.GetValue ("MOVEMENT")); + Assert.IsNull (parsed.Tag.GetValue ("MOVEMENTNUMBER")); Assert.AreEqual ("4", parsed.Tag.GetValue ("MOVEMENTTOTAL")); } diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs index 98cc7d71..f060fd97 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs @@ -125,11 +125,15 @@ static Id3v2Tag BuildForeign (Id3v2Tag probe, byte version, string value) foreach (var f in probe.UserTextFrames) frames.Add (TestBuilders.Id3v2.CreateFrame ("TXXX", Join ([0x01], Utf16 (f.Description), Nul16, Utf16 (value), Nul16, Utf16 ("V2")), version)); if (probe.Comments.Count > 0) { + // An empty comment first: the getter shows the first non-empty one, as ffprobe and TagLib# do. + frames.Add (TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), [0x00]), version)); frames.Add (TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "deu"u8.ToArray (), [0x00], System.Text.Encoding.Latin1.GetBytes (value)), version)); frames.Add (TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), "note"u8.ToArray (), [0x00], "other"u8.ToArray ()), version)); } - foreach (var _ in probe.LyricsFrames) + foreach (var _ in probe.LyricsFrames) { + frames.Add (TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "eng"u8.ToArray (), [0x00]), version)); frames.Add (TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x01], "deu"u8.ToArray (), Utf16 (""), Nul16, Utf16 (value)), version)); + } foreach (var f in probe.UrlFrames) frames.Add (TestBuilders.Id3v2.CreateFrame (f.Id, System.Text.Encoding.Latin1.GetBytes (value), version)); foreach (var f in probe.UniqueFileIdFrames) @@ -178,6 +182,45 @@ public void EveryStringProperty_WriteBackOverForeignFrames_IsByteIdentical (byte Assert.IsEmpty (uncovered, string.Join (",", uncovered)); } + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void CommentAndLyrics_EmptyFirstFrame_ReadTheNextAndEmptyStringClears (byte version) + { + var body = Join ( + TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), [0x00]), version), + TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "deu"u8.ToArray (), [0x00], "Hallo"u8.ToArray ()), version), + TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "eng"u8.ToArray (), [0x00]), version), + TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "deu"u8.ToArray (), [0x00], "Lied"u8.ToArray ()), version)); + var tag = Id3v2Tag.Read (Join (TestBuilders.Id3v2.CreateHeader (version, (uint)body.Length), body)).Tag!; + Assert.AreEqual ("Hallo", tag.Comment); + Assert.AreEqual ("Lied", tag.Lyrics); + + var before = tag.Render ().ToArray (); + tag.Comment = tag.Comment; + tag.Lyrics = tag.Lyrics; + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + + tag.Comment = ""; + tag.Lyrics = ""; + Assert.IsEmpty (tag.Comments); + Assert.IsEmpty (tag.LyricsFrames); + Assert.IsNull (tag.Comment); + Assert.IsNull (tag.Lyrics); + } + + [TestMethod] + public void CommentAndLyrics_EveryFrameEmpty_ReadEmpty () + { + var body = Join ( + TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), [0x00]), 4), + TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "eng"u8.ToArray (), [0x00]), 4)); + var tag = Id3v2Tag.Read (Join (TestBuilders.Id3v2.CreateHeader (4, (uint)body.Length), body)).Tag!; + + Assert.AreEqual ("", tag.Comment); + Assert.AreEqual ("", tag.Lyrics); + } + [TestMethod] public void Year_V23WriteBack_KeepsTheOriginalEncoding () { diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs index 6c88fc99..d0c0c4d8 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -422,14 +422,14 @@ public void OriginalReleaseDate_SetEmpty_RemovesOriginalYear () } [TestMethod] - public void Movement_Set_RewritesMovementName_ClearRemovesBoth () + public void Movement_Set_WritesMovementName_ClearRemovesIt () { var comment = new VorbisComment ("test"); comment.AddField ("MOVEMENTNAME", "Adagio"); comment.Movement = "Allegro"; Assert.AreEqual ("Allegro", comment.Movement); - AssertSingle (comment, "MOVEMENT", "Allegro"); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); AssertSingle (comment, "MOVEMENTNAME", "Allegro"); comment.Movement = null; @@ -439,23 +439,50 @@ public void Movement_Set_RewritesMovementName_ClearRemovesBoth () } [TestMethod] - public void Movement_SetWithoutMovementName_DoesNotAddIt () + public void Movement_SetOnAnEmptyTag_WritesPicardsMovementName () { var comment = new VorbisComment ("test"); comment.Movement = "Allegro"; + AssertSingle (comment, "MOVEMENTNAME", "Allegro"); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + } + + [TestMethod] + public void Movement_LegacyNameInMovement_IsReadAndKeptInStep () + { + // Earlier versions wrote the name to MOVEMENT. A MOVEMENT that is not a number still reads + // as the name; a new name updates it, and a clear removes it. + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENT", "Allegro"); + Assert.AreEqual ("Allegro", comment.Movement); + Assert.IsNull (comment.MovementNumber); + + comment.Movement = "Adagio"; + AssertSingle (comment, "MOVEMENT", "Adagio"); + AssertSingle (comment, "MOVEMENTNAME", "Adagio"); + + comment.MovementNumber = 2; + AssertSingle (comment, "MOVEMENTNUMBER", "2"); + AssertSingle (comment, "MOVEMENT", "Adagio"); + + comment.Movement = null; + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + Assert.AreEqual (2u, comment.MovementNumber); } [TestMethod] - public void Movement_SetEmpty_RemovesMovementName () + public void Movement_SetEmpty_LeavesAnEmptyNameAndRemovesALegacyName () { var comment = new VorbisComment ("test"); comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.AddField ("MOVEMENT", "Adagio"); comment.Movement = ""; Assert.AreEqual ("", comment.Movement); - Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + AssertSingle (comment, "MOVEMENTNAME", ""); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); } [TestMethod] @@ -484,7 +511,6 @@ public void PicardTags_UnchangedWriteBack_KeepsEveryField () } [TestMethod] - [DataRow ("MOVEMENT", "MOVEMENTNAME", "Allegro")] [DataRow ("ORIGINALDATE", "ORIGINALYEAR", "1969")] public void EmptyPrimary_UnchangedWriteBack_KeepsBothFields (string primary, string fallback, string fallbackValue) { diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs index ecc8aa34..c84f657e 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs @@ -83,7 +83,7 @@ public void LeadingEmptyField_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClea comment.AddField ("MOVEMENT", "V2"); comment.AddField ("MOVEMENTNAME", "N"); Assert.AreEqual ("V2", comment.Artist); - Assert.AreEqual ("V2", comment.Movement); + Assert.AreEqual ("N", comment.Movement); var before = string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value)); comment.Artist = comment.Artist; comment.Movement = comment.Movement; @@ -93,8 +93,8 @@ public void LeadingEmptyField_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClea comment.Movement = ""; Assert.AreEqual ("", string.Join ("|", comment.GetValues ("ARTIST"))); - Assert.AreEqual ("", string.Join ("|", comment.GetValues ("MOVEMENT"))); - Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + Assert.AreEqual ("", string.Join ("|", comment.GetValues ("MOVEMENTNAME"))); } [TestMethod] From b568ed31638e2fd07473e97f596a441060125039 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 15:21:26 -0700 Subject: [PATCH 21/29] docs: State the view, comment, and movement rules and the reader difference --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a927649..cc8af4ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,10 +39,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- A single-value ID3v2, APE, or Vorbis Comment getter returns the first non-empty value, and an empty string only when every value is empty. 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`. This replaces the earlier reading of a leading NUL as an empty first value. Writing back the value read changes nothing, so a multi-value frame, item, or repeated field keeps every value, and `= ""` clears it. The comparison is ordinal, so a case-only edit still writes, and `null` always clears. 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. A copy (`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, and it skips a list the target already holds. Two exceptions keep what the target holds. A source that is the target, or reads from it (a file's combined `Tag` copied into one of its own tags), only adds values the target does not show. A fallback field of its own beside a value equal to the copied one stays: Vorbis `MOVEMENTNAME` or `ORIGINALYEAR`, APE `Date`, and the ID3v2.3 `TDOR` beside `TORY`. -- A Vorbis or APE tag laid out as MusicBrainz Picard writes it, with the movement number in `MOVEMENT` beside `MOVEMENTNAME`, reads and writes the movement name in `MOVEMENTNAME` and the number in `MOVEMENT`. Such a movement is no longer read as the name "2", so a copy from a Picard FLAC no longer writes "2" over an ID3v2 `MVNM`. +- A single-value ID3v2, APE, or Vorbis Comment property returns the first non-empty value, and an empty string only when every value is empty. 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`. 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` always clears. 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. 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. +- Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. -- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Clearing a movement also removes `MOVEMENTNAME`, and setting a new movement also writes it to an existing `MOVEMENTNAME`. Writing back the APE year, Vorbis original release date, or Vorbis movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year`, `ORIGINALDATE`, or `MOVEMENT` no longer hides a filled `Date`, `ORIGINALYEAR`, or `MOVEMENTNAME`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. +- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Writing back the APE year, Vorbis original release date, or movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year` or `ORIGINALDATE` no longer hides a filled `Date` or `ORIGINALYEAR`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. - An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. - Setting a new ID3v2 original release date, or clearing it, removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. Writing back the date already read changes nothing. From cb72268ddc58d99ec332c7eca2a5239b2dfc276d Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 18:55:02 -0700 Subject: [PATCH 22/29] fix: Store the first non-empty name when a list meets one name A tag that holds one name took the first entry of a copied list even when it was empty, so a default copy of ARTIST= plus ARTIST=V2 into MP4, ASF, RIFF INFO, or ID3v1 cleared the artist and genre and dropped the target's old ones. The base list setters and RIFF INFO's now keep the first non-empty entry, the one the source shows. Also pin the lyrics fallback to a described frame. --- src/TagLibSharp2/Core/Tag.cs | 26 +++++- src/TagLibSharp2/Riff/RiffInfoTag.cs | 4 +- .../Core/TagCopyListToSingleTests.cs | 93 +++++++++++++++++++ .../Id3/Id3v2/Id3v2WriteBackTests.cs | 21 +++++ 4 files changed, 137 insertions(+), 7 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 3d067ef9..584288d1 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -83,6 +83,22 @@ public abstract class Tag [ThreadStatic] static int t_copyDepth; + /// + /// The first non-empty entry of a list, or null when there is none. A tag that stores one name + /// keeps the name a reader shows: an empty first entry (a leading NUL in ID3v2.4, a repeated empty + /// Vorbis field) is not that name. + /// + internal static string? FirstNonEmpty (string[]? values) + { + if (values is null) + return null; + foreach (var value in values) { + if (!string.IsNullOrEmpty (value)) + return value; + } + return null; + } + /// /// True when a setter is handed exactly the value its getter returned, compared ordinally, as when an /// editor writes back what it read. The setter then leaves the tag alone, so the other values of a @@ -145,7 +161,7 @@ internal static bool IsWriteBack (uint? value, uint? current) => /// /// /// This is the primary array of artists. The property returns - /// the first value from this array. + /// the first value from this array. A tag that stores one name keeps the first non-empty entry. /// /// /// Design Note: This property uses an array type for compatibility with @@ -158,7 +174,7 @@ internal static bool IsWriteBack (uint? value, uint? current) => #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public virtual string[] Performers { get => string.IsNullOrEmpty (Artist) ? [] : [Artist!]; - set => Artist = value is { Length: > 0 } ? value[0] : null; + set => Artist = FirstNonEmpty (value); } #pragma warning restore CA1819 @@ -245,7 +261,7 @@ public virtual string[] Performers { #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public virtual string[] Genres { get => string.IsNullOrEmpty (Genre) ? [] : [Genre!]; - set => Genre = value is { Length: > 0 } ? value[0] : null; + set => Genre = FirstNonEmpty (value); } #pragma warning restore CA1819 @@ -290,7 +306,7 @@ public virtual string[] Genres { #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public virtual string[] AlbumArtists { get => string.IsNullOrEmpty (AlbumArtist) ? [] : [AlbumArtist!]; - set => AlbumArtist = value is { Length: > 0 } ? value[0] : null; + set => AlbumArtist = FirstNonEmpty (value); } #pragma warning restore CA1819 @@ -328,7 +344,7 @@ public virtual string[] AlbumArtists { #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public virtual string[] Composers { get => string.IsNullOrEmpty (Composer) ? [] : [Composer!]; - set => Composer = value is { Length: > 0 } ? value[0] : null; + set => Composer = FirstNonEmpty (value); } #pragma warning restore CA1819 diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs index ba6a2a05..fe1826f0 100644 --- a/src/TagLibSharp2/Riff/RiffInfoTag.cs +++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs @@ -125,7 +125,7 @@ public override string[] Performers { ? [] : [artist!]; } - set => SetField (IART, value?.Length > 0 ? value[0] : null); + set => SetField (IART, FirstNonEmpty (value)); } #pragma warning restore CA1819 @@ -156,7 +156,7 @@ public override string[] Genres { ? [] : [genre!]; } - set => SetField (IGNR, value?.Length > 0 ? value[0] : null); + set => SetField (IGNR, FirstNonEmpty (value)); } #pragma warning restore CA1819 diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs new file mode 100644 index 00000000..d6ea3dcb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.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 System.Reflection; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mp4; +using TagLibSharp2.Riff; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A tag that stores one name gets the name the source shows. An empty first entry (repeated Vorbis +/// fields, https://xiph.org/vorbis/doc/v-comment.html) is not that name, so a list copied into a +/// single-value tag stores its first non-empty entry. +/// +[TestClass] +[TestCategory ("Unit")] +public class TagCopyListToSingleTests +{ + static readonly (string Property, string Field)[] Fields = [ + ("Artist", "ARTIST"), ("Genre", "GENRE"), ("AlbumArtist", "ALBUMARTIST"), ("Composer", "COMPOSER"), + ]; + + static readonly TagCopyOptions[] Options = [ + TagCopyOptions.All, TagCopyOptions.Basic | TagCopyOptions.Extended, TagCopyOptions.Extended, TagCopyOptions.Basic, + ]; + + static Tag NewTarget (string name) => name switch { + "mp4" => new Mp4Tag (), + "asf" => new AsfTag (), + "riff" => new RiffInfoTag (), + "id3v1" => new Id3v1Tag (), + _ => new CombinedTag (new Id3v2Tag (Id3v2Version.V24), new Id3v1Tag ()), + }; + + [TestMethod] + [DataRow ("mp4")] + [DataRow ("asf")] + [DataRow ("riff")] + [DataRow ("id3v1")] + [DataRow ("id3v2+id3v1")] + public void CopyFromALeadingEmptyList_StoresTheNameTheSourceShows (string targetName) + { + var failures = new List (); + var covered = 0; + foreach (var (propertyName, field) in Fields) { + var property = typeof (Tag).GetProperty (propertyName)!; + var probe = NewTarget (targetName); + property.SetValue (probe, "Probe"); + if (!Equals (property.GetValue (probe), "Probe")) + continue; + + foreach (var options in Options) { + if (propertyName is "AlbumArtist" or "Composer" && (options & TagCopyOptions.Extended) == 0) + continue; + var source = new VorbisComment ("source"); + source.AddField (field, ""); + source.AddField (field, "Rock"); + var target = NewTarget (targetName); + property.SetValue (target, "Old"); + + source.CopyTo (target, options); + covered++; + + if (!Equals (property.GetValue (target), "Rock")) + failures.Add ($"{propertyName} {options}: {property.GetValue (target) ?? ""}"); + if (target is CombinedTag combined && !Equals (property.GetValue (((IReadOnlyList)typeof (CombinedTag).GetProperty ("Tags", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue (combined)!)[1]), property.Name is "Artist" or "Genre" ? "Rock" : null)) + failures.Add ($"{propertyName} {options}: ID3v1 half"); + } + } + + Assert.IsEmpty (failures, string.Join ("\n", failures)); + Assert.IsGreaterThanOrEqualTo (4, covered); + } + + [TestMethod] + public void ListSetter_OnASingleValueTag_StoresTheFirstNonEmptyEntry () + { + foreach (var tag in new Tag[] { new Mp4Tag (), new AsfTag (), new RiffInfoTag (), new Id3v1Tag () }) { + tag.Performers = ["", "P2", "P3"]; + tag.Genres = ["", "Pop"]; + Assert.AreEqual ("P2", tag.Artist, tag.GetType ().Name); + Assert.AreEqual ("Pop", tag.Genre, tag.GetType ().Name); + + tag.Performers = ["", ""]; + Assert.IsTrue (string.IsNullOrEmpty (tag.Artist), tag.GetType ().Name); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs index f060fd97..c7dd1cc2 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs @@ -209,6 +209,27 @@ public void CommentAndLyrics_EmptyFirstFrame_ReadTheNextAndEmptyStringClears (by Assert.IsNull (tag.Lyrics); } + [TestMethod] + [DataRow (TestConstants.Id3v2.Version3)] + [DataRow (TestConstants.Id3v2.Version4)] + public void CommentAndLyrics_DescribedOnly_ReadTheDescribedFrame (byte version) + { + // With no frame lacking a description, the getter shows the first non-empty described one, + // and writing it back changes nothing. + var body = Join ( + TestBuilders.Id3v2.CreateFrame ("COMM", Join ([0x00], "eng"u8.ToArray (), "notes"u8.ToArray (), [0x00], "Liner"u8.ToArray ()), version), + TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "eng"u8.ToArray (), "verse"u8.ToArray (), [0x00]), version), + TestBuilders.Id3v2.CreateFrame ("USLT", Join ([0x00], "eng"u8.ToArray (), "notes"u8.ToArray (), [0x00], "Liner"u8.ToArray ()), version)); + var tag = Id3v2Tag.Read (Join (TestBuilders.Id3v2.CreateHeader (version, (uint)body.Length), body)).Tag!; + Assert.AreEqual ("Liner", tag.Comment); + Assert.AreEqual ("Liner", tag.Lyrics); + + var before = tag.Render ().ToArray (); + tag.Comment = tag.Comment; + tag.Lyrics = tag.Lyrics; + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + } + [TestMethod] public void CommentAndLyrics_EveryFrameEmpty_ReadEmpty () { From 36f50752177dbece19d16ec0f0aefa25324fdcc7 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 18:55:02 -0700 Subject: [PATCH 23/29] docs: Correct the clear, APE text, and view-copy statements --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc8af4ff..64b1c1bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- A single-value ID3v2, APE, or Vorbis Comment property returns the first non-empty value, and an empty string only when every value is empty. 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`. 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` always clears. 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. 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 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`. 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. 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. - Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. - Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Writing back the APE year, Vorbis original release date, or movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year` or `ORIGINALDATE` no longer hides a filled `Date` or `ORIGINALYEAR`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. From 8db19bc4b976bffdd0ca44cbdc6d1bd494fab525 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 19:17:47 -0700 Subject: [PATCH 24/29] fix: Name the AIFF view's tag and keep ID3v2 values as written AiffTag reads the file's ID3 tag, but it did not name it, so a copy between aiff.Tag and aiff.Id3v2Tag ran as a copy between unrelated tags and cut TPUB and the other single-value lists. It now lists that tag in Leaves, and a test checks every Tag type that holds another tag or a file of tags. The ID3v2.4 list reading trimmed every value and dropped blank ones, while the single value kept them, so a Basic copy and the default copy stored different names for " \0B". A NUL-separated value is now kept as written and only an empty one is skipped, as other readers show it. --- src/TagLibSharp2/Aiff/AiffTag.cs | 14 ++++++ src/TagLibSharp2/Core/Tag.cs | 11 +++-- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 12 +++-- .../Core/TagCopyListToSingleTests.cs | 25 ++++++++++ .../Core/TagCopyReplacesListTests.cs | 48 +++++++++++++++++++ 5 files changed, 102 insertions(+), 8 deletions(-) diff --git a/src/TagLibSharp2/Aiff/AiffTag.cs b/src/TagLibSharp2/Aiff/AiffTag.cs index f2e5335f..8ebd017d 100644 --- a/src/TagLibSharp2/Aiff/AiffTag.cs +++ b/src/TagLibSharp2/Aiff/AiffTag.cs @@ -501,5 +501,19 @@ public override BinaryData Render () => Id3v2Tag? Id3 => _file.Id3v2Tag; + /// + /// + /// This view reads the file's ID3 tag, so a copy between it and that tag (or another view over the + /// same file) only adds values the target does not show. + /// + internal override IEnumerable Leaves () + { + yield return this; + if (Id3 is { } id3) { + foreach (var leaf in id3.Leaves ()) + yield return leaf; + } + } + Id3v2Tag Ensure () => _file.EnsureId3 (); } diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 584288d1..65ec5bc7 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -161,7 +161,7 @@ internal static bool IsWriteBack (uint? value, uint? current) => /// /// /// This is the primary array of artists. The property returns - /// the first value from this array. A tag that stores one name keeps the first non-empty entry. + /// the first non-empty value of this array. A tag that stores one name keeps the first non-empty entry. /// /// /// Design Note: This property uses an array type for compatibility with @@ -256,7 +256,8 @@ public virtual string[] Performers { /// Gets or sets the genres for this track. /// /// - /// The property returns the first value from this array. + /// The property returns the first non-empty value of this array. + /// A tag that stores one name keeps the first non-empty entry. /// #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public virtual string[] Genres { @@ -300,7 +301,8 @@ public virtual string[] Genres { /// /// /// Used for compilations and various artists albums. The - /// property returns the first value from this array. + /// property returns the first non-empty value of this array. A tag that stores one name keeps + /// the first non-empty entry. /// Not all tag formats support this field. /// #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility @@ -338,7 +340,8 @@ public virtual string[] AlbumArtists { /// Gets or sets the composers for this track. /// /// - /// The property returns the first value from this array. + /// The property returns the first non-empty value of this array. + /// A tag that stores one name keeps the first non-empty entry. /// Not all tag formats support this field. /// #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index dbc2c451..1e93e7d3 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1574,7 +1574,10 @@ static string FirstTextValue (string text) /// Gets all values from a text frame (multi-value support). /// /// The frame ID (e.g., TPE1 for artists). - /// A list of values, split by null characters (v2.4) or "/" (v2.3). + /// + /// A list of values, split by null characters (v2.4; each value as written, empty values skipped) + /// or "/" (v2.3; each value trimmed, blank values skipped). + /// /// /// ID3v2.4 uses null characters as value separators. ID3v2.3 has no official /// separator, but "/" is commonly used. This method handles both. @@ -1592,12 +1595,13 @@ public IReadOnlyList GetTextFrameValues (string frameId) #else if (text!.Contains ('\0', StringComparison.Ordinal)) { #endif + // ID3v2.4 §4.2: each NUL-separated string is a value as written. An empty one is skipped, + // as the single-value getter skips it; spaces are kept, as every other reader keeps them. var parts = text.Split ('\0'); var result = new List (parts.Length); for (var i = 0; i < parts.Length; i++) { - var trimmed = parts[i].Trim (); - if (!string.IsNullOrEmpty (trimmed)) - result.Add (trimmed); + if (parts[i].Length != 0) + result.Add (parts[i]); } return result; } diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs index d6ea3dcb..a0c9e85f 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs @@ -77,6 +77,31 @@ public void CopyFromALeadingEmptyList_StoresTheNameTheSourceShows (string target Assert.IsGreaterThanOrEqualTo (4, covered); } + [TestMethod] + [DataRow ("", "Rock", "Rock")] + [DataRow (" ", "Rock", " ")] + [DataRow ("\t", "Rock", "\t")] + [DataRow (" X ", "Rock", " X ")] + public void BasicAndAll_FromAnId3v24List_StoreTheSameName (string first, string second, string expected) + { + // ID3v2.4 §4.2 values are kept as written; only an empty one is skipped. The single getter and + // the list agree, so a Basic copy (the single name) and the default copy (the list) store the same. + var source = new Id3v2Tag (Id3v2Version.V24); + source.SetTextFrameValues ("TPE1", ["placeholder"]); + source.Frames.First (f => f.Id == "TPE1").Text = first + "\0" + second; + source = Id3v2Tag.Read (source.Render ().Span).Tag!; + Assert.AreEqual (expected, source.Artist); + Assert.AreEqual (expected, Tag.FirstNonEmpty (source.Performers)); + + foreach (var name in new[] { "mp4", "asf", "riff", "id3v2+id3v1" }) { + var basic = NewTarget (name); + var all = NewTarget (name); + source.CopyTo (basic, TagCopyOptions.Basic); + source.CopyTo (all, TagCopyOptions.All); + Assert.AreEqual (basic.Artist, all.Artist, name); + } + } + [TestMethod] public void ListSetter_OnASingleValueTag_StoresTheFirstNonEmptyEntry () { diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index e1e09cd3..9fb42ce4 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -412,6 +412,54 @@ .. TestBuilders.Id3v2.CreateFrame ("TPUB", Utf16 ("Lab1\0Lab2"), version), CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); } + [TestMethod] + public void Copy_BetweenAnAiffViewAndItsId3Tag_KeepsEveryList () + { + var aiff = TagLibSharp2.Aiff.AiffFile.Read (TestBuilders.Aiff.CreateMinimal ()).File!; + aiff.Id3v2Tag = PicardId3 (Id3v2Version.V24); + var before = Frames (aiff.Id3v2Tag!); + + aiff.Tag!.CopyTo (aiff.Id3v2Tag!, TagCopyOptions.All); + CollectionAssert.AreEqual (before, Frames (aiff.Id3v2Tag!)); + + aiff.Id3v2Tag!.CopyTo (aiff.Tag!, TagCopyOptions.All); + CollectionAssert.AreEqual (before, Frames (aiff.Id3v2Tag!)); + + var reread = TagLibSharp2.Aiff.AiffFile.Read (aiff.Render ().Span).File!; + Assert.AreEqual ("Lab1|Lab2", string.Join ("|", reread.Id3v2Tag!.GetTextFrameValues ("TPUB"))); + } + + /// + /// Every Tag type in the library that keeps another tag, or a file that holds tags, is a view. + /// A view must name the tags it reads (Leaves), or a copy between it and one of them cuts lists. + /// This catches the next view added without that override. + /// + [TestMethod] + public void EveryViewType_NamesTheTagsItReads () + { + static bool HoldsTags (Type type) => + typeof (Tag).IsAssignableFrom (type) + || (type.IsArray && typeof (Tag).IsAssignableFrom (type.GetElementType ()!)) + || type.GetProperties (BindingFlags.Public | BindingFlags.Instance).Any (p => typeof (Tag).IsAssignableFrom (p.PropertyType)); + + var views = new List (); + var missing = new List (); + foreach (var type in typeof (Tag).Assembly.GetTypes ().Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t))) { + var wraps = type.GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .Any (f => HoldsTags (f.FieldType)); + if (!wraps) + continue; + views.Add (type.Name); + var leaves = type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!; + if (leaves.DeclaringType != type) + missing.Add (type.Name); + } + + Assert.IsEmpty (missing, string.Join (",", missing)); + foreach (var name in new[] { "CombinedTag", "FlacTag", "AiffTag" }) + Assert.Contains (name, views); + } + [TestMethod] public void WriteBack_AfterACopy_IsANoOpAgain () { From 0477a14e7ed68bbaefe01bbbffb1e25d48105336 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 19:17:47 -0700 Subject: [PATCH 25/29] docs: Say that ID3v2 list values are kept as written --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64b1c1bf..493d5186 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,7 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- 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`. 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. +- 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 the single value and the first list entry agree (an ID3v2.3 `/`-separated list is still trimmed). 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. 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. - Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. From 55481a0a1558287c91dd06c84690399025ab69d5 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 19:34:54 -0700 Subject: [PATCH 26/29] test: Classify every Tag type as a leaf or a view that names its tags The view guard looked for fields of a few shapes, so a view holding its tags in an IEnumerable, a delegate, a base class's private field, or a non-public holder member passed. Every concrete Tag type must now be a listed leaf format tag or override Leaves, so a new type fails until someone decides which it is. --- .../Core/TagCopyReplacesListTests.cs | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index 9fb42ce4..6d4d2600 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -430,32 +430,32 @@ public void Copy_BetweenAnAiffViewAndItsId3Tag_KeepsEveryList () } /// - /// Every Tag type in the library that keeps another tag, or a file that holds tags, is a view. - /// A view must name the tags it reads (Leaves), or a copy between it and one of them cuts lists. - /// This catches the next view added without that override. + /// Format tags that store their own fields and read no other tag. Every other Tag type is a view. + /// + static readonly string[] LeafTagTypes = [ + "ApeTag", "AsfTag", "Id3v1Tag", "Id3v2Tag", "MatroskaTag", "Mp4Tag", "RiffInfoTag", "VorbisComment", + ]; + + /// + /// Every concrete Tag type in the library is either a leaf format tag on the list above, or a view + /// that names the tags it reads (Leaves). A new type fails here until someone decides which it is, + /// whatever shape it uses to hold its tags; a view that does not name them would cut lists on a copy + /// between it and one of its own tags. /// [TestMethod] - public void EveryViewType_NamesTheTagsItReads () + public void EveryTagType_IsALeafOrAViewThatNamesItsTags () { - static bool HoldsTags (Type type) => - typeof (Tag).IsAssignableFrom (type) - || (type.IsArray && typeof (Tag).IsAssignableFrom (type.GetElementType ()!)) - || type.GetProperties (BindingFlags.Public | BindingFlags.Instance).Any (p => typeof (Tag).IsAssignableFrom (p.PropertyType)); - + var unclassified = new List (); var views = new List (); - var missing = new List (); foreach (var type in typeof (Tag).Assembly.GetTypes ().Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t))) { - var wraps = type.GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) - .Any (f => HoldsTags (f.FieldType)); - if (!wraps) - continue; - views.Add (type.Name); var leaves = type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!; - if (leaves.DeclaringType != type) - missing.Add (type.Name); + if (leaves.DeclaringType != typeof (Tag)) + views.Add (type.Name); + else if (!LeafTagTypes.Contains (type.Name) || type.BaseType != typeof (Tag)) + unclassified.Add (type.FullName!); } - Assert.IsEmpty (missing, string.Join (",", missing)); + Assert.IsEmpty (unclassified, string.Join (",", unclassified)); foreach (var name in new[] { "CombinedTag", "FlacTag", "AiffTag" }) Assert.Contains (name, views); } From 58cc3d5af7029342b1d5913fb229eb93bd704f74 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 19:34:54 -0700 Subject: [PATCH 27/29] docs: State the slash split and that an empty copied value clears --- CHANGELOG.md | 4 ++-- src/TagLibSharp2/Core/Tag.cs | 3 ++- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 5 +++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 493d5186..ddbe5c50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### 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. -- 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 the single value and the first list entry agree (an ID3v2.3 `/`-separated list is still trimmed). 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. 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 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. - Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. - Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 65ec5bc7..5d51a6f0 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -1218,7 +1218,8 @@ public virtual ValidationResult Validate () /// /// 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), the copy only adds - /// values the target does not show. A fallback field of its own beside a value equal to the copied one + /// 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. A fallback field of its own beside a value equal to the copied one /// stays: Vorbis ORIGINALYEAR, APE Date, and an ID3v2.3 TDOR beside TORY. Pictures are outside both /// rules: a non-empty source picture list always replaces the target's. /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 1e93e7d3..0446f475 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1575,8 +1575,9 @@ static string FirstTextValue (string text) /// /// The frame ID (e.g., TPE1 for artists). /// - /// A list of values, split by null characters (v2.4; each value as written, empty values skipped) - /// or "/" (v2.3; each value trimmed, blank values skipped). + /// A list of values, split by null characters (each value as written, empty values skipped), or by + /// "/" when the text has no null character, in any version (each value trimmed, blank values skipped). + /// Only for NUL-separated text is the first entry the same as . /// /// /// ID3v2.4 uses null characters as value separators. ID3v2.3 has no official From 4fe872400fd92fd61db8f81ea43580979423c0ab Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 21:19:50 -0700 Subject: [PATCH 28/29] test: Require each view to declare Leaves and list leaf tags by full name A subclass of a view, or a type that inherits a Leaves written for its base, could add a tag of its own and still pass, and so could a type reusing a leaf's simple name. Each view must now declare Leaves itself, leaf tags are listed by full name, and eleven dummy views, one per shape, pin the guard. The GetTextFrameValues remark no longer says the first entry differs for a plain value. --- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 3 +- .../Core/TagCopyReplacesListTests.cs | 133 +++++++++++++++--- 2 files changed, 119 insertions(+), 17 deletions(-) diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 0446f475..57e2b6d4 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -1577,7 +1577,8 @@ static string FirstTextValue (string text) /// /// A list of values, split by null characters (each value as written, empty values skipped), or by /// "/" when the text has no null character, in any version (each value trimmed, blank values skipped). - /// Only for NUL-separated text is the first entry the same as . + /// The first entry is the same as unless the text was split on "/"; when every + /// value is empty there is no entry and returns "". /// /// /// ID3v2.4 uses null characters as value separators. ID3v2.3 has no official diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index 6d4d2600..f5b6526a 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -430,34 +430,61 @@ public void Copy_BetweenAnAiffViewAndItsId3Tag_KeepsEveryList () } /// - /// Format tags that store their own fields and read no other tag. Every other Tag type is a view. + /// Format tags that store their own fields and read no other tag, by full name. Every other Tag type + /// is a view. /// static readonly string[] LeafTagTypes = [ - "ApeTag", "AsfTag", "Id3v1Tag", "Id3v2Tag", "MatroskaTag", "Mp4Tag", "RiffInfoTag", "VorbisComment", + "TagLibSharp2.Ape.ApeTag", "TagLibSharp2.Asf.AsfTag", "TagLibSharp2.Id3.Id3v1Tag", "TagLibSharp2.Id3.Id3v2.Id3v2Tag", + "TagLibSharp2.Matroska.MatroskaTag", "TagLibSharp2.Mp4.Mp4Tag", "TagLibSharp2.Riff.RiffInfoTag", "TagLibSharp2.Xiph.VorbisComment", ]; /// - /// Every concrete Tag type in the library is either a leaf format tag on the list above, or a view - /// that names the tags it reads (Leaves). A new type fails here until someone decides which it is, - /// whatever shape it uses to hold its tags; a view that does not name them would cut lists on a copy - /// between it and one of its own tags. + /// Null when is a listed leaf that derives directly from Tag and keeps the base + /// Leaves, or a view that declares its own Leaves. Otherwise why it is unclassified. A view must name + /// its tags itself: an inherited Leaves was written for the base's tags, not the ones this type adds. + /// + static string? Unclassified (Type type) + { + var declaring = type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!.DeclaringType; + if (declaring == type) + return null; + if (declaring == typeof (Tag) && type.BaseType == typeof (Tag) && LeafTagTypes.Contains (type.FullName)) + return null; + return $"{type.FullName} (Leaves from {declaring!.Name})"; + } + + static IEnumerable ConcreteTagTypes (Assembly assembly) => + assembly.GetTypes ().Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)); + + /// + /// Every concrete Tag type in the library is either a listed leaf format tag, or a view that declares + /// the tags it reads (Leaves). A new type fails here until someone decides which it is, whatever + /// shape it uses to hold its tags; a view that does not name them would cut lists on a copy between it + /// and one of its own tags. /// [TestMethod] public void EveryTagType_IsALeafOrAViewThatNamesItsTags () { - var unclassified = new List (); - var views = new List (); - foreach (var type in typeof (Tag).Assembly.GetTypes ().Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t))) { - var leaves = type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!; - if (leaves.DeclaringType != typeof (Tag)) - views.Add (type.Name); - else if (!LeafTagTypes.Contains (type.Name) || type.BaseType != typeof (Tag)) - unclassified.Add (type.FullName!); - } + var types = ConcreteTagTypes (typeof (Tag).Assembly).ToList (); + var unclassified = types.Select (Unclassified).OfType ().ToList (); Assert.IsEmpty (unclassified, string.Join (",", unclassified)); + foreach (var name in LeafTagTypes) + Assert.IsTrue (types.Any (t => t.FullName == name), name); foreach (var name in new[] { "CombinedTag", "FlacTag", "AiffTag" }) - Assert.Contains (name, views); + Assert.IsTrue (types.Any (t => t.Name == name && t.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!.DeclaringType == t), name); + } + + [TestMethod] + public void TagTypeGuard_FlagsEveryShapeOfAnUnnamedView () + { + var dummies = typeof (GuardDummies).GetNestedTypes (BindingFlags.NonPublic) + .Where (t => !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)).ToList (); + + var missed = dummies.Where (t => Unclassified (t) is null).Select (t => t.Name).ToList (); + + Assert.HasCount (11, dummies); + Assert.IsEmpty (missed, string.Join (",", missed)); } [TestMethod] @@ -501,3 +528,77 @@ sealed class ThrowingTag : Tag public override void Clear () { } } } + +/// +/// Views that do not name their tags, one per shape a view can use to hold them. The guard in +/// must flag every one. +/// +#pragma warning disable CA1812, IDE0052, CS0169, CS0649, CA1823, IDE0051 +static class GuardDummies +{ + abstract class DummyBase : Tag + { + 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 () { } + } + + sealed class PlainField : DummyBase { readonly Id3v2Tag _inner = new (Id3v2Version.V24); } + + sealed class Enumerable : DummyBase { readonly IEnumerable _inner = []; } + + abstract class PrivateFieldInBase : DummyBase { readonly Id3v2Tag _inner = new (Id3v2Version.V24); } + + sealed class FieldInBase : PrivateFieldInBase { } + + sealed class Delegate : DummyBase { readonly Func _inner = () => null; } + + sealed class Holder { internal Id3v2Tag? Id3; } + + sealed class InternalHolder : DummyBase { readonly Holder _file = new (); } + + sealed class PrimaryConstructor (Id3v2Tag inner) : DummyBase + { + public override string? Album { get => inner.Album; set => inner.Album = value; } + } + + sealed class MediaFile : DummyBase { readonly IMediaFile? _file; } + + sealed class Dictionary : DummyBase { readonly Dictionary _inner = []; } + + sealed class CombinedSubclass (params Tag?[] tags) : CombinedTag (tags) + { + readonly Id3v2Tag _extra = new (Id3v2Version.V24); + } + + abstract class SelfOnlyLeaves : DummyBase + { + internal override IEnumerable Leaves () { yield return this; } + } + + sealed class InheritedLeaves : SelfOnlyLeaves { readonly Id3v2Tag _inner = new (Id3v2Version.V24); } + + /// A leaf's simple name in another namespace, deriving directly from Tag. + sealed class Mp4Tag : Tag + { + readonly Id3v2Tag _inner = new (Id3v2Version.V24); + public override TagTypes TagType => TagTypes.None; + public override string? Title { get => _inner.Title; set => _inner.Title = value; } + 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 () { } + } +} +#pragma warning restore CA1812, IDE0052, CS0169, CS0649, CA1823, IDE0051 From 2c5b4590d16472473934f30eed1d29046856412a Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Sat, 21 Nov 2026 21:24:26 -0700 Subject: [PATCH 29/29] test: Move the Tag type classification into a shared test helper TagTypeClassification holds the leaf list, the view and leaf rules, and the library's view and unclassified lists, so other checks can use the same rule as the guard. --- .../Core/TagCopyReplacesListTests.cs | 38 ++--------- .../Core/TagTypeClassification.cs | 64 +++++++++++++++++++ 2 files changed, 70 insertions(+), 32 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index f5b6526a..5437f947 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -429,33 +429,6 @@ public void Copy_BetweenAnAiffViewAndItsId3Tag_KeepsEveryList () Assert.AreEqual ("Lab1|Lab2", string.Join ("|", reread.Id3v2Tag!.GetTextFrameValues ("TPUB"))); } - /// - /// Format tags that store their own fields and read no other tag, by full name. Every other Tag type - /// is a view. - /// - static readonly string[] LeafTagTypes = [ - "TagLibSharp2.Ape.ApeTag", "TagLibSharp2.Asf.AsfTag", "TagLibSharp2.Id3.Id3v1Tag", "TagLibSharp2.Id3.Id3v2.Id3v2Tag", - "TagLibSharp2.Matroska.MatroskaTag", "TagLibSharp2.Mp4.Mp4Tag", "TagLibSharp2.Riff.RiffInfoTag", "TagLibSharp2.Xiph.VorbisComment", - ]; - - /// - /// Null when is a listed leaf that derives directly from Tag and keeps the base - /// Leaves, or a view that declares its own Leaves. Otherwise why it is unclassified. A view must name - /// its tags itself: an inherited Leaves was written for the base's tags, not the ones this type adds. - /// - static string? Unclassified (Type type) - { - var declaring = type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!.DeclaringType; - if (declaring == type) - return null; - if (declaring == typeof (Tag) && type.BaseType == typeof (Tag) && LeafTagTypes.Contains (type.FullName)) - return null; - return $"{type.FullName} (Leaves from {declaring!.Name})"; - } - - static IEnumerable ConcreteTagTypes (Assembly assembly) => - assembly.GetTypes ().Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)); - /// /// Every concrete Tag type in the library is either a listed leaf format tag, or a view that declares /// the tags it reads (Leaves). A new type fails here until someone decides which it is, whatever @@ -465,14 +438,15 @@ static IEnumerable ConcreteTagTypes (Assembly assembly) => [TestMethod] public void EveryTagType_IsALeafOrAViewThatNamesItsTags () { - var types = ConcreteTagTypes (typeof (Tag).Assembly).ToList (); - var unclassified = types.Select (Unclassified).OfType ().ToList (); + var types = TagTypeClassification.ConcreteTagTypes (); + var unclassified = TagTypeClassification.Unclassified (); Assert.IsEmpty (unclassified, string.Join (",", unclassified)); - foreach (var name in LeafTagTypes) + foreach (var name in TagTypeClassification.LeafTagTypeNames) Assert.IsTrue (types.Any (t => t.FullName == name), name); + var views = TagTypeClassification.ViewTypes ().Select (t => t.Name).ToList (); foreach (var name in new[] { "CombinedTag", "FlacTag", "AiffTag" }) - Assert.IsTrue (types.Any (t => t.Name == name && t.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!.DeclaringType == t), name); + Assert.Contains (name, views); } [TestMethod] @@ -481,7 +455,7 @@ public void TagTypeGuard_FlagsEveryShapeOfAnUnnamedView () var dummies = typeof (GuardDummies).GetNestedTypes (BindingFlags.NonPublic) .Where (t => !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)).ToList (); - var missed = dummies.Where (t => Unclassified (t) is null).Select (t => t.Name).ToList (); + var missed = dummies.Where (t => TagTypeClassification.Unclassified (t) is null).Select (t => t.Name).ToList (); Assert.HasCount (11, dummies); Assert.IsEmpty (missed, string.Join (",", missed)); diff --git a/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs b/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs new file mode 100644 index 00000000..eb248d77 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagTypeClassification.cs @@ -0,0 +1,64 @@ +// 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.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// Sorts every concrete Tag type into leaf format tags, which store their own fields and read no other +/// tag, and views, which read other tags and must say which (Leaves). A type that is neither is +/// unclassified: a new view that does not name its tags would cut lists on a copy between it and one of +/// its own tags. +/// +static class TagTypeClassification +{ + /// + /// Leaf format tags, by full name. A leaf derives directly from Tag and keeps the base Leaves. + /// + internal static readonly string[] LeafTagTypeNames = [ + "TagLibSharp2.Ape.ApeTag", "TagLibSharp2.Asf.AsfTag", "TagLibSharp2.Id3.Id3v1Tag", "TagLibSharp2.Id3.Id3v2.Id3v2Tag", + "TagLibSharp2.Matroska.MatroskaTag", "TagLibSharp2.Mp4.Mp4Tag", "TagLibSharp2.Riff.RiffInfoTag", "TagLibSharp2.Xiph.VorbisComment", + ]; + + /// + /// Every concrete Tag type in , the library by default. + /// + internal static IReadOnlyList ConcreteTagTypes (Assembly? assembly = null) => + (assembly ?? typeof (Tag).Assembly).GetTypes () + .Where (t => t.IsClass && !t.IsAbstract && typeof (Tag).IsAssignableFrom (t)) + .ToList (); + + /// + /// True when declares Leaves itself. An inherited Leaves was written for the + /// base's tags, not the ones the type adds. + /// + internal static bool IsView (Type type) => LeavesDeclaringType (type) == type; + + /// + /// True when is a listed leaf that derives directly from Tag and keeps the base Leaves. + /// + internal static bool IsLeaf (Type type) => + LeavesDeclaringType (type) == typeof (Tag) && type.BaseType == typeof (Tag) && LeafTagTypeNames.Contains (type.FullName); + + /// + /// Null when is a view or a leaf; otherwise why it is unclassified. + /// + internal static string? Unclassified (Type type) => + IsView (type) || IsLeaf (type) ? null : $"{type.FullName} (Leaves from {LeavesDeclaringType (type)!.Name})"; + + /// + /// The library's views: every concrete Tag type that declares Leaves itself. + /// + internal static IReadOnlyList ViewTypes () => ConcreteTagTypes ().Where (IsView).ToList (); + + /// + /// The library's unclassified Tag types, with the reason for each; empty when every type is a leaf or a view. + /// + internal static IReadOnlyList Unclassified () => + ConcreteTagTypes ().Select (Unclassified).OfType ().ToList (); + + static Type? LeavesDeclaringType (Type type) => + type.GetMethod ("Leaves", BindingFlags.Instance | BindingFlags.NonPublic)!.DeclaringType; +}