diff --git a/CHANGELOG.md b/CHANGELOG.md index ec1c69d3..ddbe5c50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,18 @@ 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. +- 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. +- 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. + ## [0.6.0] - 2026-01-05 ### Breaking Changes 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/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 1cd75c97..fa5e57e8 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 @@ -91,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"; @@ -125,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"; @@ -172,51 +175,119 @@ private ApeTag (Dictionary items) /// public override string? Title { get => GetValue (Keys.Title); - set => SetOrRemove (Keys.Title, value); + set => SetOrRemoveProperty (Keys.Title, value, Title); } /// + /// + /// The first performer. Other names stay on ; a comma does not join them. + /// public override string? Artist { - get => GetValue (Keys.Artist); - set => SetOrRemove (Keys.Artist, value); + get => ReadFirstName (Keys.Artist); + set => SetOrRemoveProperty (Keys.Artist, value, Artist); + } + + /// + /// + /// 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); - set => SetOrRemove (Keys.Album, value); + set => SetOrRemoveProperty (Keys.Album, value, 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. 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 { - get => GetValue (Keys.AlbumArtist) ?? GetValue ("ALBUMARTIST"); - set => SetOrRemove (Keys.AlbumArtist, value); + get => ReadFirstName (Keys.AlbumArtist, Keys.AlbumArtistAlias); + set => SetOrRemoveProperty (Keys.AlbumArtist, value, AlbumArtist, Keys.AlbumArtistAlias); + } + + /// + /// + /// Names share one "Album Artist" item, separated by NUL. A single name has no extra NUL. + /// 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 (Keys.AlbumArtistAlias); + } + set => SetTextList (Keys.AlbumArtist, value, Keys.AlbumArtistAlias); } +#pragma warning restore CA1819 /// + /// + /// 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); - set => SetOrRemove (Keys.Year, value); + 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 { + // 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)) { + _items.Remove (Keys.Year); + _items.Remove (Keys.Date); + return; + } + + SetValue (Keys.Year, value!); + if (_items.ContainsKey (Keys.Date)) + SetValue (Keys.Date, value!); + } } /// public override string? Comment { get => GetValue (Keys.Comment); - set => SetOrRemove (Keys.Comment, value); + set => SetOrRemoveProperty (Keys.Comment, value, Comment); } /// + /// + /// The first genre. Other names stay on ; a comma does not join them. + /// public override string? Genre { - get => GetValue (Keys.Genre); - set => SetOrRemove (Keys.Genre, value); + get => ReadFirstName (Keys.Genre); + set => SetOrRemoveProperty (Keys.Genre, value, Genre); } + /// + /// + /// 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; @@ -288,145 +359,159 @@ public override uint? TotalDiscs { /// public override string? DiscSubtitle { get => GetValue ("DiscSubtitle"); - set => SetOrRemove ("DiscSubtitle", value); + set => SetOrRemoveProperty ("DiscSubtitle", value, DiscSubtitle); } /// + /// + /// The first composer. Other names stay on ; a comma does not join them. + /// public override string? Composer { - get => GetValue (Keys.Composer); - set => SetOrRemove (Keys.Composer, value); + get => ReadFirstName (Keys.Composer); + set => SetOrRemoveProperty (Keys.Composer, value, Composer); } + /// + /// + /// 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); - 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); } // ═══════════════════════════════════════════════════════════════ @@ -466,67 +551,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); } // ═══════════════════════════════════════════════════════════════ @@ -536,25 +621,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); } // ═══════════════════════════════════════════════════════════════ @@ -564,19 +649,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); } // ═══════════════════════════════════════════════════════════════ @@ -586,31 +671,95 @@ public override string? PodcastFeedUrl { /// public override string? Work { get => GetValue (Keys.Work); - set => SetOrRemove (Keys.Work, value); + set => SetOrRemoveProperty (Keys.Work, value, Work); } /// + /// + /// 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 => GetValue (Keys.Movement); - set => SetOrRemove (Keys.Movement, value); + get { + var name = GetValue (Keys.MovementName); + if (!string.IsNullOrEmpty (name)) + return name; + var legacy = LegacyMovementName; + return string.IsNullOrEmpty (legacy) ? name ?? legacy : legacy; + } + set { + 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!); + } + } } - /// - public override uint? MovementNumber { + /// + /// MOVEMENT when it holds a movement name (it is not a number), as earlier versions wrote it; otherwise null. + /// + string? LegacyMovementName { 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; + var value = GetValue (Keys.Movement); + return value is not null && ParseMovementNumber (Keys.Movement) is null ? value : 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; + } + + /// + /// + /// 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) ?? ParseMovementNumber (Keys.Movement); set { - if (value.HasValue) - SetValue (Keys.MovementNumber, value.Value.ToString (CultureInfo.InvariantCulture)); - else - _items.Remove (Keys.MovementNumber); + if (IsWriteBack (value, MovementNumber)) + return; + 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 { @@ -634,31 +783,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); } // ═══════════════════════════════════════════════════════════════ @@ -728,6 +877,96 @@ 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 (); + } + + /// + /// 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; + + var secondary = ReadListedOrRaw (alias); + 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)) + 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. + /// is removed on set and on clear so a second item cannot outlive the write. + /// + 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; + } + + 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). /// @@ -744,13 +983,29 @@ 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 . 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 (!IsWriteBack (value, current)) + SetOrRemove (key, value, alias); + } + /// /// Removes an item by key. /// 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/src/TagLibSharp2/Core/CombinedTag.cs b/src/TagLibSharp2/Core/CombinedTag.cs index 6a44f8cd..03bc347c 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 IEnumerable Leaves () + { + yield return this; + foreach (var inner in _tags) { + if (inner is null) + continue; + foreach (var leaf in inner.Leaves ()) + yield return leaf; + } + } + /// public override string? Comment { get => FirstNonEmptyString (t => t.Comment); diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 5eb98911..5d51a6f0 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -80,6 +80,50 @@ public enum TagTypes /// 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 + /// 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) => + !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) => + !IsCopying && value is not null && value == current; + /// /// Gets the type of tag represented by this instance. /// @@ -101,7 +145,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, and any value writes, replaces the list. /// Format-specific limitations: /// /// ID3v1: Truncated to 30 bytes. Latin-1 encoding only (Unicode characters are lost). @@ -116,7 +161,7 @@ public abstract class Tag /// /// /// This is the primary array of artists. The property returns - /// the first value from this array. + /// 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 @@ -129,7 +174,7 @@ public abstract class Tag #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 @@ -197,7 +242,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, 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. @@ -210,12 +256,13 @@ 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 { get => string.IsNullOrEmpty (Genre) ? [] : [Genre!]; - set => Genre = value is { Length: > 0 } ? value[0] : null; + set => Genre = FirstNonEmpty (value); } #pragma warning restore CA1819 @@ -244,6 +291,7 @@ public virtual string[] Genres { /// /// /// This returns the first album artist. For multiple album artists, use . + /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? AlbumArtist { get => null; set { } } @@ -253,13 +301,14 @@ 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 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 @@ -282,6 +331,7 @@ public virtual string[] AlbumArtists { /// /// /// This returns the first composer. For multiple composers, use . + /// In ID3v2, APE, and Vorbis Comments, writing back the value read keeps the other names; any other value, and any value writes, replaces the list. /// Not all tag formats support this field. Default implementation returns null. /// public virtual string? Composer { get => null; set { } } @@ -290,13 +340,14 @@ 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 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 @@ -342,8 +393,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 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. /// /// @@ -358,8 +411,9 @@ 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 Vorbis Comments, this is stored as 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 and APE, this is MOVEMENTNUMBER or a numeric MOVEMENT (Picard's mapping). /// Not all tag formats support this field. Default implementation returns null. /// /// @@ -374,7 +428,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. /// @@ -1153,8 +1208,20 @@ 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. + /// 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 + /// (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 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. 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. /// /// /// This is useful for converting between tag formats or synchronizing metadata @@ -1192,182 +1259,275 @@ public void CopyTo (Tag target, TagCopyOptions options = TagCopyOptions.All) ArgumentNullException.ThrowIfNull (target); #endif + if (ReferenceEquals (this, target)) + return; + + var writes = SnapshotCopyWrites (options); + + // 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; + } + + // 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 { + foreach (var write in writes) + write.Write (target); + } finally { + t_copyDepth--; + } + } + + /// + /// 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 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) + { + var writes = new List (); + // Basic metadata (always copied unless explicitly excluded) if ((options & TagCopyOptions.Basic) != 0) { if (Title is not null) - target.Title = Title; - if (Artist is not null) - target.Artist = Artist; + 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) - target.Album = Album; + Queue (writes, Album, static t => t.Album, static (t, v) => t.Album = v); var copyableDate = CopyableDate; if (copyableDate is not null) - target.Year = copyableDate; + Queue (writes, copyableDate, static t => t.ReadCopyableDate (), static (t, v) => t.Year = v); if (Comment is not null) - target.Comment = Comment; - if (Genre is not null) - target.Genre = Genre; + 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) - target.Track = Track; + Queue (writes, Track, static t => t.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 - if (AlbumArtist is not null) - target.AlbumArtist = AlbumArtist; - if (Composer is not null) - target.Composer = Composer; + // 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 => t.AlbumArtist, static (t, v) => t.AlbumArtist = v); + if (Composer is not null && Composers is not { Length: > 0 }) + Queue (writes, Composer, static t => t.Composer, static (t, v) => t.Composer = v); if (Conductor is not null) - target.Conductor = Conductor; + Queue (writes, Conductor, static t => t.Conductor, static (t, v) => t.Conductor = v); if (Copyright is not null) - target.Copyright = Copyright; + Queue (writes, Copyright, static t => t.Copyright, static (t, v) => t.Copyright = v); if (DiscNumber.HasValue) - target.DiscNumber = DiscNumber; + Queue (writes, DiscNumber, static t => t.DiscNumber, static (t, v) => t.DiscNumber = v); if (TotalDiscs.HasValue) - target.TotalDiscs = TotalDiscs; + Queue (writes, TotalDiscs, static t => t.TotalDiscs, static (t, v) => t.TotalDiscs = v); if (DiscSubtitle is not null) - target.DiscSubtitle = DiscSubtitle; + Queue (writes, DiscSubtitle, static t => t.DiscSubtitle, static (t, v) => t.DiscSubtitle = v); if (TotalTracks.HasValue) - target.TotalTracks = TotalTracks; + Queue (writes, TotalTracks, static t => t.TotalTracks, static (t, v) => t.TotalTracks = v); if (BeatsPerMinute.HasValue) - target.BeatsPerMinute = BeatsPerMinute; + Queue (writes, BeatsPerMinute, static t => t.BeatsPerMinute, static (t, v) => t.BeatsPerMinute = v); if (Lyrics is not null) - target.Lyrics = Lyrics; + Queue (writes, Lyrics, static t => t.Lyrics, static (t, v) => t.Lyrics = v); if (Isrc is not null) - target.Isrc = Isrc; + Queue (writes, Isrc, static t => t.Isrc, static (t, v) => t.Isrc = v); if (Publisher is not null) - target.Publisher = Publisher; + Queue (writes, Publisher, static t => t.Publisher, static (t, v) => t.Publisher = v); if (EncodedBy is not null) - target.EncodedBy = EncodedBy; + Queue (writes, EncodedBy, static t => t.EncodedBy, static (t, v) => t.EncodedBy = v); if (EncoderSettings is not null) - target.EncoderSettings = EncoderSettings; + Queue (writes, EncoderSettings, static t => t.EncoderSettings, static (t, v) => t.EncoderSettings = v); if (Grouping is not null) - target.Grouping = Grouping; + Queue (writes, Grouping, static t => t.Grouping, static (t, v) => t.Grouping = v); if (Subtitle is not null) - target.Subtitle = Subtitle; + Queue (writes, Subtitle, static t => t.Subtitle, static (t, v) => t.Subtitle = v); if (Remixer is not null) - target.Remixer = Remixer; + Queue (writes, Remixer, static t => t.Remixer, static (t, v) => t.Remixer = v); if (InitialKey is not null) - target.InitialKey = InitialKey; + Queue (writes, InitialKey, static t => t.InitialKey, static (t, v) => t.InitialKey = v); if (Mood is not null) - target.Mood = Mood; + Queue (writes, Mood, static t => t.Mood, static (t, v) => t.Mood = v); if (MediaType is not null) - target.MediaType = MediaType; + Queue (writes, MediaType, static t => t.MediaType, static (t, v) => t.MediaType = v); if (Language is not null) - target.Language = Language; + Queue (writes, Language, static t => t.Language, static (t, v) => t.Language = v); if (Barcode is not null) - target.Barcode = Barcode; + Queue (writes, Barcode, static t => t.Barcode, static (t, v) => t.Barcode = v); if (CatalogNumber is not null) - target.CatalogNumber = CatalogNumber; + Queue (writes, CatalogNumber, static t => t.CatalogNumber, static (t, v) => t.CatalogNumber = v); if (OriginalReleaseDate is not null) - target.OriginalReleaseDate = OriginalReleaseDate; + Queue (writes, OriginalReleaseDate, static t => t.OriginalReleaseDate, static (t, v) => t.OriginalReleaseDate = v); if (Description is not null) - target.Description = Description; + Queue (writes, Description, static t => t.Description, static (t, v) => t.Description = v); if (DateTagged is not null) - target.DateTagged = DateTagged; + Queue (writes, DateTagged, static t => t.DateTagged, static (t, v) => t.DateTagged = v); if (AmazonId is not null) - target.AmazonId = AmazonId; + Queue (writes, AmazonId, static t => t.AmazonId, static (t, v) => t.AmazonId = v); if (IsCompilation) - target.IsCompilation = true; + Queue (writes, true, static t => t.IsCompilation, static (t, v) => t.IsCompilation = v); // Classical music metadata if (Work is not null) - target.Work = Work; + Queue (writes, Work, static t => t.Work, static (t, v) => t.Work = v); if (Movement is not null) - target.Movement = Movement; + Queue (writes, Movement, static t => t.Movement, static (t, v) => t.Movement = v); if (MovementNumber.HasValue) - target.MovementNumber = MovementNumber; + Queue (writes, MovementNumber, static t => t.MovementNumber, static (t, v) => t.MovementNumber = v); if (MovementTotal.HasValue) - target.MovementTotal = MovementTotal; + Queue (writes, MovementTotal, static t => t.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 => t.AlbumSort, static (t, v) => t.AlbumSort = v); if (ArtistSort is not null) - target.ArtistSort = ArtistSort; + Queue (writes, ArtistSort, static t => t.ArtistSort, static (t, v) => t.ArtistSort = v); if (TitleSort is not null) - target.TitleSort = TitleSort; + Queue (writes, TitleSort, static t => t.TitleSort, static (t, v) => t.TitleSort = v); if (AlbumArtistSort is not null) - target.AlbumArtistSort = AlbumArtistSort; + Queue (writes, AlbumArtistSort, static t => t.AlbumArtistSort, static (t, v) => t.AlbumArtistSort = v); if (ComposerSort is not null) - target.ComposerSort = ComposerSort; + Queue (writes, ComposerSort, static t => t.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 => t.ReplayGainTrackGain, static (t, v) => t.ReplayGainTrackGain = v); if (ReplayGainTrackPeak is not null) - target.ReplayGainTrackPeak = ReplayGainTrackPeak; + Queue (writes, ReplayGainTrackPeak, static t => t.ReplayGainTrackPeak, static (t, v) => t.ReplayGainTrackPeak = v); if (ReplayGainAlbumGain is not null) - target.ReplayGainAlbumGain = ReplayGainAlbumGain; + Queue (writes, ReplayGainAlbumGain, static t => t.ReplayGainAlbumGain, static (t, v) => t.ReplayGainAlbumGain = v); if (ReplayGainAlbumPeak is not null) - target.ReplayGainAlbumPeak = ReplayGainAlbumPeak; + Queue (writes, ReplayGainAlbumPeak, static t => t.ReplayGainAlbumPeak, static (t, v) => t.ReplayGainAlbumPeak = v); if (R128TrackGain is not null) - target.R128TrackGain = R128TrackGain; + Queue (writes, R128TrackGain, static t => t.R128TrackGain, static (t, v) => t.R128TrackGain = v); if (R128AlbumGain is not null) - target.R128AlbumGain = R128AlbumGain; + 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) - target.MusicBrainzTrackId = MusicBrainzTrackId; + Queue (writes, MusicBrainzTrackId, static t => t.MusicBrainzTrackId, static (t, v) => t.MusicBrainzTrackId = v); if (MusicBrainzReleaseId is not null) - target.MusicBrainzReleaseId = MusicBrainzReleaseId; + Queue (writes, MusicBrainzReleaseId, static t => t.MusicBrainzReleaseId, static (t, v) => t.MusicBrainzReleaseId = v); if (MusicBrainzArtistId is not null) - target.MusicBrainzArtistId = MusicBrainzArtistId; + Queue (writes, MusicBrainzArtistId, static t => t.MusicBrainzArtistId, static (t, v) => t.MusicBrainzArtistId = v); if (MusicBrainzReleaseGroupId is not null) - target.MusicBrainzReleaseGroupId = MusicBrainzReleaseGroupId; + Queue (writes, MusicBrainzReleaseGroupId, static t => t.MusicBrainzReleaseGroupId, static (t, v) => t.MusicBrainzReleaseGroupId = v); if (MusicBrainzAlbumArtistId is not null) - target.MusicBrainzAlbumArtistId = MusicBrainzAlbumArtistId; + Queue (writes, MusicBrainzAlbumArtistId, static t => t.MusicBrainzAlbumArtistId, static (t, v) => t.MusicBrainzAlbumArtistId = v); if (MusicBrainzRecordingId is not null) - target.MusicBrainzRecordingId = MusicBrainzRecordingId; + Queue (writes, MusicBrainzRecordingId, static t => t.MusicBrainzRecordingId, static (t, v) => t.MusicBrainzRecordingId = v); if (MusicBrainzWorkId is not null) - target.MusicBrainzWorkId = MusicBrainzWorkId; + Queue (writes, MusicBrainzWorkId, static t => t.MusicBrainzWorkId, static (t, v) => t.MusicBrainzWorkId = v); if (MusicBrainzDiscId is not null) - target.MusicBrainzDiscId = MusicBrainzDiscId; + Queue (writes, MusicBrainzDiscId, static t => t.MusicBrainzDiscId, static (t, v) => t.MusicBrainzDiscId = v); if (MusicBrainzReleaseStatus is not null) - target.MusicBrainzReleaseStatus = MusicBrainzReleaseStatus; + Queue (writes, MusicBrainzReleaseStatus, static t => t.MusicBrainzReleaseStatus, static (t, v) => t.MusicBrainzReleaseStatus = v); if (MusicBrainzReleaseType is not null) - target.MusicBrainzReleaseType = MusicBrainzReleaseType; + Queue (writes, MusicBrainzReleaseType, static t => t.MusicBrainzReleaseType, static (t, v) => t.MusicBrainzReleaseType = v); if (MusicBrainzReleaseCountry is not null) - target.MusicBrainzReleaseCountry = MusicBrainzReleaseCountry; + Queue (writes, MusicBrainzReleaseCountry, static t => t.MusicBrainzReleaseCountry, static (t, v) => t.MusicBrainzReleaseCountry = v); if (AcoustIdId is not null) - target.AcoustIdId = AcoustIdId; + Queue (writes, AcoustIdId, static t => t.AcoustIdId, static (t, v) => t.AcoustIdId = v); if (AcoustIdFingerprint is not null) - target.AcoustIdFingerprint = AcoustIdFingerprint; + Queue (writes, AcoustIdFingerprint, static t => t.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 => t.Pictures, static (t, v) => t.Pictures = v); } + return writes; } + + /// + /// 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) + { + 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/Frames/CommentFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs index 3dfc40dd..2bc05b42 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. An internal NUL ends it. + data = Id3Text.CutAtFirstNul (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..ad3f551a 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs @@ -197,6 +197,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // 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 aad26514..f7072f5c 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; + // 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 { 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..9f40be57 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. An internal NUL ends them. + data = Id3Text.CutAtFirstNul (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..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,6 +374,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // 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 17d405c6..552a8f6d 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -105,42 +105,18 @@ 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); } - 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) { @@ -149,9 +125,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..dcf79d0c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -156,36 +156,17 @@ 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), - 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 1b76b2ca..06c457e2 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,7 @@ static string DecodeText (ReadOnlySpan data, TextEncodingType encoding) if (data.IsEmpty) return string.Empty; + // 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 new file mode 100644 index 00000000..355bf695 --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -0,0 +1,130 @@ +// 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; + +/// +/// Shared decoding for ID3 text. A trailing terminator is not part of the string. +/// +internal static class Id3Text +{ + /// + /// 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) { + 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 72b73105..57e2b6d4 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -202,25 +202,29 @@ 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); } /// 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); + } } /// @@ -247,30 +251,41 @@ 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. + /// 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 { + // 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", + value, + Version == 4, + keepMatchingYear: false, + alsoClear: Version == 4 ? "TORY" : "TDOR"); } - set => SetDateFrame (Version == 4 ? "TDOR" : "TORY", value, Version == 4, keepMatchingYear: false); } /// public override string? Comment { get => GetComment (); - set => SetComment (value); + set { + if (!IsWriteBack (value, Comment)) + SetComment (value); + } } /// @@ -494,8 +509,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); } /// @@ -532,7 +551,7 @@ public override uint? Track { /// public override string? AlbumArtist { get => GetTextFrame ("TPE2"); - set => SetTextFrame ("TPE2", value); + set => SetTextFrameProperty ("TPE2", value, AlbumArtist); } /// @@ -569,7 +588,7 @@ public override uint? DiscNumber { /// public override string? Composer { get => GetTextFrame ("TCOM"); - set => SetTextFrame ("TCOM", value); + set => SetTextFrameProperty ("TCOM", value, Composer); } /// @@ -586,13 +605,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); } /// @@ -612,115 +631,118 @@ public override bool IsCompilation { /// public override string? PodcastFeedUrl { get => GetUrl ("WFED"); - set => SetUrl ("WFED", value); + set { + if (!IsWriteBack (value, PodcastFeedUrl)) + SetUrl ("WFED", value); + } } /// 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); } /// @@ -844,109 +866,112 @@ public override uint? TotalDiscs { /// public override string? Lyrics { get => GetLyrics (); - set => SetLyrics (value); + set { + if (!IsWriteBack (value, Lyrics)) + SetLyrics (value); + } } /// 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); } /// @@ -955,53 +980,66 @@ 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. - /// Writes to TXXX:MOVEMENT for compatibility with non-Apple software. + /// 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"); - set => SetUserText ("MOVEMENT", value); + get { + var apple = GetTextFrame ("MVNM"); + if (!string.IsNullOrEmpty (apple)) + return apple; + var user = GetUserText ("MOVEMENT"); + return string.IsNullOrEmpty (user) ? apple ?? user : user; + } + set { + if (IsWriteBack (value, Movement)) + return; + 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. + /// 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 { @@ -1016,13 +1054,22 @@ 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 { + if (IsWriteBack (value, MovementNumber)) + return; + 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. + /// 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 { @@ -1037,7 +1084,32 @@ 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 { + if (IsWriteBack (value, MovementTotal)) + return; + 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)); } /// @@ -1156,6 +1228,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!)); @@ -1447,11 +1521,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, "" 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) + { + 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,18 +1550,44 @@ static bool HasDuplicateTagAfter (ReadOnlySpan data, int firstTagEnd) return null; } + /// + /// 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) + { + 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 ""; + } + /// /// 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 (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). + /// 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 /// separator, but "/" is commonly used. This method handles both. /// 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 (); @@ -1482,12 +1597,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; } @@ -1635,10 +1751,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; } @@ -1652,9 +1770,32 @@ 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); } + /// + /// 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 (!IsWriteBack (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 (!IsWriteBack (value, current)) + SetUserText (description, value); + } + /// /// Sets or creates a text frame. /// @@ -1994,20 +2135,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) => @@ -2074,12 +2223,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 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) { 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; } @@ -2133,14 +2285,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/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/src/TagLibSharp2/Xiph/FlacTag.cs b/src/TagLibSharp2/Xiph/FlacTag.cs index 4bd64bf3..ce6e7bd8 100644 --- a/src/TagLibSharp2/Xiph/FlacTag.cs +++ b/src/TagLibSharp2/Xiph/FlacTag.cs @@ -112,6 +112,16 @@ public override string? Movement { set => EnsureVorbisComment ().Movement = value; } + /// + 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 { get => _file.VorbisComment?.Copyright; diff --git a/src/TagLibSharp2/Xiph/VorbisComment.cs b/src/TagLibSharp2/Xiph/VorbisComment.cs index 54eaf0f7..8107a795 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,28 +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"); - set => SetValue ("ORIGINALDATE", value); + 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); } /// @@ -175,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); } /// @@ -220,7 +224,7 @@ public override uint? DiscNumber { /// public override string? Composer { get => GetValue ("COMPOSER"); - set => SetValue ("COMPOSER", value); + set => SetValueProperty ("COMPOSER", value, Composer); } /// @@ -257,31 +261,82 @@ 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. + /// 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 => GetValue ("MOVEMENT") ?? GetValue ("MOVEMENTNAME"); - set => SetValue ("MOVEMENT", value); + get { + var name = GetValue ("MOVEMENTNAME"); + if (!string.IsNullOrEmpty (name)) + return name; + var legacy = LegacyMovementName; + return string.IsNullOrEmpty (legacy) ? name ?? legacy : legacy; + } + set { + 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); + } + } + + /// + /// MOVEMENT when it holds a movement name (it is not a number), as earlier versions wrote it; otherwise null. + /// + string? LegacyMovementName { + get { + var value = GetValue ("MOVEMENT"); + return value is not null && !TryParseUInt (value, out _) ? value : null; + } } /// + /// + /// 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 { - var value = GetValue ("MOVEMENTNUMBER"); - return TryParseUInt (value, out var num) ? num : null; + if (TryParseUInt (GetValue ("MOVEMENTNUMBER"), out var num)) + return num; + return TryParseUInt (GetValue ("MOVEMENT"), out num) ? num : null; + } + set { + if (IsWriteBack (value, MovementNumber)) + return; + var text = value?.ToString (System.Globalization.CultureInfo.InvariantCulture); + if (LegacyMovementName is not null) { + SetValue ("MOVEMENTNUMBER", text); + return; + } + SetValue ("MOVEMENT", text); + if (text is null || GetValue ("MOVEMENTNUMBER") is not null) + SetValue ("MOVEMENTNUMBER", text); } - set => SetValue ("MOVEMENTNUMBER", value?.ToString (System.Globalization.CultureInfo.InvariantCulture)); } /// @@ -300,7 +355,7 @@ public override uint? MovementTotal { /// public override string? Copyright { get => GetValue ("COPYRIGHT"); - set => SetValue ("COPYRIGHT", value); + set => SetValueProperty ("COPYRIGHT", value, Copyright); } /// @@ -317,103 +372,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); } /// @@ -481,49 +536,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); } /// @@ -533,103 +588,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); } /// @@ -705,7 +760,7 @@ public override uint? TotalDiscs { /// public override string? DiscSubtitle { get => GetValue ("DISCSUBTITLE"); - set => SetValue ("DISCSUBTITLE", value); + set => SetValueProperty ("DISCSUBTITLE", value, DiscSubtitle); } /// @@ -739,10 +794,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) { @@ -756,11 +815,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; } /// @@ -912,6 +975,80 @@ 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, and so does an empty string unless every value is already empty. + /// + void SetValueProperty (string name, string? value, string? current) + { + if (!IsWriteBack (value, current)) + 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 . + /// 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) + { + 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) + SetValue (name, value); + return; + } + + if (string.IsNullOrEmpty (value)) { + RemoveAll (fallback); + SetValue (name, value); + 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; + } + /// /// Removes all fields with the specified name. /// diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTests.cs index cce27d50..11d510a4 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,343 @@ 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]); + } + + [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.AreEqual ("", onlyNuls.Artist); + Assert.HasCount (0, onlyNuls.Performers); + + var emptyText = new ApeTag (); + emptyText.SetValue ("Genre", ""); + Assert.AreEqual ("", 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); + } + + [TestMethod] + public void Year_Set_RewritesDate_ClearRemovesBoth () + { + var replaced = new ApeTag (); + replaced.SetValue ("Date", "1999"); + replaced.Year = "2001"; + + Assert.AreEqual ("2001", replaced.Year); + Assert.AreEqual ("2001", replaced.GetValue ("Year")); + Assert.AreEqual ("2001", 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 = ""; + 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] + 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); + } + + [TestMethod] + public void AlbumArtist_LocatorDoesNotHideAliasText () + { + 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!; + } + + 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/Ape/ApeTagWriteBackTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs new file mode 100644 index 00000000..0f6fc9d1 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagWriteBackTests.cs @@ -0,0 +1,203 @@ +// 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_AndAnEditReplaces (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); + var read = (string?)property.GetValue (tag); + property.SetValue (tag, read); + var after = Snapshot (Reparse (tag)); + + 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. + 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)); + 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 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 () + { + 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/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/TagCopyListToSingleTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs new file mode 100644 index 00000000..a0c9e85f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagCopyListToSingleTests.cs @@ -0,0 +1,118 @@ +// 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] + [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 () + { + 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/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs new file mode 100644 index 00000000..5437f947 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -0,0 +1,578 @@ +// 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.Mpeg; +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 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")); + } + + static Id3v2Tag PicardId3 (Id3v2Version version) + { + var tag = new Id3v2Tag (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!; + } + + 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)); + + // 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] + 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] + [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 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 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 types = TagTypeClassification.ConcreteTagTypes (); + var unclassified = TagTypeClassification.Unclassified (); + + Assert.IsEmpty (unclassified, string.Join (",", unclassified)); + 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.Contains (name, views); + } + + [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 => TagTypeClassification.Unclassified (t) is null).Select (t => t.Name).ToList (); + + Assert.HasCount (11, dummies); + Assert.IsEmpty (missed, string.Join (",", missed)); + } + + [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 () { } + } +} + +/// +/// 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 diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs index 06a20f5a..53110d97 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyTests.cs @@ -1,9 +1,12 @@ // 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.Asf; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Mp4; using TagLibSharp2.Xiph; namespace TagLibSharp2.Tests.Core; @@ -266,6 +269,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 +280,129 @@ 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] + 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_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] 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; +} 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/Id3v2TagClassicalMusicTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs index 454cb9a2..eefc97eb 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TagClassicalMusicTests.cs @@ -134,6 +134,91 @@ 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 = 12; + Assert.AreEqual (9u, indexed.Tag.MovementNumber); + 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 (12u, indexed.Tag.MovementTotal); + + indexed.Tag.MovementTotal = null; + Assert.IsNull (indexed.Tag.MovementNumber); + Assert.IsNull (indexed.Tag.MovementTotal); + 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!; + + 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); + Assert.AreEqual (2u, reparsed.Tag!.MovementNumber); + Assert.IsNull (reparsed.Tag.MovementTotal); + } + [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 () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs new file mode 100644 index 00000000..c24ec065 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2TrailingTerminatorTests.cs @@ -0,0 +1,704 @@ +// 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. +/// Text frames keep internal NULs between values. A comment or lyric ends at the first NUL. +/// +[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_EndsTheText () + { + // 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", 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] + 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_EndsTheText () + { + 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", 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] + 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 InvolvedPeople_Utf16OddLength_DoesNotDropTheLastCharacter () + { + 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 (0x41, 0x00); // A + builder.Add (0x00); // lone byte; pairing it with the low byte of A would eat the name + + var frame = InvolvedPeopleFrame.Read ("TIPL", builder.ToBinaryData ().Span, Id3v2Version.V24); + + Assert.IsTrue (frame.IsSuccess, frame.Error); + Assert.AreEqual (1, frame.Frame!.Count); + Assert.AreEqual ("A", frame.Frame.GetPerson ("guitar")); + } + + [TestMethod] + public void Performers_Utf16BomOnEachValue_ReturnsBothNames () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("a")); + builder.Add (0, 0); + builder.Add (0xFF, 0xFE); + builder.Add (Encoding.Unicode.GetBytes ("b")); + builder.Add (0, 0); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + 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 Performers_Utf16SecondValueBigEndianBom_ReturnsBothNames () + { + using var builder = new BinaryDataBuilder (); + 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 tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().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 Performers_Utf16SecondValueWithoutBom_UsesFirstBom () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFE, 0xFF); + builder.Add (0x00, 0x61); + builder.Add (0, 0); + builder.Add (0x00, 0x62); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TPE1", builder.ToBinaryData ().ToArray ()); + + Assert.HasCount (2, tag.Performers); + Assert.AreEqual ("a", tag.Performers[0]); + Assert.AreEqual ("b", tag.Performers[1]); + } + + [TestMethod] + public void Title_Utf16OddLength_DoesNotDropLastCharacter () + { + using var builder = new BinaryDataBuilder (); + builder.Add ((byte)TextEncodingType.Utf16WithBom); + builder.Add (0xFF, 0xFE); + builder.Add (0x41, 0x00); + builder.Add (0x42, 0x00); + builder.Add (0x00); + + var tag = ReadFrame (TestConstants.Id3v2.Version4, "TIT2", builder.ToBinaryData ().ToArray ()); + + Assert.AreEqual ("AB", tag.Title); + Assert.AreEqual ("AB", tag.Frames[0].Text); + } + + [TestMethod] + public void Text_LeadingNul_ReadsTheFirstNonEmptyValue () + { + using var builder = new BinaryDataBuilder (); + 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 ("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 ("b", 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 ("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")); + } + + [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.AreEqual ("A\0B", stored); + 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_SingleValueIsTheFirstName () + { + 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 ("b", tag.GetTextFrame ("TPE1")); + Assert.AreEqual ("b", 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 (); + 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) + { + 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')); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs new file mode 100644 index 00000000..c7dd1cc2 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WriteBackTests.cs @@ -0,0 +1,449 @@ +// 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_AndAnEditReplaces (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); + var read = (string?)property.GetValue (tag); + property.SetValue (tag, read); + var after = Snapshot (Reparse (tag)); + + 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. + 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)); + foreach (var name in ListFields) + Assert.Contains (name, covered); + 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"]; + + /// + /// 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 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) { + // 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) { + 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) + 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 (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 ((Id3v2Version)version); + property.SetValue (probe, candidate); + if (!Equals (property.GetValue (probe), candidate)) + continue; + var foreign = BuildForeign (probe, version, candidate); + if (Equals (property.GetValue (foreign), candidate)) { + tag = foreign; + break; + } + } + if (tag is null) { + uncovered.Add (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] + [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] + [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 () + { + 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 () + { + 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 LeadingEmptyValue_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClears (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 ("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 = ""; + 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)] + 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] + public void Genre_EmptyValues_ReadTheFirstNonEmptyValue () + { + // 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 = ""; + 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 ("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"; + 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/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; } 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 dcd4b269..d0c0c4d8 100644 --- a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentExtendedMetadataTests.cs @@ -355,6 +355,221 @@ 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_Set_RewritesOriginalYear_ClearRemovesBoth () + { + var comment = new VorbisComment ("test"); + comment.AddField ("ORIGINALYEAR", "1969"); + comment.OriginalReleaseDate = "2001-01-01"; + + Assert.AreEqual ("2001-01-01", comment.OriginalReleaseDate); + 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.OriginalReleaseDate = null; + Assert.IsNull (comment.OriginalReleaseDate); + Assert.HasCount (0, comment.GetValues ("ORIGINALYEAR")); + Assert.HasCount (0, comment.GetValues ("ORIGINALDATE")); + } + + [TestMethod] + [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_WritesMovementName_ClearRemovesIt () + { + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.Movement = "Allegro"; + + Assert.AreEqual ("Allegro", comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + AssertSingle (comment, "MOVEMENTNAME", "Allegro"); + + comment.Movement = null; + Assert.IsNull (comment.Movement); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + Assert.HasCount (0, comment.GetValues ("MOVEMENTNAME")); + } + + [TestMethod] + 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_LeavesAnEmptyNameAndRemovesALegacyName () + { + var comment = new VorbisComment ("test"); + comment.AddField ("MOVEMENTNAME", "Adagio"); + comment.AddField ("MOVEMENT", "Adagio"); + comment.Movement = ""; + + Assert.AreEqual ("", comment.Movement); + AssertSingle (comment, "MOVEMENTNAME", ""); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + } + + [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] + [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 () + { + 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 () { diff --git a/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs new file mode 100644 index 00000000..c84f657e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Xiph/VorbisCommentWriteBackTests.cs @@ -0,0 +1,127 @@ +// 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_AndAnEditReplaces (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); + var read = (string?)property.GetValue (comment); + property.SetValue (comment, read); + var after = Snapshot (Reparse (comment)); + + 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. + 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)); + foreach (var name in ListFields) + Assert.Contains (name, covered); + Assert.IsGreaterThanOrEqualTo (45, covered.Count, string.Join (",", covered)); + } + + [TestMethod] + public void LeadingEmptyField_ReadsTheNextValue_WriteBackKeepsIt_EmptyStringClears () + { + 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 ("V2", comment.Artist); + 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; + Assert.AreEqual (before, string.Join ("|", comment.Fields.Select (f => f.Name + "=" + f.Value))); + + comment.Artist = ""; + comment.Movement = ""; + + Assert.AreEqual ("", string.Join ("|", comment.GetValues ("ARTIST"))); + Assert.HasCount (0, comment.GetValues ("MOVEMENT")); + Assert.AreEqual ("", string.Join ("|", 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 () + { + 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")); + } +}