diff --git a/CHANGELOG.md b/CHANGELOG.md index b165f706..52d44dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A file whose RIFF size is still the streaming placeholder 0xFFFFFFFF reports no duration: its frame counts were never filled in. - AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; a save that would have to rewrite untouched text whose code page is a guess (no `CSET`), is not decoded here (for example Shift-JIS or cp1251), or that holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) is refused, and the error names the field and which of those reasons applies. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO is unchanged (Latin-1). - Limits: a save loads the whole file (about the file's size in memory when nothing moves, twice that when data moves), so AVI files of 2 GiB or more cannot be saved yet. `MediaFile.Read` and `AviFile.ReadFromFile` read only the header and tag chunks. +- Matroska `AlbumArtistSort` and `ComposerSort`: `SORT_WITH` nested in the album-level `ARTIST` (`TargetTypeValue` 50) and in `COMPOSER`, with flat `ALBUM_ARTIST_SORT` / `COMPOSER_SORT` as the fallback. Clearing removes both forms at every level the getter reads. When the track inherits the album's `ARTIST`, writing either `ArtistSort` or `AlbumArtistSort` first copies that `ARTIST` to the track level, so the other sort is kept (#116). #### Raw AAC (ADTS/ADIF) Support - `AacFile` reads and writes raw AAC files (`.aac`): ADTS (ISO/IEC 13818-7 §6.2, MPEG-2 and MPEG-4) and ADIF (§6.1) @@ -86,6 +87,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska: a new SeekHead entry is added only to the first SeekHead (RFC 9559 section 6.3). - A file that starts with an ID3v2 tag followed by an ADTS or ADIF stream is now detected as `MediaFormat.Aac` instead of `MediaFormat.Mp3`, and `Mp3File.IsValidFormat` returns false for it - APE: `ApeTagItem.Parse` and the item check that places an APEv2 tag (`ApeTagLocation`, used by WavPack, Musepack, Monkey's Audio and AAC) now share one set of item rules, and the check no longer copies each item value. The accepted tags are unchanged. The reserved-key error now names the reserved spelling ("ID3", "TAG", "OggS", "MP+"), not the key as written. +- Matroska `AlbumArtists` reads and writes a flat `ALBUM_ARTIST` (the name ffmpeg writes) when the file has one, so it pairs with that file's `ALBUM_ARTIST_SORT`; otherwise it is still the album-level `ARTIST`. Clearing it removes `ALBUM_ARTIST` and `ALBUM_ARTIST_SORT`. +- Matroska sort setters treat an empty string like null and remove the sort, the way the parent setters already do. +- Matroska fields written for the whole file (`Year`, `Comment`, `Genre`, `Genres`, `Composers` and the like) are written where their getter reads them. A value inherited from a broader target is replaced in place instead of shadowed by a copy at the track level, and a clear removes the name at every level the getter reads, so `Genre = null` no longer leaves an inherited genre showing. A new field goes beside the file's other fields, not into a Tag that holds only `ARTIST`. +- Matroska flat sorts (`ARTIST_SORT`, `ALBUM_ARTIST_SORT`, `COMPOSER_SORT`) belong to the value in their own Tag, as ffmpeg writes them. A Tag without that value passes its sort down to the value below it, and a broader Tag that repeats the same value is the same value (the tagging spec allows repeating it per track). Only a broader Tag with a different value keeps its own sort apart. A set leaves one copy, in the value's Tag; a clear removes every copy of that value's sort; a cleared value takes the sorts of its own Tag and of the value-less broader Tags above it, unless an equal value below still reads them, and a broader Tag that repeats it keeps its own; and a value placed between another value and its sort moves that sort down to the value it sorts. The track title, album title and album-level album artist pair their sorts over the run that starts at their level, so a value-less `ALBUM_ARTIST_SORT` at 60 or 70 is read, cleared and replaced too. A value written equal to the broader one it shadows repeats that SimpleTag with its `SORT_WITH`. Tags that target a chapter, attachment, track or edition are never read or changed by these rules. +- Matroska custom fields named `TITLE_SORT`, `ARTIST_SORT`, `ALBUM_SORT`, `ALBUM_ARTIST_SORT` or `COMPOSER_SORT` are read, written and removed through the matching sort property, so they pair with their value and see a nested `SORT_WITH`; a sort takes one value. +- Matroska setters treat writing back the value read as a no-op, so the file's bytes stay as they were; a null still clears, including a value a broader level holds behind an empty one. They follow `Tag.IsWriteBack`, checked before anything changes and against the list the getter reads: `""` or an empty list is a write-back only when no value holds text, and `CopyTo` makes the target hold exactly the source's value, so a copy equal to the target's first ISRC, catalog number, artist or genre replaces the rest of the list. `Publisher = null` also removes `LABEL`, and `ReplayGainTrackGain`/`ReplayGainTrackPeak` remove the older `REPLAYGAIN_GAIN`/`REPLAYGAIN_PEAK` copy on a set or clear, as their getters read those names. ### Fixed diff --git a/README.md b/README.md index 2babe936..22492f46 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison - **Multi-Target**: Supports .NET Standard 2.0/2.1, .NET 8.0, and .NET 10.0 - **Format Support**: - Audio: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC), raw AAC (ADTS/ADIF, ID3v2/APEv2/ID3v1), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack - - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags, chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. + - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags (including `SORT_WITH` sort names for title, artist, album, album artist, and composer), chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. - MPEG program streams (`.mpg`, `.mpeg`, `.mpe`, `.vob`) and MPEG video elementary streams (`.mpv`, `.m1v`, `.m2v`): duration, MPEG-1/MPEG-2 video properties, and the first audio stream (MPEG audio, AC-3, LPCM). ID3v2 in front of the stream, an ID3v2.4 tag appended after it (the layout TagLib# writes), and ID3v1 are read and written in place; the stream bytes are not changed. - Audible `.aa`: the text dictionary (title, author, narrator, dates, descriptions, and every other key by name), the cover image, and the duration. Dictionary edits can be saved; the encrypted audio, its DRM keys, and the cover are copied unchanged. Edited files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores (the purpose of the `68ec733412b9` key is unknown). Keep a copy of the original, or save to a new path. Audible `.aax` is MPEG-4 and opens as MP4/M4A, with its audiobook atoms (narrator, short and parent titles, product IDs, release date) as named properties. Decryption is out of scope. - AVI (`.avi`, including OpenDML): RIFF INFO and `ID32` (ID3v2) tags, duration, video size, frame rate and FourCC, and the first audio stream. Tags are saved without changing the `movi` sample data; every `idx1` and OpenDML index stays valid. INFO text follows the RIFF `CSET` chunk (ISO 8859-1 when there is none): 65001, 1252, 0 and 28591 are decoded, and with no `CSET` valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and other text as Windows-1252. On save, a value you did not change keeps its exact bytes and the file keeps its `CSET`; changed values are written in the file's code page when they fit it (with no `CSET`, ASCII only), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it, which ffprobe, TagLib# and exiftool read (mediainfo ignores `CSET`). When the list becomes UTF-8, untouched text in a declared code page that is decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; the save is refused, with an error naming the field and the reason, when an untouched value's code page is only a guess (no `CSET`), is not decoded here (Shift-JIS, cp1251, ...), or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0). The new `CSET` keeps the old one's country, language and dialect codes. The five undefined 1252 code points are written as UTF-8, never as 1252 bytes. A save loads the whole file into memory (about one file's worth when nothing moves, two when the data has to move), so AVI files of 2 GiB or more cannot be saved yet; reading has no such limit. diff --git a/src/TagLibSharp2/Matroska/MatroskaTag.cs b/src/TagLibSharp2/Matroska/MatroskaTag.cs index e78eaedb..ef00fd65 100644 --- a/src/TagLibSharp2/Matroska/MatroskaTag.cs +++ b/src/TagLibSharp2/Matroska/MatroskaTag.cs @@ -31,6 +31,8 @@ public sealed class MatroskaTag : Tag const ulong AlbumLevel = 50; const ulong PartLevel = 40; const ulong TrackLevel = 30; + const string AlbumArtistName = "ALBUM_ARTIST"; + const string AlbumArtistSortName = "ALBUM_ARTIST_SORT"; readonly List _blocks = new (); string? _segmentTitle; @@ -44,25 +46,39 @@ internal MatroskaTag () /// public override string? Title { - get { - // TITLE at 30 is the track. An empty one blocks every broader title. - if (HasFileLevelName (TrackLevel, "TITLE")) - return FirstAt (TrackLevel, "TITLE"); - // The segment title is the file title. Otherwise the most specific - // file-level TITLE below a collection still displays, so a part, - // edition, or lone album title is not a blank name. - if (!string.IsNullOrEmpty (_segmentTitle)) - return _segmentTitle; - var level = MostSpecificFileTitleBelowCollection (); - return level is ulong found ? FirstAt (found, "TITLE") : null; + get => FirstOf (TitlesRead ()); + set { + if (IsWriteBackAt (value, TitlesRead (), TrackLevel, "TITLE")) + return; + SetValue (TrackLevel, "TITLE", value, [], ["TITLE_SORT"], shadows: false); } - set => SetAt (TrackLevel, "TITLE", value); } + /// + /// The titles Title reads, the first of which it returns; its setter's write-back check reads the same list. + /// TITLE at 30 is the track, and an empty one blocks every broader title. The segment title is the file + /// title. Otherwise the most specific file-level TITLE below a collection still displays, so a part, + /// edition, or lone album title is not a blank name. + /// + string[] TitlesRead () + { + if (HasFileLevelName (TrackLevel, "TITLE")) + return AllAt (TrackLevel, "TITLE"); + if (!string.IsNullOrEmpty (_segmentTitle)) + return [_segmentTitle!]; + return MostSpecificFileTitleBelowCollection () is ulong level ? AllAt (level, "TITLE") : []; + } + + static string? FirstOf (string[] values) => values.Length > 0 ? values[0] : null; + /// public override string? Artist { - get => First ("ARTIST"); - set => SetAt (TrackLevel, "ARTIST", value); + get => FirstOf (All ("ARTIST")); + set { + if (IsWriteBackAt (value, All ("ARTIST"), TrackLevel, "ARTIST")) + return; + SetValue (TrackLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT"], shadows: true); + } } /// @@ -71,19 +87,56 @@ public override string[] Performers { var artists = All ("ARTIST"); return artists.Length > 0 ? artists : All ("ACTOR"); } - set => SetAtValues (TrackLevel, "ARTIST", value); + set { + if (IsListWriteBack (value, Performers, AnyTextAt (TrackLevel, "ARTIST"), clearsOneLevel: true)) + return; + SetValues (TrackLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT"], shadows: true); + } } /// public override string? Album { - get => FirstAt (AlbumLevel, "TITLE"); - set => SetAt (AlbumLevel, "TITLE", value); + get => FirstOf (AllAt (AlbumLevel, "TITLE")); + set { + if (IsWriteBackAt (value, AllAt (AlbumLevel, "TITLE"), AlbumLevel, "TITLE")) + return; + SetValue (AlbumLevel, "TITLE", value, [], ["ALBUM_SORT"], shadows: false); + } } /// + /// + /// The album artist is ARTIST at the album level (TargetTypeValue 50), per + /// https://www.matroska.org/technical/tagging.html. A file that carries a flat ALBUM_ARTIST + /// (the name ffmpeg writes) names its album artist there instead: it is read and written, and + /// clearing it also removes its flat ALBUM_ARTIST_SORT, so the specification's album-level + /// ARTIST shows through. + /// public override string[] AlbumArtists { - get => ItemLevel >= AlbumLevel ? All ("ARTIST") : AllAt (AlbumLevel, "ARTIST"); - set => SetAtValues (AlbumLevel, "ARTIST", value); + get { + if (UsesAlbumArtistName) + return All (AlbumArtistName); + return ItemLevel >= AlbumLevel ? All ("ARTIST") : AllAt (AlbumLevel, "ARTIST"); + } + set { + // A clear of ALBUM_ARTIST removes every visible level; the spec-level write is one level. + var byName = UsesAlbumArtistName; + if (IsListWriteBack (value, AlbumArtists, byName ? AnyText (AlbumArtistName) : AnyTextAt (AlbumLevel, "ARTIST"), clearsOneLevel: !byName)) + return; + if (!UsesAlbumArtistName) { + // ALBUM_ARTIST_SORT at 50 is the album artist's whatever the track has, so only ARTIST_SORT can be the track's. + SetValues (AlbumLevel, "ARTIST", value, ["ARTIST_SORT"], ["ARTIST_SORT", AlbumArtistSortName], shadows: true); + return; + } + + if (!HasText (value)) { + RemoveVisible (AlbumArtistName); + RemoveVisible (AlbumArtistSortName); + return; + } + + SetAtValues (ChosenLevel (AlbumArtistName)!.Value, AlbumArtistName, value); + } } /// @@ -167,7 +220,15 @@ public override uint? TotalDiscs { /// public override string[] Composers { get => All ("COMPOSER"); - set => SetItemValues ("COMPOSER", value); + set { + // The write-back check runs first, as in every setter. A clear takes the composers' flat sorts with + // them; a COMPOSER_SORT with no COMPOSER is left alone. + if (IsListWriteBack (value, Composers, AnyText ("COMPOSER"), clearsOneLevel: false)) + return; + if (!HasText (value) && ChosenLevel ("COMPOSER") is not null) + RemoveVisible ("COMPOSER_SORT"); + SetItemValues ("COMPOSER", value); + } } /// @@ -197,7 +258,12 @@ public override string? Subtitle { /// public override uint? BeatsPerMinute { get => ParseWholeOrDecimal (First ("BPM")); - set => SetItem ("BPM", value?.ToString (CultureInfo.InvariantCulture)); + set { + // "120.0" reads as 120; writing 120 back is not a change, but a copy replaces a list of them. + if (value is not null && value == BeatsPerMinute && (!IsCopying || All ("BPM").Length == 1)) + return; + SetItem ("BPM", value?.ToString (CultureInfo.InvariantCulture)); + } } /// @@ -209,7 +275,7 @@ public override string? Conductor { /// public override string? Publisher { get => First ("PUBLISHER") ?? First ("LABEL"); - set => SetItem ("PUBLISHER", value); + set => SetItemWithFallback ("PUBLISHER", "LABEL", value, Publisher, replaceFallback: false); } /// @@ -274,32 +340,98 @@ public override string? DateTagged { /// public override string? TitleSort { - get => NestedSortAt (TrackLevel, "TITLE") ?? FirstAt (TrackLevel, "TITLE_SORT"); - set => SetSort ("TITLE", "TITLE_SORT", value, TrackLevel); + get => ReadSort ("TITLE", "TITLE_SORT", TrackLevel); + set { + if (IsSortWriteBack (value, "TITLE", "TITLE_SORT", TrackLevel)) + return; + SetSort ("TITLE", "TITLE_SORT", value, TrackLevel); + } } /// + /// + /// SORT_WITH nested in the ARTIST that reads, else the flat + /// ARTIST_SORT that belongs to it: in its Tag, in a broader Tag that repeats the same artist, or + /// passed down from a broader Tag with no ARTIST. A broader Tag with a different artist keeps its + /// ARTIST_SORT for that artist. + /// public override string? ArtistSort { - get => NestedSort ("ARTIST") ?? First ("ARTIST_SORT"); - set => SetSort ("ARTIST", "ARTIST_SORT", value, null); + get => ReadSort ("ARTIST", "ARTIST_SORT", null); + set { + if (IsSortWriteBack (value, "ARTIST", "ARTIST_SORT", null)) + return; + SplitSharedArtist (NullIfEmpty (value)); + SetSort ("ARTIST", "ARTIST_SORT", value, null); + } } /// public override string? AlbumSort { - get => NestedSortAt (AlbumLevel, "TITLE") ?? FirstAt (AlbumLevel, "ALBUM_SORT"); - set => SetSort ("TITLE", "ALBUM_SORT", value, AlbumLevel); + get => ReadSort ("TITLE", "ALBUM_SORT", AlbumLevel); + set { + if (IsSortWriteBack (value, "TITLE", "ALBUM_SORT", AlbumLevel)) + return; + SetSort ("TITLE", "ALBUM_SORT", value, AlbumLevel); + } + } + + /// + /// + /// + /// The sort of the album artist that reads: SORT_WITH nested in + /// that SimpleTag, else the flat ALBUM_ARTIST_SORT that belongs to it: in its Tag, in a broader + /// Tag that repeats the same artist, or passed down from one with no artist. For a flat ALBUM_ARTIST that is its own + /// SORT_WITH or ALBUM_ARTIST_SORT. + /// See https://www.matroska.org/technical/tagging.html ("Nested Information", "Target types") + /// and RFC 9559 section 5.1.8. + /// + /// + /// When the file has no tag below the album level, the album-level ARTIST is also the + /// track's artist, and one SORT_WITH is read as both this and . + /// Before a write would change one of them, the ARTIST is copied to the track level (30), + /// so the track keeps its own sort and the two stay independent. + /// + /// + public override string? AlbumArtistSort { + get => ReadSort (AlbumArtistValueName, AlbumArtistSortName, AlbumArtistSortLevel); + set { + if (IsSortWriteBack (value, AlbumArtistValueName, AlbumArtistSortName, AlbumArtistSortLevel)) + return; + if (UsesAlbumArtistName) { + SetSort (AlbumArtistName, AlbumArtistSortName, value, null); + return; + } + + SplitSharedArtist (NullIfEmpty (value)); + SetSort ("ARTIST", AlbumArtistSortName, value, AlbumArtistSortLevel); + } + } + + /// + /// + /// SORT_WITH nested in the COMPOSER that reads, else the flat + /// COMPOSER_SORT that belongs to it: at its level, at a broader level that repeats the same + /// composer, or passed down from one with no COMPOSER. See https://www.matroska.org/technical/tagging.html. + /// + public override string? ComposerSort { + get => ReadSort ("COMPOSER", "COMPOSER_SORT", null); + set { + if (IsSortWriteBack (value, "COMPOSER", "COMPOSER_SORT", null)) + return; + SetSort ("COMPOSER", "COMPOSER_SORT", value, null); + } } /// public override string? ReplayGainTrackGain { get => First ("REPLAYGAIN_TRACK_GAIN") ?? First ("REPLAYGAIN_GAIN"); - set => SetItem ("REPLAYGAIN_TRACK_GAIN", value); + set => SetItemReplacingLegacy ("REPLAYGAIN_TRACK_GAIN", "REPLAYGAIN_GAIN", value, ReplayGainTrackGain); } /// public override string? ReplayGainTrackPeak { get => First ("REPLAYGAIN_TRACK_PEAK") ?? First ("REPLAYGAIN_PEAK"); - set => SetItem ("REPLAYGAIN_TRACK_PEAK", value); + set => SetItemReplacingLegacy ("REPLAYGAIN_TRACK_PEAK", "REPLAYGAIN_PEAK", value, ReplayGainTrackPeak); } /// @@ -442,13 +574,52 @@ public override void Clear () /// exactly, the way reads COMMENT: the nearest level at or above the item /// level that sets the name wins (RFC 9559 §5.1.8.1.1 and https://www.matroska.org/technical/tagging.html). /// A tag with only TagBinary has no text and is skipped. + /// + /// A flat sort name (TITLE_SORT, ARTIST_SORT, ALBUM_SORT, ALBUM_ARTIST_SORT, + /// COMPOSER_SORT) is read, set and removed through its sort property, so it pairs with its value the + /// same way: a sort belongs to the value it sorts, and a nested SORT_WITH wins over the flat name. + /// /// public override IReadOnlyList GetCustomField (string name) { CustomFieldValues.ThrowIfNull (name); + if (IsSortName (name)) + return SortByName (name) is string sort ? [sort] : CustomFieldValues.None; return CustomFieldValues.IsUsableName (name) ? All (name) : CustomFieldValues.None; } + static bool IsSortName (string name) => + name is "TITLE_SORT" or "ARTIST_SORT" or "ALBUM_SORT" or AlbumArtistSortName or "COMPOSER_SORT"; + + string? SortByName (string name) => name switch { + "TITLE_SORT" => TitleSort, + "ARTIST_SORT" => ArtistSort, + "ALBUM_SORT" => AlbumSort, + AlbumArtistSortName => AlbumArtistSort, + _ => ComposerSort, + }; + + void SetSortByName (string name, string? value) + { + switch (name) { + case "TITLE_SORT": + TitleSort = value; + break; + case "ARTIST_SORT": + ArtistSort = value; + break; + case "ALBUM_SORT": + AlbumSort = value; + break; + case AlbumArtistSortName: + AlbumArtistSort = value; + break; + default: + ComposerSort = value; + break; + } + } + /// /// /// Writes one SimpleTag per value at the item level, the level and @@ -457,6 +628,12 @@ public override IReadOnlyList GetCustomField (string name) /// most specific file-level target in the file, or 50 (album) when there is none, so on a file with /// only album tags "TITLE" writes the album title; still prefers the segment /// title there. + /// + /// A value name (ARTIST, TITLE, COMPOSER, ALBUM_ARTIST, ...) is written raw: no flat + /// sort moves with it, so a sort can be left beside a value it no longer sorts. Use the properties + /// (, , , ) to keep each + /// flat sort with its value. A flat sort name goes through its sort property (see ). + /// /// public override bool SetCustomField (string name, params string[] values) { @@ -464,6 +641,14 @@ public override bool SetCustomField (string name, params string[] values) if (!CustomFieldValues.IsUsableName (name) || !CustomFieldValues.TryNormalize (values, out var kept)) return false; + if (IsSortName (name)) { + // A sort is one name for its value. + if (kept.Count > 1) + return false; + SetSortByName (name, kept.Count == 0 ? null : kept[0]); + return true; + } + if (kept.Count == 0) { RemoveCustomField (name); return true; @@ -483,6 +668,11 @@ public override bool RemoveCustomField (string name) CustomFieldValues.ThrowIfNull (name); if (!CustomFieldValues.IsUsableName (name)) return false; + if (IsSortName (name)) { + var had = SortByName (name) is not null; + SetSortByName (name, null); + return had; + } var item = ItemLevel; var removed = false; @@ -514,7 +704,7 @@ internal BinaryData RenderWithout (HashSet? removedAttachments) foreach (var block in _blocks) { // A Tag contains at least one SimpleTag (RFC 9559 section 5.1.8.1.2). One that a clear emptied is // dropped. One that was already empty when read is kept, so a save leaves it as it was. - if (block.Tags.Count == 0 && !block.WasEmpty) + if (IsDropped (block)) continue; if (removedAttachments is { Count: > 0 } && block.TargetsAttachment (removedAttachments)) { var kept = block.RenderWithout (removedAttachments); @@ -529,6 +719,8 @@ internal BinaryData RenderWithout (HashSet? removedAttachments) return written == 0 ? BinaryData.Empty : EbmlWriter.Master (MatroskaIds.Tags, tags.ToBinaryData ().Span); } + static bool IsDropped (TagBlock block) => block.Tags.Count == 0 && !block.WasEmpty; + internal void SetSegmentTitle (string? title) => _segmentTitle = title; internal void AddBlock (TagBlock block) => _blocks.Add (block); @@ -537,7 +729,9 @@ internal ulong ItemLevel { get { ulong? level = null; foreach (var block in _blocks) { - if (!block.IsFileLevel) + t_levelSteps++; + // A Tag that a clear emptied is not rendered, so it is not the item either. + if (!block.IsFileLevel || IsDropped (block)) continue; if (level is null || block.Level < level) level = block.Level; @@ -563,6 +757,7 @@ internal ulong ItemLevel { bool HasFileLevelName (ulong level, string name) { foreach (var block in _blocks) { + t_levelSteps++; if (block.IsFileLevel && block.Level == level && block.HasName (name)) return true; } @@ -570,16 +765,8 @@ bool HasFileLevelName (ulong level, string name) return false; } - string? First (string name) - { - var values = Values (name); - for (var i = 0; i < values.Count; i++) { - if (values[i].Length > 0) - return values[i]; - } - - return null; - } + // A getter's value is the first of the list its setter's write-back check reads (All, AllAt). + string? First (string name) => FirstOf (All (name)); string[] All (string name) { @@ -603,16 +790,7 @@ string[] All (string name) return result; } - string? FirstAt (ulong level, string name) - { - var values = ValuesAt (level, name); - for (var i = 0; i < values.Count; i++) { - if (values[i].Length > 0) - return values[i]; - } - - return null; - } + string? FirstAt (ulong level, string name) => FirstOf (AllAt (level, name)); string[] AllAt (ulong level, string name) { @@ -651,6 +829,7 @@ List Values (string name) var item = ItemLevel; ulong? chosen = null; foreach (var block in _blocks) { + t_levelSteps++; if (!block.IsFileLevel || block.Level < item) continue; if (!block.HasName (name)) @@ -674,72 +853,323 @@ List Values (string name) void SetSort (string name, string flatName, string? value, ulong? level) { + // An empty sort is no sort, the way an empty parent value removes the parent. + if (string.IsNullOrEmpty (value)) + value = null; var replaced = level is ulong fixedLevel ? ReplaceNestedSortAt (fixedLevel, name, value) : ReplaceNestedSort (name, value); - if (value is null) { - if (level is ulong clearLevel) - RemoveAt (clearLevel, flatName); - else - RemoveFlatSort (flatName); - } else if (!replaced) { - if (level is ulong writeLevel) - SetAt (writeLevel, flatName, value); - else - SetItem (flatName, value); + // One sort per value: a nested sort that took the value, or a clear, leaves no flat copy of the old one + // for another reader to show; a flat set replaces the copy the getter reads and drops the rest of its run. + if (level is ulong fixedAt) { + // The flat sorts of the level's run: a set keeps one, in the value's Tag, and a clear none. + var flats = new HashSet (); + foreach (var holding in RunFrom (fixedAt, name, flatName)) { + if (holding.HasFlat && (value is null || replaced || holding.Level != fixedAt)) + flats.Add (holding.Level); + } + + RemoveAtLevels (flats, flatName); + if (value is not null && !replaced) + SetAt (fixedAt, flatName, value); + } else if (value is null || replaced) { + RemovePairedFlat (name, flatName); + } else { + var target = PairedFlatWriteLevel (name); + RemovePairedFlat (name, flatName, target); + SetAtValues (target, flatName, [value]); } } + [ThreadStatic] + static long t_levelSteps; + + /// + /// The Tags the sort pairing visits, counted per thread. Pairing a sort is linear in the Tags of the + /// file, so tests bound this count instead of a wall-clock time. + /// + internal static long LevelSteps { + get => t_levelSteps; + set => t_levelSteps = value; + } + + sealed class LevelHolding (ulong level) + { + public ulong Level { get; } = level; + public bool HasFlat { get; set; } + public List Values { get; } = []; + public List DefaultValues { get; } = []; + public bool HasValue => Values.Count > 0; + + // The values a getter reads at this level: the default-language ones when there are any. + public List Read => DefaultValues.Count > 0 ? DefaultValues : Values; + } + /// - /// A null sort removes the flat name at every file level the getter can still climb to. + /// One pass over the Tags: each level the getters climb (from the item up, skipping a Tag that is not + /// rendered), in order, with its values of and whether it holds . /// - void RemoveFlatSort (string flatName) + List LevelsHolding (string name, string flatName) { var item = ItemLevel; + var levels = new SortedDictionary (); foreach (var block in _blocks) { - if (block.IsFileLevel && block.Level >= item) - block.Remove (flatName); + t_levelSteps++; + if (!block.IsFileLevel || IsDropped (block) || block.Level < item) + continue; + if (!levels.TryGetValue (block.Level, out var holding)) + levels[block.Level] = holding = new LevelHolding (block.Level); + foreach (var tag in block.Tags) { + if (tag.Name == flatName) + holding.HasFlat = true; + if (tag.Name != name) + continue; + holding.Values.Add (tag.Text ?? string.Empty); + if (tag.IsDefault) + holding.DefaultValues.Add (tag.Text ?? string.Empty); + } } + + return [.. levels.Values]; } - bool ReplaceNestedSort (string name, string? value) + /// + /// The levels whose flat sort belongs to the the getter reads, item first: its run. + /// A flat sort sorts the value in its own Tag (the ffmpeg convention), and a Tag with no value of its own + /// passes its sort down to the value below it (tagging.html, "Target types": a tag applies to every + /// narrower target). A broader Tag that repeats the same value is the same value, which the spec allows + /// ("you can also repeat the value for each track"), so the run goes on through it. The run ends below + /// the first broader Tag whose value differs: that Tag's sort, and every one above it, is another value's. + /// + List PairedLevels (string name, string flatName) { - var chosen = ChosenLevel (name); - return chosen is not null && ReplaceNestedSortAt (chosen.Value, name, value); + var paired = new List (); + List? value = null; + foreach (var holding in LevelsHolding (name, flatName)) { + if (holding.HasValue) { + if (value is null) + value = holding.Read; + else if (!SameText (value, holding.Read)) + break; + } + + paired.Add (holding); + } + + return paired; + } + + static bool SameText (List a, List b) + { + if (a.Count != b.Count) + return false; + for (var i = 0; i < a.Count; i++) { + if (a[i] != b[i]) + return false; + } + + return true; + } + + /// The level of the flat sort that belongs to the the getter reads. + ulong? PairedFlatLevel (string name, string flatName) + { + foreach (var holding in PairedLevels (name, flatName)) { + if (holding.HasFlat) + return holding.Level; + } + + return null; } + string? PairedFlat (string name, string flatName) => + PairedFlatLevel (name, flatName) is ulong level ? FirstAt (level, flatName) : null; + /// - /// Rewrites SORT_WITH on the tag the getter reads. Returns false when that tag has none. + /// Removes the flat sort at every level can reach, and none that belongs to another value. /// - bool ReplaceNestedSortAt (ulong level, string name, string? value) + void RemovePairedFlat (string name, string flatName, ulong? keep = null) { - var preferDefault = false; + // A copy at the level about to be written is replaced in place there, so its position stays. + var levels = new HashSet (); + foreach (var holding in PairedLevels (name, flatName)) { + if (holding.HasFlat && holding.Level != keep) + levels.Add (holding.Level); + } + + RemoveAtLevels (levels, flatName); + } + + // One pass, so a clear over many levels stays linear in the Tags. + void RemoveAtLevels (HashSet levels, string name) + { + if (levels.Count == 0) + return; foreach (var block in _blocks) { - if (!block.IsFileLevel || block.Level != level) - continue; - if (block.HasDefault (name)) - preferDefault = true; + t_levelSteps++; + if (block.IsFileLevel && levels.Contains (block.Level)) + block.Remove (name); } + } + + /// + /// Where a new flat sort goes: in the Tag of the value it sorts, the ffmpeg pairing. A value above the album + /// (where ordinary fields are not written), or none, has its sort at the ordinary level, which is still in + /// its run. The caller removes the run's other copies first, so one copy is left for every reader. + /// + ulong PairedFlatWriteLevel (string name) => + ChosenLevel (name) is ulong parent && parent <= AlbumLevel ? parent : OrdinaryWriteLevel (); + + /// + /// Removes at every file level the getters can still climb to. + /// + void RemoveVisible (string name) + { + var item = ItemLevel; + foreach (var block in _blocks) { + if (block.IsFileLevel && block.Level >= item) + block.Remove (name); + } + } + + /// + /// The flat ALBUM_ARTIST names the album artist when any level the item can see has one. + /// + bool UsesAlbumArtistName => ChosenLevel (AlbumArtistName) is not null; + + /// + /// When the track has no ARTIST of its own, inherits the album's, + /// and both it and read the SORT_WITH of one SimpleTag. + /// Before a write that would change that shared sort, copy every ARTIST at the inherited + /// level to the track level, and to the album level when it came from above the album, so each + /// property keeps its own sort and every parent reads the same names as before. + /// + void SplitSharedArtist (string? value) + { + if (UsesAlbumArtistName || ChosenLevel ("ARTIST") is not ulong level) + return; + var shared = SortParentAt (level, "ARTIST"); + if (shared is null || !shared.Children.Exists (child => child.Name == "SORT_WITH")) + return; + if (ItemLevel < AlbumLevel && level != AlbumLevel) + return; + if (value is not null && value == NestedSortAt (level, "ARTIST")) + return; + + // Each copy repeats the same value, so the runs of ARTIST_SORT and ALBUM_ARTIST_SORT still reach the + // original's flat sorts: no flat sort is copied, and none is left as a second copy. + var artists = TagsNamedAt (level, "ARTIST"); + + CopyTags (artists, TrackLevel); + if (level > AlbumLevel) + CopyTags (artists, AlbumLevel); + } + List TagsNamedAt (ulong level, string name) + { + var found = new List (); foreach (var block in _blocks) { + t_levelSteps++; if (!block.IsFileLevel || block.Level != level) continue; foreach (var tag in block.Tags) { - if (tag.Name != name || (preferDefault && !tag.IsDefault) || string.IsNullOrEmpty (tag.Text)) + if (tag.Name == name) + found.Add (tag); + } + } + + return found; + } + + void CopyTags (List tags, ulong level) + { + var block = FileBlock (level); + foreach (var tag in tags) + block.Tags.Add (CopyTag (tag, tag.Text)); + } + + static string? NullIfEmpty (string? value) => string.IsNullOrEmpty (value) ? null : value; + + static List NonEmpty (string[]? values) + { + var kept = new List (); + if (values is not null) { + foreach (var value in values) { + if (!string.IsNullOrEmpty (value)) + kept.Add (value); + } + } + + return kept; + } + + // The non-empty values, in order, are what the getter already returns: writing them back changes nothing. + static bool SameValues (string[]? values, string[] current) + { + var at = 0; + if (values is not null) { + foreach (var value in values) { + if (string.IsNullOrEmpty (value)) continue; - if (!tag.Children.Exists (child => child.Name == "SORT_WITH")) + if (at >= current.Length || current[at] != value) return false; - tag.Children.RemoveAll (child => child.Name == "SORT_WITH"); - if (value is not null) - tag.Children.Add (new SimpleTag ("SORT_WITH", value)); - return true; + at++; } } + return at == current.Length; + } + + static bool HasText (string[]? values) + { + if (values is null) + return false; + foreach (var value in values) { + if (!string.IsNullOrEmpty (value)) + return true; + } + return false; } + bool ReplaceNestedSort (string name, string? value) + { + var chosen = ChosenLevel (name); + return chosen is not null && ReplaceNestedSortAt (chosen.Value, name, value); + } + + /// + /// Rewrites SORT_WITH on the tag the getter reads. Returns false when that tag has none. + /// + bool ReplaceNestedSortAt (ulong level, string name, string? value) + { + var tag = SortParentAt (level, name); + if (tag is null || !tag.Children.Exists (child => child.Name == "SORT_WITH")) + return false; + tag.Children.RemoveAll (child => child.Name == "SORT_WITH"); + if (value is not null) + tag.Children.Add (new SimpleTag ("SORT_WITH", value)); + return true; + } + string? NestedSortAt (ulong level, string name) + { + var tag = SortParentAt (level, name); + if (tag is null) + return null; + foreach (var child in tag.Children) { + if (child.Name == "SORT_WITH" && !string.IsNullOrEmpty (child.Text)) + return child.Text; + } + + return null; + } + + /// + /// The SimpleTag whose SORT_WITH the sort getters read: the first non-empty + /// at , preferring a default-language one. + /// + SimpleTag? SortParentAt (ulong level, string name) { var preferDefault = false; foreach (var block in _blocks) { @@ -753,14 +1183,8 @@ bool ReplaceNestedSortAt (ulong level, string name, string? value) if (!block.IsFileLevel || block.Level != level) continue; foreach (var tag in block.Tags) { - if (tag.Name != name || (preferDefault && !tag.IsDefault) || string.IsNullOrEmpty (tag.Text)) - continue; - foreach (var child in tag.Children) { - if (child.Name == "SORT_WITH" && !string.IsNullOrEmpty (child.Text)) - return child.Text; - } - - return null; + if (tag.Name == name && (!preferDefault || tag.IsDefault) && !string.IsNullOrEmpty (tag.Text)) + return tag; } } @@ -787,16 +1211,209 @@ List ValuesAt (ulong level, string name) return values; } - // A target broader than the album is not where ordinary fields are written. + // A target broader than the album is not where ordinary fields are written. A Tag that holds only ARTIST + // and its sort, such as the track copy that keeps ArtistSort apart from AlbumArtistSort or a track artist + // whose sort was just set, does not move new fields to its level: a sort write does not change where + // later fields land, and they reach the track by inheritance. ulong OrdinaryWriteLevel () { - var level = ItemLevel; - return level > AlbumLevel ? AlbumLevel : level; + ulong? level = null; + foreach (var block in _blocks) { + if (!block.IsFileLevel || IsDropped (block) || IsArtistOnly (block)) + continue; + if (level is null || block.Level < level) + level = block.Level; + } + + var found = level ?? ItemLevel; + return found > AlbumLevel ? AlbumLevel : found; + } + + static bool IsArtistOnly (TagBlock block) => + block.Tags.Count > 0 && block.Tags.TrueForAll (tag => tag.Name is "ARTIST" or "ARTIST_SORT"); + + /// + /// Writes an item field where its getter reads it. A value inherited from a broader target + /// (tagging.html, "Target types") is replaced in place, so a set is not hidden behind a copy at the + /// item level and readers that look only at the broader target see it too. A clear removes the name at + /// every level the getter climbs to, so no inherited value shows through. + /// + void SetItem (string name, string? value) + { + // Writing back the value read changes nothing. A clear always runs, so nothing a broader level + // holds is left for another reader to show. + if (IsWriteBackAt (value, All (name), null, name)) + return; + if (string.IsNullOrEmpty (value)) { + RemoveVisible (name); + return; + } + + SetAtValues (ItemWriteLevel (name), name, [value!]); + } + + void SetItemValues (string name, string[]? values) + { + if (IsListWriteBack (values, All (name), AnyText (name), clearsOneLevel: false)) + return; + if (!HasText (values)) { + RemoveVisible (name); + return; + } + + SetAtValues (ItemWriteLevel (name), name, values); + } + + void SetItemReplacingLegacy (string name, string legacy, string? value, string? current) => + SetItemWithFallback (name, legacy, value, current, replaceFallback: true); + + /// + /// A field read from , else from . Writing back the value + /// read changes nothing, in a copy too, as the fallback is its own field; a copy still drops the other + /// values of (Tag.IsWriteBack, the Vorbis rule). A clear removes both names, so the + /// getter reads null. A set writes ; an older copy of the same value under + /// goes when , so no reader shows the old one. + /// "" counts as the value read only when no value of either name holds text (#136), so a clear has nothing to remove. + /// + void SetItemWithFallback (string name, string fallback, string? value, string? current, bool replaceFallback) + { + if (IsValueRead (value, current) || (value is { Length: 0 } && !AnyText (name) && !AnyText (fallback))) { + if (IsCopying && !string.IsNullOrEmpty (value) && All (name).Length > 1 && First (name) == value) + SetAtValues (ItemWriteLevel (name), name, [value!]); + return; + } + + if (string.IsNullOrEmpty (value) || replaceFallback) + RemoveVisible (fallback); + SetItem (name, value); + } + + /// + /// The write-back rule of (#136): handed exactly the value + /// its getter read, a setter changes nothing. A copy replaces the target's list, so while + /// runs a value is unchanged only when the target already holds exactly that one + /// value. is the list the getter reads, whose first value it returns, so the check + /// cannot read anything the getter does not. "" is the value read only when no value of the name holds text + /// where the setter clears (, or every visible level), as #136 has it, so the clear + /// would remove nothing. A null over a field that reads null is a no-op for a setter that writes one level, + /// whose clear could only uncover a broader value; otherwise null clears every level the getter climbs. + /// + bool IsWriteBackAt (string? value, string[] held, ulong? level, string name) + { + var current = FirstOf (held); + if (value is null) + return current is null && level is not null; + if (value.Length == 0) + return current is null && !(level is ulong at ? AnyTextAt (at, name) : AnyText (name)); + if (!IsValueRead (value, current)) + return false; + return !IsCopying || (held.Length == 1 && held[0] == value); + } + + /// + /// A sort handed the value its getter read changes nothing (Tag.IsWriteBack), in a copy too, unless the flat + /// sort read sits beside other texts at its level, which a copy replaces so the target holds one sort. A + /// nested sort read is the value's own, and a flat sort elsewhere in its run is another field (as a Vorbis + /// fallback field is), so a copy of a nested sort leaves the file as it is: a sort the item inherits stays + /// where it is and its value is not split. + /// + bool IsSortWriteBack (string? value, string name, string flatName, ulong? level) + { + var (nested, flatLevel) = SortSource (name, flatName, level); + var current = nested ?? (flatLevel is ulong read ? FirstAt (read, flatName) : null); + // A sort never reads "", so "" is never the value read and always clears. + if (!IsValueRead (value, current)) + return false; + if (!IsCopying || nested is not null) + return true; + foreach (var held in AllAt (flatLevel!.Value, flatName)) { + if (held != value) + return false; + } + + return true; + } + + /// + /// Where a sort is read: the SORT_WITH nested in the value the getter reads, and the level of the flat + /// sort that belongs to it. A sort of a value the getter reads at one level (: the track + /// title, the album title, the album-level ARTIST) belongs to that level's run, the level and each + /// broader one up to a different value (), so a value-less broader sort passes down to it + /// as every other sort does. Any other sort belongs to the run of the value the item reads (). + /// + (string? Nested, ulong? FlatLevel) SortSource (string name, string flatName, ulong? level) + { + if (level is not ulong at) + return (NestedSort (name), PairedFlatLevel (name, flatName)); + foreach (var holding in RunFrom (at, name, flatName)) { + if (holding.HasFlat) + return (NestedSortAt (at, name), holding.Level); + } + + return (NestedSortAt (at, name), null); + } + + string? ReadSort (string name, string flatName, ulong? level) + { + var (nested, flatLevel) = SortSource (name, flatName, level); + return nested ?? (flatLevel is ulong read ? FirstAt (read, flatName) : null); } - void SetItem (string name, string? value) => SetAt (OrdinaryWriteLevel (), name, value); + string AlbumArtistValueName => UsesAlbumArtistName ? AlbumArtistName : "ARTIST"; + + // The album artist is the album-level ARTIST once the file has a track level (AlbumArtists reads level 50 + // then), so its sort belongs to that level's run; otherwise it is the value the item reads. + ulong? AlbumArtistSortLevel => UsesAlbumArtistName || ItemLevel >= AlbumLevel ? null : AlbumLevel; + + /// + /// The list form: the values read, in order, are a no-op, in a copy too, as the target then holds exactly + /// that list. An empty list is the value read only when no value holds text where the setter clears; null + /// over an empty list is a no-op only for a one-level setter (). + /// + static bool IsListWriteBack (string[]? values, string[] current, bool anyText, bool clearsOneLevel) + { + if (values is null) + return clearsOneLevel && current.Length == 0; + if (!HasText (values)) + return current.Length == 0 && !anyText; + return SameValues (values, current); + } + + // Whether any visible file-level value of the name holds text. + bool AnyText (string name) + { + var item = ItemLevel; + foreach (var block in _blocks) { + t_levelSteps++; + if (!block.IsFileLevel || block.Level < item) + continue; + foreach (var tag in block.Tags) { + if (tag.Name == name && !string.IsNullOrEmpty (tag.Text)) + return true; + } + } + + return false; + } + + bool AnyTextAt (ulong level, string name) + { + foreach (var block in _blocks) { + t_levelSteps++; + if (!block.IsFileLevel || block.Level != level) + continue; + foreach (var tag in block.Tags) { + if (tag.Name == name && !string.IsNullOrEmpty (tag.Text)) + return true; + } + } + + return false; + } - void SetItemValues (string name, string[]? values) => SetAtValues (OrdinaryWriteLevel (), name, values); + // The level the getter reads, unless that is broader than the album, where ordinary fields are not written. + ulong ItemWriteLevel (string name) => + ChosenLevel (name) is ulong level && level <= AlbumLevel ? level : OrdinaryWriteLevel (); string? TrackPartNumber () { @@ -1072,6 +1689,128 @@ static void ReplaceOrAdd (TagBlock block, string name, string value) return null; } + void SetValue (ulong level, string name, string? value, string[] inherited, string[] owned, bool shadows) => + SetValues (level, name, string.IsNullOrEmpty (value) ? null : [value!], inherited, owned, shadows); + + /// + /// Writes a value at one level and keeps each flat sort with the value it sorts (tagging.html, "Target + /// types"; the ffmpeg convention keeps a value and its flat sort in one Tag). A new value in a Tag whose + /// flat sort a narrower value reads moves that sort to the narrower value. A + /// value removed from a Tag takes that Tag's flat sorts with it. When the getters + /// climb through this level (), a value equal to the broader one it now shadows is + /// a repeat of it and copies its SimpleTags, nested SORT_WITH included, so the narrower levels that + /// read the broader value keep reading the same sort. + /// + void SetValues (ulong level, string name, string[]? values, string[] inherited, string[] owned, bool shadows) + { + var had = HasFileLevelName (level, name); + // The narrower value and the sorts of its run that sit in this Tag or above: the write must not take them. + var narrower = ChosenLevel (name) is ulong n && n < level ? n : (ulong?)null; + var kept = new List<(string Flat, ulong At)> (); + if (narrower is not null) { + foreach (var flat in inherited) { + if (PairedFlatLevel (name, flat) is ulong at && at >= level) + kept.Add ((flat, at)); + } + } + + // A value that leaves this Tag takes the flat sorts of its run with it: its own Tag's, and a broader + // value-less Tag's that passed down to it, which would otherwise pass on to another value. + var run = new List<(string Flat, ulong At)> (); + if (had && !HasText (values)) { + foreach (var flat in owned) { + foreach (var at in OwnSortLevels (level, name, flat)) + run.Add ((flat, at)); + } + } + + if (!HasText (values)) + RemoveAt (level, name); + else if (shadows && !had && ShadowedLevel (level, name, values!) is ulong shadowed) + CopyTags (TagsNamedAt (shadowed, name), level); + else + SetAtValues (level, name, values); + if (had && !HasFileLevelName (level, name)) { + foreach (var flat in owned) { + var levels = new HashSet (); + foreach (var (runFlat, at) in run) { + if (runFlat == flat && !kept.Contains ((flat, at))) + levels.Add (at); + } + + RemoveAtLevels (levels, flat); + } + } + + // A value placed between the narrower value and its sort, or a repeat of it renamed here, would leave + // the sort with another value; it moves down to the value it sorts. + foreach (var (flat, at) in kept) { + if (PairedFlatLevel (name, flat) != at) + MoveTags (at, narrower!.Value, flat); + } + } + + /// + /// The levels whose flat sorts belong to the value at alone: its own Tag, and each + /// value-less broader Tag up to the next one that holds a value. A broader Tag that repeats the same value + /// keeps its own sort, which the narrower levels read once this value goes (tagging.html, "Target types": a + /// tag applies to every narrower target). + /// + List OwnSortLevels (ulong level, string name, string flatName) + { + var own = new List (); + foreach (var holding in LevelsHolding (name, flatName)) { + if (holding.Level < level) + continue; + if (holding.Level > level && holding.HasValue) + break; + own.Add (holding.Level); + } + + return own; + } + + // The nearest broader level with a value of the name, when that value is the same list of texts as values. + ulong? ShadowedLevel (ulong level, string name, string[] values) + { + var written = NonEmpty (values); + foreach (var holding in LevelsHolding (name, name)) { + if (holding.Level <= level || !holding.HasValue) + continue; + return SameText (NonEmpty ([.. holding.Read]), written) ? holding.Level : null; + } + + return null; + } + + /// The levels of the run that starts at : it, and each broader level up to a different value. + List RunFrom (ulong level, string name, string flatName) + { + var run = new List (); + List? value = null; + foreach (var holding in LevelsHolding (name, flatName)) { + if (holding.Level < level) + continue; + if (holding.Level == level) + value = holding.Read; + else if (holding.HasValue && (value is null || !SameText (value, holding.Read))) + break; + run.Add (holding); + } + + return run; + } + + void MoveTags (ulong from, ulong to, string name) + { + // Only the sort the narrower value read moves, so the narrower level holds none of its own. + var moving = TagsNamedAt (from, name); + RemoveAt (from, name); + var home = FileBlock (to); + foreach (var tag in moving) + home.Tags.Add (tag); + } + void SetAt (ulong level, string name, string? value) { if (string.IsNullOrEmpty (value)) { @@ -1136,7 +1875,7 @@ void SetAtValues (ulong level, string name, string[]? values) } } - static SimpleTag CopyTag (SimpleTag previous, string text) + static SimpleTag CopyTag (SimpleTag previous, string? text) { var tag = new SimpleTag (previous.Name, text, previous.IsDefault) { Language = previous.Language, @@ -1178,6 +1917,7 @@ void RemoveTags (List tags) void RemoveAt (ulong level, string name) { foreach (var block in _blocks) { + t_levelSteps++; if (block.IsFileLevel && block.Level == level) block.Remove (name); } diff --git a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs index c7c306aa..ea94a571 100644 --- a/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs +++ b/tests/TagLibSharp2.Tests/Core/TagCopyReplacesListTests.cs @@ -7,6 +7,7 @@ using TagLibSharp2.Asf; using TagLibSharp2.Core; using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Matroska; using TagLibSharp2.Mpeg; using TagLibSharp2.Tests.Asf; using TagLibSharp2.Xiph; @@ -89,6 +90,23 @@ static IEnumerable StringProperties () => var tag = AsfFile.Read ([.. file, .. AsfTestBuilder.CreateDataObject (0)]).File!.Tag; return tag.GetCustomField (name).Contains (Stale) ? tag : null; } + case "matroska": + case "matroska-segment": { + var probe = new MatroskaTag (); + property.SetValue (probe, "V1"); + if (OnlySimpleTag (probe) is not var (level, name) || !Equals (property.GetValue (probe), "V1")) + return null; + var block = new TagBlock (level); + block.Tags.Add (new SimpleTag (name, "V1")); + block.Tags.Add (new SimpleTag (name, Stale)); + var tag = new MatroskaTag (); + tag.AddBlock (block); + // A segment title equal to the first value: Title reads the track's TITLE first, so the copy + // must still see the second one. + if (format == "matroska-segment") + tag.SetSegmentTitle ("V1"); + return Equals (property.GetValue (tag), "V1") ? tag : null; + } default: throw new ArgumentOutOfRangeException (nameof (format)); } @@ -96,6 +114,41 @@ static IEnumerable StringProperties () => static readonly string[] AsfContentDescriptionNames = ["Title", "Author", "Copyright", "Description", "Rating"]; + /// + /// The TargetTypeValue and TagName of the one SimpleTag a Matroska tag renders, or null when it renders + /// none or more than one (RFC 9559 section 5.1.8: Tags, Tag, Targets, SimpleTag). + /// + static (ulong Level, string Name)? OnlySimpleTag (MatroskaTag tag) + { + var bytes = tag.Render ().ToArray (); + if (bytes.Length == 0 || !EbmlReader.TryRead (bytes, 0, bytes.Length, out var tags)) + return null; + (ulong, string)? found = null; + var body = bytes.AsSpan (tags.DataOffset, (int)tags.DataLength); + for (var at = 0; at < body.Length && EbmlReader.TryRead (body, at, body.Length, out var element); at = element.End) { + var inner = body.Slice (element.DataOffset, (int)element.DataLength); + ulong level = 50; + for (var i = 0; i < inner.Length && EbmlReader.TryRead (inner, i, inner.Length, out var child); i = child.End) { + var payload = inner.Slice (child.DataOffset, (int)child.DataLength); + if (child.Id == MatroskaIds.Targets) { + for (var t = 0; t < payload.Length && EbmlReader.TryRead (payload, t, payload.Length, out var target); t = target.End) { + if (target.Id == MatroskaIds.TargetTypeValue) + level = payload[target.DataOffset..target.End].ToArray ().Aggregate (0UL, (v, b) => (v << 8) | b); + } + } else if (child.Id == MatroskaIds.SimpleTag) { + if (found is not null) + return null; + for (var n = 0; n < payload.Length && EbmlReader.TryRead (payload, n, payload.Length, out var field); n = field.End) { + if (field.Id == MatroskaIds.TagName) + found = (level, Encoding.UTF8.GetString (payload[field.DataOffset..field.End])); + } + } + } + } + + return found; + } + static string ApeKey (ApeTag tag) { // One item: value size (4, LE), flags (4), key (ASCII, NUL-terminated), value. @@ -141,6 +194,8 @@ static bool RenderHolds (Tag tag, string text) [DataRow ("ape")] [DataRow ("vorbis")] [DataRow ("asf")] + [DataRow ("matroska")] + [DataRow ("matroska-segment")] public void CopyAll_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) { var covered = new List (); @@ -174,6 +229,8 @@ public void CopyAll_SourceEqualsTargetFirstValue_ReplacesTheList (string targetF [DataRow ("ape")] [DataRow ("vorbis")] [DataRow ("asf")] + [DataRow ("matroska")] + [DataRow ("matroska-segment")] public void CopyBasic_SourceEqualsTargetFirstValue_ReplacesTheList (string targetFormat) { var failures = new List (); diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs index 3cf4533d..93ab6658 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaAttachmentTests.cs @@ -1252,4 +1252,36 @@ sealed class TestPicture (string mimeType, PictureType pictureType, string descr public BinaryData PictureData { get; } = new (data); } + + [TestMethod] + public void SortWrites_LeaveTheTagsOfOtherItemsAsRead () + { + // A Tag that targets an attachment and a track belongs to that item (RFC 9559 section 5.1.8.1.1), even at a + // level the file's sorts climb through. A sort clear and the split it makes leave it alone, in memory too: + // removing the attachment later renders that Tag from memory, without the attachment's UID. + var atTrack = Master (0x7373, Concat ( + Master (0x63C0, Concat (Element (0x68CA, new byte[] { 30 }), Element (0x63C6, new byte[] { 5 }), Element (0x63C5, new byte[] { 1 }))), + Simple ("ARTIST", "Shared"), Simple ("ARTIST_SORT", "shared sort"))); + var atAlbum = Master (0x7373, Concat ( + Master (0x63C0, Concat (Element (0x68CA, new byte[] { 50 }), Element (0x63C6, new byte[] { 5 }), Element (0x63C9, new byte[] { 1 }))), + Simple ("ARTIST", "Other"))); + var original = Movie ( + Tags (Tag (50, SimpleSorted ("ARTIST", "Band", "band")), Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST_SORT", "solo")), atTrack, atAlbum), + Attachments (CoverPng (5)), + Master (MatroskaIds.Cluster, new byte[] { 1 })); + var file = MatroskaFile.Read (original).File!; + Assert.AreEqual ("band", file.Tag.ArtistSort); + + file.Tag.ArtistSort = null; + file.Tag.Pictures = []; + + var bytes = Save (file, original); + var again = MatroskaFile.Read (bytes).File!.Tag; + Assert.IsNull (again.ArtistSort); + Assert.AreEqual ("band", again.AlbumArtistSort); + Assert.AreEqual ("Band", string.Join ("|", again.Performers)); + Assert.AreEqual (1, CountOf (bytes, "shared sort"u8.ToArray ())); + Assert.AreEqual (1, CountOf (bytes, "Other"u8.ToArray ())); + Assert.AreEqual (0, CountOf (bytes, "solo"u8.ToArray ())); + } } diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaCopyReplacesTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaCopyReplacesTests.cs new file mode 100644 index 00000000..589c74f5 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaCopyReplacesTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Matroska; + +// Tag.IsWriteBack (#136): writing back the value read changes nothing, but a CopyTo makes the target hold exactly +// the source's value, so a copy equal to the target's first value still replaces the target's other values. +public partial class MatroskaFileTests +{ + [TestMethod] + public void CopyTo_ValueEqualToTheFirst_ReplacesTheList () + { + var tag = MatroskaFile.Read (FileWith (Tags (Tag (50, + Simple ("ISRC", "A"), Simple ("ISRC", "B"), + Simple ("CATALOG_NUMBER", "C1"), Simple ("CATALOG_NUMBER", "C2"), + Simple ("BPM", "120"), Simple ("BPM", "130"), + Simple ("PUBLISHER", "P1"), Simple ("PUBLISHER", "P2"), Simple ("LABEL", "L"))))).File!.Tag; + + new VorbisComment { Isrc = "A", CatalogNumber = "C1", BeatsPerMinute = 120, Publisher = "P1" }.CopyTo (tag); + + var again = MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag; + var bytes = tag.Render ().ToArray (); + Assert.AreEqual ("A", again.Isrc); + Assert.AreEqual (1, CountOf (bytes, "ISRC"u8.ToArray ())); + Assert.AreEqual (1, CountOf (bytes, "CATALOG_NUMBER"u8.ToArray ())); + Assert.AreEqual (0, CountOf (bytes, "130"u8.ToArray ())); + Assert.AreEqual (0, CountOf (bytes, "P2"u8.ToArray ())); + Assert.AreEqual (1, CountOf (bytes, "LABEL"u8.ToArray ()), "the fallback name is its own field"); + } + + [TestMethod] + public void CopyBasic_ArtistEqualToTheFirst_ReplacesThePerformers () + { + var tag = MatroskaFile.Read (FileWith (Tags (Tag (30, Simple ("ARTIST", "Ada"), Simple ("ARTIST", "Bob"))))).File!.Tag; + + new VorbisComment { Artist = "Ada" }.CopyTo (tag, TagCopyOptions.Basic); + + Assert.AreEqual ("Ada", string.Join ("|", tag.Performers)); + } + + [TestMethod] + public void CopyTo_ValuesTheTargetHoldsAsTheOnlyOnes_ChangesNoBytes () + { + // The title read from the album, a nested sort read, and a list held as read: nothing to replace. + var original = FileWith (Tags ( + Tag (50, Simple ("TITLE", "Alb"), SimpleSorted ("ARTIST", "Band", "band"), Simple ("ARTIST_SORT", "stray")), + Tag (30, Simple ("GENRE", "Rock")))); + var tag = MatroskaFile.Read (original).File!.Tag; + var before = tag.Render ().ToArray (); + Assert.AreEqual ("Alb", tag.Title); + + new VorbisComment { Title = "Alb", ArtistSort = "band", Genres = ["Rock"] }.CopyTo (tag); + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + + // One value held at the collection level, and a BPM stored as "120.0": a copy finds each held as it is. + var collection = MatroskaFile.Read (FileWith (Tags (Tag (70, Simple ("PUBLISHER", "P"), Simple ("BPM", "120.0")), Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + var held = collection.Render ().ToArray (); + new VorbisComment { Publisher = "P", BeatsPerMinute = 120 }.CopyTo (collection); + CollectionAssert.AreEqual (held, collection.Render ().ToArray ()); + } + + [TestMethod] + public void EmptyWrite_OverAFieldThatHoldsNoText_ChangesNoBytes () + { + // "" is the value read only when no value of the name holds text (#136). + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ALBUM_ARTIST", ""), Simple ("ALBUM_ARTIST_SORT", "x"), Simple ("ARTIST", "Band")), + Tag (30, Simple ("TITLE", "Song"))))).File!.Tag; + var before = tag.Render ().ToArray (); + + tag.AlbumArtists = tag.AlbumArtists; + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + Assert.AreEqual ("x", tag.AlbumArtistSort); + } + + [TestMethod] + public void CopyTo_TitleEqualToTheSegmentTitle_ReplacesTheTrackTitles () + { + // Title reads the track's TITLE before the segment title (RFC 9559 section 5.1.2.12 names the segment). + var tag = MatroskaFile.Read (FileWith ( + Master (0x1549A966, Element (0x7BA9, "A"u8)), + Tags (Tag (30, Simple ("TITLE", "A"), Simple ("TITLE", "Zq2"))))).File!.Tag; + Assert.AreEqual ("A", tag.Title); + + new VorbisComment { Title = "A" }.CopyTo (tag, TagCopyOptions.Basic); + + Assert.AreEqual (0, CountOf (tag.Render ().ToArray (), "Zq2"u8.ToArray ())); + } + + [TestMethod] + public void EmptyWrite_OfTheComposersRead_KeepsTheirSort () + { + // An empty COMPOSER reads as no composers and holds no text; writing that back is the value read, so its sort + // stays (#136). The same holds for "" over a field that holds no text. A chapter's composer is not the file's. + foreach (var data in new[] { + FileWith (Tags (Tag (50, Simple ("COMPOSER", ""), Simple ("COMPOSER_SORT", "x"), Simple ("GENRE", "")), Tag (30, Simple ("TITLE", ""), Simple ("GENRE", "")), + ChapterTag (30, Chapter (2), Simple ("TITLE", "Chapter")))), + FileWith (Tags (Tag (50, Simple ("COMPOSER", ""), Simple ("COMPOSER_SORT", "x")))), + FileWith (Tags (Tag (50, Simple ("COMPOSER", ""), Simple ("COMPOSER_SORT", "x")), ChapterTag (50, Chapter (1), Simple ("COMPOSER", "Ch")))) }) { + var tag = MatroskaFile.Read (data).File!.Tag; + var before = tag.Render ().ToArray (); + + tag.Composers = tag.Composers; + tag.Genres = tag.Genres; + if (tag.Genre is null) + tag.Genre = ""; + if (tag.Title is null) + tag.Title = ""; + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + Assert.AreEqual ("x", tag.ComposerSort); + } + } + + [TestMethod] + public void EmptyWrite_OverAnEmptyValueWithTextBehindIt_Clears () + { + // An empty PUBLISHER at 30 reads as none, but the album's still holds text, so "" is a clear (#136). + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("PUBLISHER", "P"), Simple ("GENRE", "Rock"), Simple ("REPLAYGAIN_GAIN", "-3 dB")), + Tag (30, Simple ("TITLE", "S"), Simple ("PUBLISHER", ""), Simple ("GENRE", ""), Simple ("REPLAYGAIN_GAIN", ""))))).File!.Tag; + Assert.IsNull (tag.Publisher); + + tag.Publisher = ""; + tag.Genre = ""; + tag.ReplayGainTrackGain = ""; + + var bytes = tag.Render ().ToArray (); + Assert.AreEqual (0, CountOf (bytes, "PUBLISHER"u8.ToArray ())); + Assert.AreEqual (0, CountOf (bytes, "Rock"u8.ToArray ())); + Assert.AreEqual (0, CountOf (bytes, "REPLAYGAIN_GAIN"u8.ToArray ()), "the older name holds text behind its empty one"); + + // The fallback name alone holds the hidden text. + var label = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("LABEL", "L")), Tag (30, Simple ("TITLE", "S"), Simple ("LABEL", ""))))).File!.Tag; + Assert.IsNull (label.Publisher); + label.Publisher = ""; + Assert.AreEqual (0, CountOf (label.Render ().ToArray (), "LABEL"u8.ToArray ())); + + // A one-level setter clears its level when that level holds an empty value, even while a narrower one reads text. + var artist = MatroskaFile.Read (FileWith (Tags (Tag (30, Simple ("ARTIST", ""), Simple ("ARTIST_SORT", "s"), Simple ("TITLE", "S")), Tag (20, Simple ("ARTIST", "X"))))).File!.Tag; + Assert.AreEqual ("X", artist.Artist); + artist.Artist = ""; + Assert.AreEqual (0, CountOf (artist.Render ().ToArray (), "ARTIST_SORT"u8.ToArray ())); + } + + [TestMethod] + public void EmptyWrite_OverAFieldWithAFallback_ClearsBothNames () + { + var tag = MatroskaFile.Read (FileWith (Tags (Tag (50, + Simple ("PUBLISHER", "P"), Simple ("LABEL", "L"), + Simple ("REPLAYGAIN_TRACK_GAIN", "-1 dB"), Simple ("REPLAYGAIN_GAIN", "-2 dB"), + Simple ("GENRE", "Rock"))))).File!.Tag; + + tag.Publisher = ""; + tag.ReplayGainTrackGain = ""; + tag.Genre = ""; + + var again = MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag; + Assert.IsNull (again.Publisher); + Assert.IsNull (again.ReplayGainTrackGain); + Assert.IsNull (again.Genre); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs index 42ac4502..b8f4eefd 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs @@ -236,4 +236,28 @@ static void WriteWideSize (byte[] buffer, int at, ulong size) size >>= 8; } } + + [TestMethod] + public void SortWrites_ThatCopyAnArtist_KeepItsSimpleTagsPastTheParseDepth () + { + // The split and an equal shadow copy a whole ARTIST SimpleTag. Its children nested past the parse depth are + // kept as stored (#151), so each copy carries them, and the original keeps its own. + var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8)); + var chain = Nested (0x67C8, MatroskaFile.MaxSimpleTagDepth + 5, Element (0x45A3, "N"u8), leaf); + byte[] Artist (string text, string sort) => Master (0x67C8, Concat ( + Element (0x45A3, "ARTIST"u8), Element (0x4487, System.Text.Encoding.UTF8.GetBytes (text)), + Master (0x67C8, Concat (Element (0x45A3, "SORT_WITH"u8), Element (0x4487, System.Text.Encoding.UTF8.GetBytes (sort)))), chain)); + + var single = MatroskaFile.Read (FileWith (Tags (Tag (50, Artist ("Band", "band"))))).File!; + single.Tag.ArtistSort = "new"; + var split = single.Tag.Render ().ToArray (); + Assert.AreEqual (2, Occurrences (split, KeptSlice (chain)), "the split's track copy carries the kept children"); + Assert.AreEqual ("band", MatroskaFile.Read (FileWith (split)).File!.Tag.AlbumArtistSort); + + var shadow = MatroskaFile.Read (FileWith (Tags (Tag (70, Artist ("Coll", "coll")), Tag (30, Simple ("TITLE", "Song"))))).File!; + shadow.Tag.AlbumArtists = ["Coll"]; + var copied = shadow.Tag.Render ().ToArray (); + Assert.AreEqual (2, Occurrences (copied, KeptSlice (chain)), "the album's repeat carries the kept children"); + Assert.AreEqual ("coll", MatroskaFile.Read (FileWith (copied)).File!.Tag.ArtistSort); + } } diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaIntegrationTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaIntegrationTests.cs index 70eaf693..16b6339d 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaIntegrationTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaIntegrationTests.cs @@ -15,6 +15,8 @@ namespace TagLibSharp2.Tests.Matroska; /// These tests are skipped by default. To run them: /// 1. Set the TAGLIBSHARP2_TEST_MATROSKA environment variable to a path to a .mkv, .mka, or .webm file /// 2. Run with: dotnet test --filter "TestCategory=Integration" +/// The sort-name tests copy the file to a temporary path; the original is never written. +/// The same sort-name checks run in CI on built files from . /// [TestClass] [TestCategory ("Integration")] @@ -88,6 +90,14 @@ public void Save_RealMatroska_ToggledTrack_RoundTripsAndKeepsClusters () Assert.AreEqual (toggled.Length, restored.Length, "a stored flag is rewritten in place"); } + [TestMethod] + public void SortNames_RoundTripThroughSave_AndClear () => + MatroskaSortRoundTrip.VerifyOnCopy (SkipIfNoTestFile (TestFileEnvVar, "Matroska")); + + [TestMethod] + public Task SortNames_RoundTripThroughSaveAsync_AndClear () => + MatroskaSortRoundTrip.VerifyOnCopyAsync (SkipIfNoTestFile (TestFileEnvVar, "Matroska")); + /// The ID of every Seek, in every SeekHead, whose position names an element with that ID. static List LandingSeeks (byte[] file) { @@ -634,3 +644,127 @@ sealed class BackPicture : IPicture public BinaryData PictureData { get; } = new (BackCover); } } + +/// +/// Sets, saves, re-reads, clears, and re-reads AlbumArtistSort and ComposerSort +/// on a temporary copy of a Matroska file, checking the parent values never change. +/// +static class MatroskaSortRoundTrip +{ + public const string AlbumArtistSort = "Band, The"; + public const string ComposerSort = "Bach, Johann Sebastian"; + + // A later write to an unrelated field must still land where its getter reads it. + public const string Genre = "Round Trip Genre"; + + /// The file to copy. It is never written. + /// Inspects the saved bytes after the sort names are set. + public static void VerifyOnCopy (string source, Action? afterSet = null) + { + var copy = CopyToTemp (source); + try { + var original = MatroskaFile.ReadFromFile (copy); + Assert.IsTrue (original.IsSuccess, original.Error); + var before = Snapshot.Of (original.File!.Tag); + + original.File.Tag.AlbumArtistSort = AlbumArtistSort; + original.File.Tag.ComposerSort = ComposerSort; + original.File.Tag.Genre = Genre; + var saved = original.File.SaveToFile (); + Assert.IsTrue (saved.IsSuccess, saved.Error); + + var bytes = File.ReadAllBytes (copy); + afterSet?.Invoke (bytes); + var set = MatroskaFile.Read (bytes); + Assert.IsTrue (set.IsSuccess, set.Error); + AssertSet (set.File!.Tag, before); + + var reopened = MatroskaFile.ReadFromFile (copy); + Assert.IsTrue (reopened.IsSuccess, reopened.Error); + reopened.File!.Tag.AlbumArtistSort = null; + reopened.File.Tag.ComposerSort = null; + reopened.File.Tag.Genre = null; + var clearedSave = reopened.File.SaveToFile (); + Assert.IsTrue (clearedSave.IsSuccess, clearedSave.Error); + + var cleared = MatroskaFile.ReadFromFile (copy); + Assert.IsTrue (cleared.IsSuccess, cleared.Error); + AssertCleared (cleared.File!.Tag, before); + } finally { + File.Delete (copy); + } + } + + /// The file to copy. It is never written. + /// Inspects the saved bytes after the sort names are set. + public static async Task VerifyOnCopyAsync (string source, Action? afterSet = null) + { + var copy = CopyToTemp (source); + try { + var original = await MatroskaFile.ReadFromFileAsync (copy); + Assert.IsTrue (original.IsSuccess, original.Error); + var before = Snapshot.Of (original.File!.Tag); + + original.File.Tag.AlbumArtistSort = AlbumArtistSort; + original.File.Tag.ComposerSort = ComposerSort; + original.File.Tag.Genre = Genre; + var saved = await original.File.SaveToFileAsync (); + Assert.IsTrue (saved.IsSuccess, saved.Error); + + var set = await MatroskaFile.ReadFromFileAsync (copy); + Assert.IsTrue (set.IsSuccess, set.Error); + afterSet?.Invoke (File.ReadAllBytes (copy)); + AssertSet (set.File!.Tag, before); + + set.File.Tag.AlbumArtistSort = null; + set.File.Tag.ComposerSort = null; + set.File.Tag.Genre = null; + var clearedSave = await set.File.SaveToFileAsync (); + Assert.IsTrue (clearedSave.IsSuccess, clearedSave.Error); + + var cleared = await MatroskaFile.ReadFromFileAsync (copy); + Assert.IsTrue (cleared.IsSuccess, cleared.Error); + AssertCleared (cleared.File!.Tag, before); + } finally { + File.Delete (copy); + } + } + + static string CopyToTemp (string source) + { + var copy = Path.Combine (Path.GetTempPath (), $"taglibsharp2-sort-{Guid.NewGuid ():N}{Path.GetExtension (source)}"); + File.Copy (source, copy); + return copy; + } + + static void AssertSet (MatroskaTag tag, Snapshot before) + { + Assert.AreEqual (AlbumArtistSort, tag.AlbumArtistSort); + Assert.AreEqual (ComposerSort, tag.ComposerSort); + Assert.AreEqual (Genre, tag.Genre); + before.AssertParentsUnchanged (tag); + } + + static void AssertCleared (MatroskaTag tag, Snapshot before) + { + Assert.IsNull (tag.AlbumArtistSort); + Assert.IsNull (tag.ComposerSort); + Assert.IsNull (tag.Genre); + before.AssertParentsUnchanged (tag); + } + + sealed record Snapshot (string? Title, string? Artist, string? ArtistSort, string[] AlbumArtists, string[] Composers) + { + public static Snapshot Of (MatroskaTag tag) => + new (tag.Title, tag.Artist, tag.ArtistSort, tag.AlbumArtists, tag.Composers); + + public void AssertParentsUnchanged (MatroskaTag tag) + { + Assert.AreEqual (Title, tag.Title); + Assert.AreEqual (Artist, tag.Artist); + Assert.AreEqual (ArtistSort, tag.ArtistSort); + CollectionAssert.AreEqual (AlbumArtists, tag.AlbumArtists); + CollectionAssert.AreEqual (Composers, tag.Composers); + } + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSortIndependenceTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortIndependenceTests.cs new file mode 100644 index 00000000..ba7bf04b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortIndependenceTests.cs @@ -0,0 +1,532 @@ +// 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.Matroska; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Matroska; + +// Invariant: setting or clearing AlbumArtistSort never changes ArtistSort, and the reverse, on every +// file shape, and neither changes a parent value. The album artist is the flat ALBUM_ARTIST when the +// file has one (the ffmpeg convention), else the album-level ARTIST, and its sort pairs with it. +public partial class MatroskaFileTests +{ + static readonly (string Name, Func Build)[] SortShapes = [ + ("single-level nested", () => FileWith (Tags ( + Tag (50, Simple ("TITLE", "The Album"), SimpleSorted ("ARTIST", "The Band", "shared"))))), + ("single-level nested, two artists", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "A", "shared"), Simple ("ARTIST", "B"))))), + ("collection-level nested", () => FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "The Band", "shared")), + Tag (50, Simple ("TITLE", "The Album"))))), + ("single-level nested and flat", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "shared"), Simple ("ARTIST_SORT", "flat artist"), + Simple ("ALBUM_ARTIST_SORT", "flat album artist"))))), + ("single-level empty nested", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", ""), Simple ("ARTIST_SORT", "flat artist"))))), + ("single-level non-default nested", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "shared"), Simple ("ARTIST", "Die Band", isDefault: false))))), + ("album nested, track without artist", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "shared")), + Tag (30, Simple ("TITLE", "The Song"))))), + ("album nested and flat, subtrack without artist", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "shared"), Simple ("ALBUM_ARTIST_SORT", "flat")), + Tag (20, Simple ("TITLE", "The Part"))))), + ("collection nested, track without artist", () => FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "The Band", "collection")), + Tag (30, Simple ("TITLE", "The Song"))))), + ("album and track nested", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "album")), + Tag (30, SimpleSorted ("ARTIST", "Ada", "track"))))), + ("ffmpeg flat album artist", () => FileWith (Tags ( + Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort"), + Simple ("ALBUM_ARTIST", "The Band"), Simple ("ALBUM_ARTIST_SORT", "Band, The"))))), + ("nested album artist name", () => FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "Ada", "ada"), SimpleSorted ("ALBUM_ARTIST", "The Band", "band"))))), + ("no artist", () => FileWith (Tags (Tag (50, Simple ("TITLE", "The Album"))))), + ]; + + static byte[] SortShape (string name) => Array.Find (SortShapes, shape => shape.Name == name).Build (); + + [TestMethod] + public void SortSet_AlbumArtistAndArtistSort_StayIndependentOnEveryShape () + { + var operations = new (string Name, Action Apply, Func Read, string? Expected)[] { + ("AlbumArtistSort = NEW", t => t.AlbumArtistSort = "NEW", t => t.AlbumArtistSort, "NEW"), + ("AlbumArtistSort = null", t => t.AlbumArtistSort = null, t => t.AlbumArtistSort, null), + ("ArtistSort = NEW", t => t.ArtistSort = "NEW", t => t.ArtistSort, "NEW"), + ("ArtistSort = null", t => t.ArtistSort = null, t => t.ArtistSort, null), + ("AlbumArtistSort = empty", t => t.AlbumArtistSort = "", t => t.AlbumArtistSort, null), + ("ArtistSort = empty", t => t.ArtistSort = "", t => t.ArtistSort, null), + }; + + foreach (var (shape, build) in SortShapes) { + foreach (var (name, apply, read, expected) in operations) { + var label = $"{shape}: {name}"; + var tag = MatroskaFile.Read (build ()).File!.Tag; + var before = SortState.Of (tag); + + apply (tag); + + Assert.AreEqual (expected, read (tag), label); + var after = SortState.Of (tag); + var reread = SortState.Of (MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag); + Assert.AreEqual (after, reread, $"{label}: render"); + var expectedState = name.StartsWith ("AlbumArtistSort", StringComparison.Ordinal) + ? before with { AlbumArtistSort = expected } + : before with { ArtistSort = expected }; + Assert.AreEqual (expectedState, after, label); + } + } + } + + [TestMethod] + public void SortSet_Empty_ClearsLikeNull_OnEverySortName () + { + var setters = new (string Name, Action Set, Func Get)[] { + ("TitleSort", (t, v) => t.TitleSort = v, t => t.TitleSort), + ("ArtistSort", (t, v) => t.ArtistSort = v, t => t.ArtistSort), + ("AlbumSort", (t, v) => t.AlbumSort = v, t => t.AlbumSort), + ("AlbumArtistSort", (t, v) => t.AlbumArtistSort = v, t => t.AlbumArtistSort), + ("ComposerSort", (t, v) => t.ComposerSort = v, t => t.ComposerSort), + }; + static byte[] Build () => FileWith (Tags ( + Tag (70, Simple ("ARTIST_SORT", "f70"), Simple ("ALBUM_ARTIST_SORT", "f70"), Simple ("COMPOSER_SORT", "f70")), + Tag (50, + SimpleSorted ("TITLE", "The Album", "album"), SimpleSorted ("ARTIST", "The Band", "band"), + Simple ("ARTIST_SORT", "f50"), Simple ("ALBUM_ARTIST_SORT", "f50"), Simple ("ALBUM_SORT", "f50"), + SimpleSorted ("COMPOSER", "Bach", "bach"), Simple ("COMPOSER_SORT", "f50")), + Tag (30, SimpleSorted ("TITLE", "The Song", "song"), Simple ("TITLE_SORT", "f30")))); + + foreach (var (name, set, get) in setters) { + var tag = MatroskaFile.Read (Build ()).File!.Tag; + Assert.IsNotNull (get (tag), name); + + set (tag, ""); + + Assert.IsNull (get (tag), name); + Assert.IsNull (get (MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag), $"{name}: render"); + } + } + + [TestMethod] + public void SortSet_SingleLevelSharedArtist_ReviewerSequence_KeepsBoth () + { + var tag = MatroskaFile.Read (SortShape ("single-level nested")).File!.Tag; + + tag.ArtistSort = "Artist-only sort"; + tag.AlbumArtistSort = "Album-artist sort"; + + Assert.AreEqual ("Artist-only sort", tag.ArtistSort); + Assert.AreEqual ("Album-artist sort", tag.AlbumArtistSort); + + tag.AlbumArtistSort = null; + + Assert.AreEqual ("Artist-only sort", tag.ArtistSort); + Assert.IsNull (tag.AlbumArtistSort); + Assert.AreEqual ("The Band", tag.Artist); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + } + + [TestMethod] + public void SortSet_SameValueOnSharedArtist_LeavesTheFileAlone () + { + var original = SortShape ("single-level nested"); + var tag = MatroskaFile.Read (original).File!.Tag; + var rendered = tag.Render ().ToArray (); + + tag.AlbumArtistSort = "shared"; + tag.ArtistSort = "shared"; + + CollectionAssert.AreEqual (rendered, tag.Render ().ToArray ()); + } + + [TestMethod] + public void CopyTo_SingleLevelNestedTarget_KeepsArtistAndAlbumArtistSortApart () + { + var source = new VorbisComment { ArtistSort = "Beatles, The", AlbumArtistSort = "Various" }; + var target = MatroskaFile.Read (SortShape ("single-level nested")).File!.Tag; + + source.CopyTo (target); + + Assert.AreEqual ("Beatles, The", target.ArtistSort); + Assert.AreEqual ("Various", target.AlbumArtistSort); + Assert.AreEqual ("The Band", target.Artist); + CollectionAssert.AreEqual (SortTheBand, target.AlbumArtists); + } + + [TestMethod] + public void Read_SingleLevel_NestedSortWinsOverTheFlatName () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "nested"), Simple ("ALBUM_ARTIST_SORT", "flat"))))).File!.Tag; + var collection = MatroskaFile.Read (FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "The Band", "nested"), Simple ("ALBUM_ARTIST_SORT", "flat")), + Tag (50, Simple ("TITLE", "The Album"))))).File!.Tag; + + Assert.AreEqual ("nested", tag.AlbumArtistSort); + Assert.AreEqual ("nested", collection.AlbumArtistSort); + } + + [TestMethod] + public void Read_FlatAlbumArtist_NestedSortWinsOverTheFlatName () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "Ada"), SimpleSorted ("ALBUM_ARTIST", "The Band", "nested"), + Simple ("ALBUM_ARTIST_SORT", "flat"))))).File!.Tag; + + Assert.AreEqual ("nested", tag.AlbumArtistSort); + } + + [TestMethod] + public void Read_FlatAlbumArtist_PairsWithItsSort () + { + var tag = MatroskaFile.Read (SortShape ("ffmpeg flat album artist")).File!.Tag; + + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("Ada", tag.Artist); + Assert.AreEqual ("Ada sort", tag.ArtistSort); + } + + [TestMethod] + public void Read_FlatAlbumArtistAboveTheTrack_IsTheAlbumArtist () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "Album Artist By Spec"), Simple ("ALBUM_ARTIST", "The Band"), + Simple ("ALBUM_ARTIST_SORT", "Band, The")), + Tag (30, SimpleSorted ("ARTIST", "Ada", "ada"))))).File!.Tag; + + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("ada", tag.ArtistSort); + } + + [TestMethod] + public void AlbumArtistsSet_FlatAlbumArtist_WritesItAndKeepsTheArtist () + { + var tag = MatroskaFile.Read (SortShape ("ffmpeg flat album artist")).File!.Tag; + + tag.AlbumArtists = ["New Band"]; + + Assert.AreEqual ("New Band", string.Join ("|", tag.AlbumArtists)); + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("Ada", tag.Artist); + Assert.AreEqual ("Ada sort", tag.ArtistSort); + + var again = MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag; + Assert.AreEqual ("New Band", string.Join ("|", again.AlbumArtists)); + Assert.AreEqual ("Ada", again.Artist); + } + + [TestMethod] + public void AlbumArtistsClear_FlatAlbumArtist_RemovesItAndItsSort () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (70, Simple ("ALBUM_ARTIST", "Collection Band")), + Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort"), + Simple ("ALBUM_ARTIST", "The Band"), Simple ("ALBUM_ARTIST_SORT", "Band, The"))))).File!.Tag; + + tag.AlbumArtists = []; + + // The album-level ARTIST is the album artist by the specification once ALBUM_ARTIST is gone. + Assert.AreEqual ("Ada", string.Join ("|", tag.AlbumArtists)); + Assert.IsNull (tag.AlbumArtistSort); + Assert.AreEqual ("Ada", tag.Artist); + Assert.AreEqual ("Ada sort", tag.ArtistSort); + } + + [TestMethod] + public void SortSet_FlatAlbumArtist_WritesAlbumArtistSortNotTheArtistSort () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "Ada", "ada"), Simple ("ALBUM_ARTIST", "The Band"))))).File!.Tag; + Assert.IsNull (tag.AlbumArtistSort); + + tag.AlbumArtistSort = "Band, The"; + + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("ada", tag.ArtistSort); + var rendered = tag.Render ().ToArray (); + Assert.AreEqual (1, CountOf (rendered, "ALBUM_ARTIST_SORT"u8.ToArray ())); + Assert.AreEqual (1, CountOf (rendered, "SORT_WITH"u8.ToArray ())); + + tag.AlbumArtistSort = null; + + Assert.IsNull (tag.AlbumArtistSort); + Assert.AreEqual ("ada", tag.ArtistSort); + } + + [TestMethod] + public void RoundTrip_SingleLevelSharedArtist_OnDisk () + { + var path = WriteTempMatroska (FileWith ( + Tags (Tag (50, Simple ("TITLE", "The Album"), SimpleSorted ("ARTIST", "The Band", "shared"), + SimpleSorted ("COMPOSER", "Bach", "bach"), Simple ("GENRE", "Rock"))), + Master (0x1F43B675, SortClusterMarker))); + try { + MatroskaSortRoundTrip.VerifyOnCopy (path, saved => { + Assert.AreEqual (1, CountOf (saved, SortClusterMarker)); + Assert.AreEqual (1, CountOf (saved, TagNameElement ("GENRE")), "the genre is replaced, not shadowed"); + }); + } finally { + File.Delete (path); + } + } + + [TestMethod] + public async Task RoundTrip_FlatAlbumArtist_OnDiskAsync () + { + var path = WriteTempMatroska (SortShape ("ffmpeg flat album artist")); + try { + await MatroskaSortRoundTrip.VerifyOnCopyAsync (path, saved => Assert.AreEqual (1, CountOf (saved, "ALBUM_ARTIST_SORT"u8.ToArray ()))); + } finally { + File.Delete (path); + } + } + + // Invariant: a sort write never changes where later item-field writes land. After any sort operation on + // any shape, clearing Genre, Comment or Year reads null, and setting one reads the new value from a single + // SimpleTag, in memory and after a render. The fields start at 50, where TagLib# and ffmpeg write them. + [TestMethod] + public void SortSet_ThenItemFields_ClearAndSetOnEveryShape () + { + var sortOps = new (string Name, Action Apply, Func Read, string? Expected)[] { + ("AlbumArtistSort = NEW", t => t.AlbumArtistSort = "NEW", t => t.AlbumArtistSort, "NEW"), + ("AlbumArtistSort = null", t => t.AlbumArtistSort = null, t => t.AlbumArtistSort, null), + ("AlbumArtistSort = empty", t => t.AlbumArtistSort = "", t => t.AlbumArtistSort, null), + ("ArtistSort = NEW", t => t.ArtistSort = "NEW", t => t.ArtistSort, "NEW"), + ("ArtistSort = null", t => t.ArtistSort = null, t => t.ArtistSort, null), + ("ArtistSort = empty", t => t.ArtistSort = "", t => t.ArtistSort, null), + }; + var fields = new (string Name, string TagName, Action Set, Func Get)[] { + ("Genre", "GENRE", (t, v) => t.Genre = v, t => t.Genre), + ("Comment", "COMMENT", (t, v) => t.Comment = v, t => t.Comment), + ("Year", "DATE_RELEASED", (t, v) => t.Year = v, t => t.Year), + ("Genres", "GENRE", (t, v) => t.Genres = v is null ? [] : [v], t => t.Genres.FirstOrDefault ()), + }; + + foreach (var (shape, data) in ItemFieldShapes ()) { + foreach (var (sortName, apply, read, expected) in sortOps) { + foreach (var (field, tagName, set, get) in fields) { + foreach (var value in new[] { null, "1999" }) { + var label = $"{shape}: {sortName}, then {field} = {value ?? "null"}"; + var tag = MatroskaFile.Read (data).File!.Tag; + + apply (tag); + set (tag, value); + + Assert.AreEqual (value, get (tag), label); + Assert.AreEqual (expected, read (tag), $"{label}: sort"); + var rendered = tag.Render ().ToArray (); + var again = MatroskaFile.Read (FileWith (rendered)).File!.Tag; + Assert.AreEqual (value, get (again), $"{label}: render"); + Assert.AreEqual (expected, read (again), $"{label}: render sort"); + Assert.AreEqual (value is null ? 0 : 1, CountOf (rendered, TagNameElement (tagName)), $"{label}: {tagName} count"); + } + } + } + } + } + + static IEnumerable<(string Name, byte[] Data)> ItemFieldShapes () + { + string[] kinds = ["absent", "plain", "nested"]; + // ARTIST at 30 and 50 {absent, plain, nested} x nested ARTIST at 70 x ALBUM_ARTIST {none, 50, nested 70} x track filler. + for (var i = 0; i < 3 * 3 * 2 * 3 * 2; i++) { + var a30 = i % 3; + var a50 = i / 3 % 3; + var a70 = i / 9 % 2; + var albumArtist = i / 18 % 3; + var filler = i / 54; + var at70 = new List (); + var at50 = new List { Simple ("GENRE", "Rock"), Simple ("COMMENT", "c50"), Simple ("DATE_RELEASED", "2001") }; + var at30 = new List (); + if (ArtistAt (a30, 30) is { } x30) + at30.Add (x30); + if (ArtistAt (a50, 50) is { } x50) + at50.Add (x50); + if (a70 == 1) + at70.Add (SimpleSorted ("ARTIST", "A70", "n70")); + if (albumArtist == 1) + at50.Add (Simple ("ALBUM_ARTIST", "AA50")); + if (albumArtist == 2) + at70.Add (SimpleSorted ("ALBUM_ARTIST", "AA70", "aa70")); + if (filler == 1) + at30.Add (Simple ("TITLE", "Song")); + var blocks = new List (); + if (at70.Count > 0) + blocks.Add (Tag (70, [.. at70])); + blocks.Add (Tag (50, [.. at50])); + if (at30.Count > 0) + blocks.Add (Tag (30, [.. at30])); + yield return ($"a30={kinds[a30]} a50={kinds[a50]} a70={a70} albumArtist={albumArtist} filler={filler}", + FileWith (Tags ([.. blocks]))); + } + } + + static byte[]? ArtistAt (int kind, ulong level) => kind switch { + 1 => Simple ("ARTIST", $"A{level}"), + 2 => SimpleSorted ("ARTIST", $"A{level}", $"n{level}"), + _ => null, + }; + + static byte[] TagNameElement (string name) => Element (0x45A3, Encoding.UTF8.GetBytes (name)); + + [TestMethod] + public void NewField_AfterASortSplit_StaysWithTheFileFields () + { + // TagLib# writes every tag at 50 and reads new fields only there. The ARTIST copy at 30 that keeps + // ArtistSort apart must not pull later new fields down to 30. + var original = FileWith ( + Tags (Tag (50, Simple ("TITLE", "The Album"), SimpleSorted ("ARTIST", "The Band", "shared"), Simple ("GENRE", "Rock"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.ArtistSort = "track"; + parsed.Tag.Conductor = "Cond"; + parsed.Tag.Genre = "Jazz"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("track", again.ArtistSort); + Assert.AreEqual ("shared", again.AlbumArtistSort); + Assert.AreEqual ("Cond", again.Conductor); + Assert.AreEqual ("Jazz", again.Genre); + Assert.IsTrue (FileTargetHas (bytes, 30, "ARTIST"), "the track keeps its own ARTIST"); + Assert.IsTrue (FileTargetHas (bytes, 50, "CONDUCTOR")); + Assert.IsFalse (FileTargetHas (bytes, 30, "CONDUCTOR")); + Assert.IsTrue (FileTargetHas (bytes, 50, "GENRE")); + Assert.AreEqual (1, CountOf (bytes, TagNameElement ("GENRE"))); + CollectionAssert.AreEqual (new ulong[] { 50, 30 }, TargetLevelsInOrder (bytes), "the new track Tag goes after the album's"); + } + + [TestMethod] + public void SortSplit_FromACollectionArtist_OrdersTheNewTagsBroadestFirst () + { + var original = FileWith ( + Tags (Tag (70, SimpleSorted ("ARTIST", "The Band", "shared")), Tag (60, Simple ("TOTAL_PARTS", "2"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.AlbumArtistSort = "album"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("album", again.AlbumArtistSort); + Assert.AreEqual ("shared", again.ArtistSort); + CollectionAssert.AreEqual (new ulong[] { 70, 60, 50, 30 }, TargetLevelsInOrder (bytes)); + } + + [TestMethod] + public void SortClear_ThatEmptiesATag_DropsIt () + { + // RFC 9559 section 5.1.8.1.2: a Tag holds at least one SimpleTag. Clearing the sorts empties the 30 Tag; + // the file is then album-level, so the 60 ALBUM_ARTIST_SORT is visible and goes too. + var original = FileWith ( + Tags ( + Tag (60, Simple ("ALBUM_ARTIST_SORT", "aa")), + Tag (50, Simple ("TITLE", "The Album"), Simple ("ARTIST", "The Band"), Simple ("COMPOSER", "Bach")), + Tag (30, Simple ("ARTIST_SORT", "a"), Simple ("COMPOSER_SORT", "c"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.ArtistSort = null; + parsed.Tag.ComposerSort = null; + parsed.Tag.AlbumArtistSort = null; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.IsNull (again.ArtistSort); + Assert.IsNull (again.ComposerSort); + Assert.IsNull (again.AlbumArtistSort); + CollectionAssert.AreEqual (new ulong[] { 50 }, TargetLevelsInOrder (bytes)); + Assert.AreEqual (1, CountOf (bytes, Id (0x7373))); + } + + [TestMethod] + public void SortSet_WithoutASharedNestedSort_AddsNoTrackArtist () + { + // A split is only for a shared SORT_WITH: not for a bare ARTIST, and not when ALBUM_ARTIST names the album artist. + var shapes = new[] { + ("bare single-level artist", FileWith (Tags (Tag (50, Simple ("ARTIST", "The Band"), Simple ("GENRE", "Rock"))))), + ("nested artist beside ALBUM_ARTIST", SortShape ("nested album artist name")), + ("ffmpeg flat album artist", SortShape ("ffmpeg flat album artist")), + }; + foreach (var (name, data) in shapes) { + foreach (var write in new Action[] { t => t.ArtistSort = "NEW", t => t.AlbumArtistSort = "NEW", t => t.ArtistSort = null }) { + var tag = MatroskaFile.Read (data).File!.Tag; + var artistsBefore = CountOf (tag.Render ().ToArray (), TagNameElement ("ARTIST")); + + write (tag); + + var rendered = tag.Render ().ToArray (); + Assert.AreEqual (artistsBefore, CountOf (rendered, TagNameElement ("ARTIST")), name); + Assert.IsFalse (FileTargetHas (FileWith (rendered), 30, "ARTIST"), name); + } + } + } + + [TestMethod] + public void Clear_ThatEmptiesTheTrackTag_ReadsLikeTheSavedFile () + { + // An emptied Tag is not rendered (RFC 9559 section 5.1.8.1.2), so the file is then album-level and the + // collection ARTIST reaches the album. Memory must say what a re-read of the saved file says. + var original = FileWith ( + Tags ( + Tag (70, SimpleSorted ("ARTIST", "Collection", "collection")), + Tag (50, Simple ("TITLE", "The Album")), + Tag (30, Simple ("GENRE", "Jazz"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + Assert.IsEmpty (parsed.Tag.AlbumArtists); + + parsed.Tag.Genre = null; + + var inMemory = SortState.Of (parsed.Tag); + var again = SaveAndReread (parsed, original, out _); + Assert.AreEqual (SortState.Of (again), inMemory); + Assert.AreEqual ("Collection", string.Join ("|", parsed.Tag.AlbumArtists)); + } + + [TestMethod] + public void AlbumArtistsSet_CollectionAlbumArtist_StaysAtItsLevel () + { + var original = FileWith ( + Tags (Tag (70, SimpleSorted ("ALBUM_ARTIST", "Old Band", "Band, Old")), Tag (30, Simple ("TITLE", "The Song"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.AlbumArtists = ["New Band"]; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("New Band", string.Join ("|", again.AlbumArtists)); + Assert.AreEqual (1, CountOf (bytes, TagNameElement ("ALBUM_ARTIST"))); + Assert.IsTrue (FileTargetHas (bytes, 70, "ALBUM_ARTIST")); + Assert.IsFalse (FileTargetHas (bytes, 30, "ALBUM_ARTIST")); + } + + [TestMethod] + public void AlbumArtistsSet_EmptyStrings_ClearTheFlatAlbumArtistAndItsSort () + { + foreach (var empty in new[] { new[] { "" }, new[] { "", "" } }) { + var tag = MatroskaFile.Read (SortShape ("ffmpeg flat album artist")).File!.Tag; + + tag.AlbumArtists = empty; + + Assert.AreEqual ("Ada", string.Join ("|", tag.AlbumArtists)); + Assert.IsNull (tag.AlbumArtistSort); + var rendered = tag.Render ().ToArray (); + Assert.AreEqual (0, CountOf (rendered, TagNameElement ("ALBUM_ARTIST"))); + Assert.AreEqual (0, CountOf (rendered, TagNameElement ("ALBUM_ARTIST_SORT"))); + } + } + + sealed record SortState ( + string? Title, string? Album, string? Artist, string Performers, string AlbumArtists, string Composers, + string? ArtistSort, string? AlbumArtistSort, string? ComposerSort, string? TitleSort, string? AlbumSort) + { + public static SortState Of (MatroskaTag tag) => new ( + tag.Title, tag.Album, tag.Artist, string.Join ("|", tag.Performers), string.Join ("|", tag.AlbumArtists), + string.Join ("|", tag.Composers), tag.ArtistSort, tag.AlbumArtistSort, tag.ComposerSort, tag.TitleSort, + tag.AlbumSort); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSortModelTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortModelTests.cs new file mode 100644 index 00000000..96636a9f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortModelTests.cs @@ -0,0 +1,738 @@ +// 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.Matroska; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Matroska; + +// The sort ownership model, as an oracle that reads rendered bytes (the PR body states it in prose): +// - A nested SORT_WITH sorts the SimpleTag it is in (tagging.html, "Nested Information"). +// - A flat X_SORT sorts the X in its own Tag (the ffmpeg convention). A Tag with no X passes its X_SORT down. +// - Climbing from the item, levels form runs of one value. A broader Tag that repeats the same X is the +// same value (tagging.html, "Target types": "you can also repeat the value for each track"); a Tag with a +// different X starts the next run. The item's sort is the nested sort on the X it reads, else the first +// flat X_SORT in its run. +// - The album artist of a file with a track level is the ARTIST at 50, so its run starts at 50 (with no +// ARTIST there, the album has none) and climbs the same way. +// - Only file-level Tags count: a Tag that targets a chapter, attachment, track or edition is another item's. +// Every operation must keep: the library reads what the oracle reads; a write-back changes no byte; a copy +// of the values read changes no value; a sort set leaves exactly one copy in the item's run, in the value's +// Tag (at 50 or below), and a clear leaves none; a Tag of another item is untouched; and no other value's +// sort changes. A value write that makes two levels equal joins their runs and one that makes them differ +// splits them; only then may the item's sort change with its value unchanged. +public partial class MatroskaFileTests +{ + sealed record ModelTag (string Name, string Text, List Sorts); + + sealed record ModelRun (string Key, ulong Head, string? Sort, List Levels); + + [TestMethod] + public void SortModel_HoldsForEveryShapeAndOperation () + { + var failures = new List (); + var cases = 0; + foreach (var pair in SortPairs) { + foreach (var (shape, data) in ModelShapes (pair)) { + foreach (var op in ModelOps (pair)) { + cases++; + var label = $"{pair.Name} {shape}: {op.Name}"; + try { + CheckModel (pair, data, op, failures, label); + } catch (AssertFailedException e) { + failures.Add ($"{label}: {e.Message}"); + } + } + } + } + + Assert.IsTrue (cases > 10000, $"only {cases} cases"); + if (Environment.GetEnvironmentVariable ("SORT_MODEL_DUMP") is string dump) + File.WriteAllLines (dump, failures); + Assert.IsEmpty (failures, $"{failures.Count} of {cases} cases broke the model, e.g.\n{string.Join ("\n", failures.Take (8))}"); + } + + sealed record ModelOp (string Name, Action Apply, string Kind, string? Expected = null, Action? Then = null); + + static ModelOp[] ModelOps (SortPair pair) + { + Action setSort = pair.Getter switch { + Getter.Artist => (t, v) => t.ArtistSort = v, + Getter.Composer => (t, v) => t.ComposerSort = v, + _ => (t, v) => t.AlbumArtistSort = v, + }; + var ops = new List { + new ("sort = NEW", t => setSort (t, "NEW"), "set", "NEW"), + new ("sort = null", t => setSort (t, null), "clear"), + new ("sort = empty", t => setSort (t, ""), "clear"), + new ("sort written back", t => setSort (t, ReadSort (t, pair)), "writeback"), + new ("every value and sort written back", WriteEverythingBack, "writebackall"), + new ("CopyTo of the values read", t => { var copy = new VorbisComment (); t.CopyTo (copy); copy.CopyTo (t); }, "copyread"), + new ("sort = NEW, then the value", t => setSort (t, "NEW"), "set", "NEW", t => SetValueOf (t, pair, "NEWV")), + new ("Title = NEWV", t => t.Title = "NEWV", "unrelated"), + new ("Genre = NEWV", t => t.Genre = "NEWV", "unrelated"), + }; + // Writes of each text a shape holds, so a write can make two levels equal or different. + foreach (var text in new[] { $"{pair.Value}30", $"{pair.Value}50", $"{pair.Value}70", $"{pair.Value}A", $"{pair.Value}B", pair.Value }) + ops.Add (new ($"value = {text}", t => SetValueOf (t, pair, text), "value")); + if (pair.Getter is Getter.Artist) { + foreach (var text in new[] { "ARTIST30", "ARTIST50", "ARTIST70", "ARTISTA", "ARTISTB", "ARTIST" }) + ops.Add (new ($"AlbumArtists = {text}", t => t.AlbumArtists = [text], "value")); + } + switch (pair.Getter) { + case Getter.Artist: + ops.Add (new ("Artist = NEWV", t => t.Artist = "NEWV", "value")); + ops.Add (new ("Artist = the artist read", t => t.Artist = t.Artist, "writeback")); + ops.Add (new ("CopyTo Artist only, as read", t => new VorbisComment { Artist = t.Artist }.CopyTo (t), "copyone")); + ops.Add (new ("CopyTo Artist and sort", t => new VorbisComment { Artist = "NEWV", ArtistSort = "NEWS" }.CopyTo (t), "copy", "NEWS")); + ops.Add (new ("AlbumArtists = NEWV", t => t.AlbumArtists = ["NEWV"], "value")); + ops.Add (new ("AlbumArtists = []", t => t.AlbumArtists = [], "valueclear")); + ops.Add (new ("Artist = null", t => t.Artist = null, "valueclear")); + ops.Add (new ("Performers = []", t => t.Performers = [], "valueclear")); + break; + case Getter.Composer: + ops.Add (new ("Composers = NEWV", t => t.Composers = ["NEWV"], "value")); + ops.Add (new ("CopyTo Composers and sort", t => new VorbisComment { Composers = ["NEWV"], ComposerSort = "NEWS" }.CopyTo (t), "copy", "NEWS")); + ops.Add (new ("Composers = []", t => t.Composers = [], "valueclear")); + break; + default: + ops.Add (new ("AlbumArtists = NEWV", t => t.AlbumArtists = ["NEWV"], "value")); + ops.Add (new ("AlbumArtists = []", t => t.AlbumArtists = [], "valueclear")); + break; + } + + return [.. ops]; + } + + static void SetValueOf (MatroskaTag t, SortPair pair, string text) + { + switch (pair.Getter) { + case Getter.Artist: + t.Artist = text; + break; + case Getter.Composer: + t.Composers = [text]; + break; + default: + t.AlbumArtists = [text]; + break; + } + } + + static string ModelState (MatroskaTag t, bool values = true) => + string.Join (" | ", t.Artist, values ? string.Join (",", t.Performers) : "", string.Join (",", t.AlbumArtists), string.Join (",", t.Composers), + values ? t.ArtistSort : "", t.AlbumArtistSort, t.ComposerSort, t.Title, t.Album, t.Genre); + + static void WriteEverythingBack (MatroskaTag t) + { + t.Artist = t.Artist; + t.Performers = t.Performers; + t.AlbumArtists = t.AlbumArtists; + t.Composers = t.Composers; + t.ArtistSort = t.ArtistSort; + t.AlbumArtistSort = t.AlbumArtistSort; + t.ComposerSort = t.ComposerSort; + t.Title = t.Title; + t.Genre = t.Genre; + } + + static void CheckModel (SortPair pair, byte[] data, ModelOp op, List failures, string label) + { + var tag = MatroskaFile.Read (data).File!.Tag; + var beforeBytes = tag.Render ().ToArray (); + var before = ModelLayout (beforeBytes); + var (beforeKey, beforeSort, beforeRuns) = Oracle (before, pair); + Assert.AreEqual (beforeSort, ReadSort (tag, pair), "the library reads what the model reads"); + + op.Apply (tag); + + var afterBytes = tag.Render ().ToArray (); + var after = ModelLayout (afterBytes); + CollectionAssert.AreEqual (OtherItemTags (beforeBytes), OtherItemTags (afterBytes), "a Tag of a chapter, attachment, track or edition changed"); + var (afterKey, afterSort, afterRuns) = Oracle (after, pair); + Assert.AreEqual (afterSort, ReadSort (tag, pair), "after: the library reads what the model reads"); + Assert.AreEqual (afterSort, ReadSort (MatroskaFile.Read (FileWith (afterBytes)).File!.Tag, pair), "after a render"); + + if (op.Then is not null) { + // The sort sits in its value's Tag, so a later write of the item's value leaves it there. + var held = SortLevels (after, op.Expected!); + op.Then (tag); + var final = ModelLayout (tag.Render ().ToArray ()); + CollectionAssert.IsSubsetOf (held, SortLevels (final, op.Expected!), $"the sort left {string.Join (",", held)}"); + } + + // Writing back every value is a write-back, except where rule 8 makes it a clear: an empty list read from a + // whole-file field (Composers, a flat ALBUM_ARTIST) while a broader level still holds text (#136). + var kind = op.Kind == "writebackall" ? (EmptyReadOverText (before, pair) ? "valueclear" : "writeback") : op.Kind; + switch (kind) { + case "writeback": + CollectionAssert.AreEqual (beforeBytes, afterBytes, "a write-back changed bytes"); + return; + case "copyread": + // A copy replaces (Tag.IsWriteBack): the bytes may change, but every value and sort reads the same, + // and a sort the copy wrote leaves one copy. + Assert.AreEqual (ModelState (MatroskaFile.Read (FileWith (beforeBytes)).File!.Tag), ModelState (tag), "a copy of the values read changed what is read"); + if (afterSort is not null && beforeBytes.AsSpan ().SequenceEqual (afterBytes) is false) + AssertOneCopy (after, pair, afterSort); + break; + case "copyone": + // One artist copied over a list replaces the list (a value write); nothing else changes. + Assert.AreEqual (ModelState (MatroskaFile.Read (FileWith (beforeBytes)).File!.Tag, values: false), ModelState (tag, values: false), "a copy of the artist read changed another property"); + break; + case "unrelated": + // A write to another property, even one that adds a track level, leaves every value and sort of the + // pair where it was; what each getter reads is then the model's read of that layout (checked above). + CollectionAssert.AreEqual (PairLayout (before, pair), PairLayout (after, pair), "another property's write moved a value or sort of the pair"); + return; + case "set": + Assert.AreEqual (op.Expected, afterSort, "the set reads back"); + AssertOneCopy (after, pair, op.Expected!); + AssertInTheValuesTag (after, pair, op.Expected!); + break; + + case "clear": + Assert.IsNull (afterSort, "the clear reads back"); + AssertNoCopy (after, pair, beforeSort); + break; + case "copy": + Assert.AreEqual ("NEWV", afterKey, "the copied value is read"); + Assert.AreEqual (op.Expected, afterSort, "the copied sort is read"); + AssertOneCopy (after, pair, op.Expected!); + break; + } + + // A value write moves sorts only as rule 7 says, so the whole layout of the pair's sorts is predicted from the + // layout before. A sort write changes no other value's own sort. + if (kind is "value" or "valueclear" or "copy" or "copyone") + AssertValueWriteFollowsTheModel (before, after, pair, skipItemRun: op.Kind == "copy"); + else + AssertOtherSortsKept (before, after, pair, beforeRuns); + } + + static bool EmptyReadOverText (SortedDictionary> layout, SortPair pair) + { + var name = ValueName (layout, pair); + if (name is not ("COMPOSER" or "ALBUM_ARTIST")) + return false; + var read = layout.Values.FirstOrDefault (tags => tags.Exists (t => t.Name == name)); + return read is not null && read.TrueForAll (t => t.Name != name || t.Text.Length == 0) + && layout.Values.Any (tags => tags.Exists (t => t.Name == name && t.Text.Length > 0)); + } + + static string? ValuesAt (SortedDictionary> layout, ulong level, string name) => + layout.TryGetValue (level, out var tags) && tags.Exists (t => t.Name == name) + ? string.Join ("|", tags.Where (t => t.Name == name).Select (t => t.Text)) : null; + + // Every level's values, flat sorts and nested sorts of the pair, as text. + static List PairLayout (SortedDictionary> layout, SortPair pair) + { + var name = ValueName (layout, pair); + var flat = FlatName (layout, pair); + return [.. layout.Select (l => $"{l.Key}: {string.Join (",", l.Value.Where (t => t.Name == name).Select (t => $"{t.Text}({string.Join ("/", t.Sorts)})"))} | {string.Join (",", l.Value.Where (t => t.Name == flat).Select (t => t.Text))}") + .Where (line => !line.EndsWith (": | ", StringComparison.Ordinal))]; + } + + /// + /// The sort a value's head level owns: the nested sort on its SimpleTag, else the first flat sort from it up + /// through value-less levels and levels that repeat it (rules 2 and 4). + /// + static string? OwnSort (SortedDictionary> layout, ulong head, string name, string flat) + { + if (!layout.TryGetValue (head, out var headTags)) + return null; + var nested = headTags.Where (t => t.Name == name && t.Text.Length > 0).SelectMany (t => t.Sorts).FirstOrDefault (s => s.Length > 0); + if (nested is not null) + return nested; + var value = ValuesAt (layout, head, name); + foreach (var level in layout.Keys.Where (l => l >= head)) { + var at = ValuesAt (layout, level, name); + if (level > head && at is not null && at != value) + break; + var flats = layout[level].Where (t => t.Name == flat).ToList (); + if (flats.Count > 0) + return flats.Select (t => t.Text).FirstOrDefault (t => t.Length > 0); + } + + return null; + } + + // A sort write sets or clears the item's sort; every other value keeps its own. + static void AssertOtherSortsKept (SortedDictionary> before, SortedDictionary> after, SortPair pair, List beforeRuns) + { + var name = ValueName (before, pair); + var flat = FlatName (before, pair); + // The item's own run is the one written. A split (rule 10) gives the item a copy of its value, and the + // broader value it copied keeps its own sort. + var item = ItemRun (before, pair).Head; + var split = item is not null && ItemRun (after, pair).Head is ulong now && now != item; + foreach (var run in beforeRuns) { + if (run == beforeRuns[0] && !split) + continue; + Assert.AreEqual (OwnSort (before, run.Head, name, flat), OwnSort (after, run.Head, name, flat), $"the {run.Key} at {run.Head} lost or changed its sort"); + } + } + + /// + /// Rule 7 applied to the layout before, compared with the layout after. A rename keeps its sorts. A cleared + /// value takes its own Tag's flat sorts and those of the value-less broader Tags up to the next value, except + /// the one an equal narrower value reads. A sort the narrower value read from at or above the written level, + /// which is no longer in its run, moves down to it. A whole-file field (Composers, a flat ALBUM_ARTIST) is + /// written where it is read, and its clear removes every value and every sort with them. A value written + /// equal to the broader value it shadows repeats that value's nested sorts. Nested sorts elsewhere stay. + /// + static void AssertValueWriteFollowsTheModel (SortedDictionary> before, SortedDictionary> after, SortPair pair, bool skipItemRun) + { + var name = ValueName (before, pair); + var flat = FlatName (before, pair); + var wholeFile = name is "COMPOSER" or "ALBUM_ARTIST"; + var fixedAlbum = pair.Getter is Getter.AlbumArtistByArtist && !ByAlbumArtistName (before, pair); + var levels = before.Keys.Union (after.Keys).OrderBy (l => l).ToList (); + var predicted = levels.ToDictionary (l => l, l => before.TryGetValue (l, out var tags) ? tags.Where (t => t.Name == flat).Select (t => t.Text).ToList () : []); + var written = levels.Where (l => ValuesAt (before, l, name) != ValuesAt (after, l, name)).ToList (); + + if (wholeFile) { + if (written.Count > 0 && levels.TrueForAll (l => ValuesAt (after, l, name) is null)) + foreach (var level in levels) + predicted[level].Clear (); + } else { + foreach (var at in written) { + // The narrower value is the lowest one, below the written level; the sort it reads is the first flat in its run. + var narrower = fixedAlbum ? null : levels.Where (l => l < at && ValuesAt (before, l, name) is not null).Cast ().FirstOrDefault (); + ulong? read = narrower is null ? null : ItemRun (before, pair).Levels.Where (l => predicted[l].Count > 0).Cast ().FirstOrDefault (); + var kept = read is ulong r && r >= at ? read : null; + if (ValuesAt (before, at, name) is not null && ValuesAt (after, at, name) is null) { + foreach (var level in levels.Where (l => l >= at)) { + if (level > at && ValuesAt (before, level, name) is not null) + break; + if (level != kept) + predicted[level].Clear (); + } + } + + if (kept is ulong from && narrower is ulong to) { + var stillRead = ItemRun (after, pair).Levels.Where (l => predicted[l].Count > 0).Cast ().FirstOrDefault (); + if (stillRead != from && predicted[to].Count == 0) { + predicted[to] = predicted[from]; + predicted[from] = []; + } + } + } + } + + // A copy then sets the item's sort, which rewrites the flats of the item's run: the levels from the item up, + // through every level without a value (a Tag the set emptied is gone) or with the item's value. + var skip = new HashSet (); + if (skipItemRun) { + var itemValue = levels.Select (l => ValuesAt (after, l, name)).FirstOrDefault (v => v is not null); + foreach (var level in levels) { + var at = ValuesAt (after, level, name); + if (at is not null && at != itemValue) + break; + skip.Add (level); + } + } + foreach (var level in levels.Where (l => !skip.Contains (l))) { + var actual = after.TryGetValue (level, out var tags) ? tags.Where (t => t.Name == flat).Select (t => t.Text).Order ().ToList () : []; + CollectionAssert.AreEqual (predicted[level].Order ().ToList (), actual, $"level {level}: flat sorts [{string.Join (",", actual)}] where the model puts [{string.Join (",", predicted[level])}]"); + + string Nested (SortedDictionary> layout, ulong at) => + layout.TryGetValue (at, out var found) ? string.Join (",", found.Where (t => t.Name == name).Select (t => string.Join ("/", t.Sorts))) : ""; + if (!written.Contains (level)) { + Assert.AreEqual (Nested (before, level), Nested (after, level), $"level {level}: a nested sort changed"); + } else if (!wholeFile && ValuesAt (before, level, name) is null && ValuesAt (after, level, name) is string now) { + var broader = levels.Where (l => l > level && ValuesAt (after, l, name) is not null).Cast ().FirstOrDefault (); + if (broader is ulong b && ValuesAt (after, b, name) == now) + Assert.AreEqual (Nested (before, b), Nested (after, level), $"level {level}: a repeat of the {b} value lacks its nested sorts"); + } + } + } + + // The pair the library uses for the album artist depends on the file: ALBUM_ARTIST when it has one. + static bool ByAlbumArtistName (SortedDictionary> layout, SortPair pair) => + pair.Getter is Getter.AlbumArtistByName or Getter.AlbumArtistByArtist && layout.Values.Any (tags => tags.Exists (t => t.Name == "ALBUM_ARTIST")); + + static string ValueName (SortedDictionary> layout, SortPair pair) => + pair.Getter is Getter.AlbumArtistByName or Getter.AlbumArtistByArtist ? (ByAlbumArtistName (layout, pair) ? "ALBUM_ARTIST" : "ARTIST") : pair.Value; + + static string FlatName (SortedDictionary> layout, SortPair pair) => pair.Flat; + + /// The model's read: the item's value key, its sort, and every run from the item up. + static (string? Key, string? Sort, List Runs) Oracle (SortedDictionary> layout, SortPair pair) + { + var name = ValueName (layout, pair); + var flat = FlatName (layout, pair); + var levels = layout.Keys.ToList (); + var item = levels.Count == 0 ? 50UL : levels[0]; + var fixedAlbum = pair.Getter is Getter.AlbumArtistByArtist or Getter.AlbumArtistByName && !ByAlbumArtistName (layout, pair) && item < 50; + + string Values (ulong level) => string.Join ("|", layout[level].Where (t => t.Name == name).Select (t => t.Text)); + bool HasValue (ulong level) => layout[level].Exists (t => t.Name == name); + string? FirstFlat (ulong level) + { + var flats = layout[level].Where (t => t.Name == flat).ToList (); + return flats.Count == 0 ? null : flats.Select (t => t.Text).FirstOrDefault (t => t.Length > 0); + } + + (bool Found, string? Sort) FirstFlatOrBlock (ulong level) => layout[level].Exists (t => t.Name == flat) ? (true, FirstFlat (level)) : (false, null); + + string? NestedOf (ulong level) + { + var parent = layout[level].FirstOrDefault (t => t.Name == name && t.Text.Length > 0); + return parent?.Sorts.FirstOrDefault (s => s.Length > 0); + } + + if (fixedAlbum) { + var album = AlbumRun (layout, name); + var key = layout.ContainsKey (50) && HasValue (50) ? Values (50) : null; + var sort = (key is null ? null : NestedOf (50)) ?? album.Select (FirstFlatOrBlock).FirstOrDefault (s => s.Found).Sort; + return (key, sort, [new ModelRun (key ?? "", 50, sort, album)]); + } + + // Split the levels into runs: levels below the first value join its run; a level with a different value starts the next. + var runs = new List<(string? Key, ulong Head, List Levels)> (); + var pending = new List (); + foreach (var level in levels) { + if (!HasValue (level)) { + if (runs.Count == 0) + pending.Add (level); + else + runs[^1].Levels.Add (level); + continue; + } + + var key = Values (level); + if (runs.Count > 0 && runs[^1].Key == key) { + runs[^1].Levels.Add (level); + continue; + } + + var members = runs.Count == 0 ? new List (pending) { level } : [level]; + runs.Add ((key, level, members)); + } + + if (runs.Count == 0) { + // No value at all: every flat sort is the item's. + var orphan = pending.Select (FirstFlatOrBlock).FirstOrDefault (s => s.Found); + return (null, orphan.Sort, []); + } + + + // The item reads its run from the item up. A value's own sort, compared across an edit, is its head + // Tag's and above: a sort in a narrower Tag that only the item inherited is the item's. + string? SortOf (string? key, ulong head, IEnumerable reads) => + NestedOf (head) ?? reads.Select (FirstFlatOrBlock).FirstOrDefault (s => s.Found).Sort; + var model = new List (); + foreach (var (key, head, members) in runs) + model.Add (new ModelRun (key!, head, SortOf (key, head, members.Where (l => l >= head)), members)); + return (runs[0].Key, SortOf (runs[0].Key, runs[0].Head, runs[0].Levels), model); + } + + // One sort for the item's value: the nested one on the SimpleTag read with no flat left in its run, or one flat. + static void AssertOneCopy (SortedDictionary> layout, SortPair pair, string expected) + { + var (flats, nested) = ItemRunSorts (layout, pair); + if (nested == expected) + Assert.IsEmpty (flats, $"a nested sort left flat copies: {string.Join (",", flats)}"); + else + CollectionAssert.AreEqual (new[] { expected }, flats, "the run holds one flat copy of the new sort"); + } + + static void AssertNoCopy (SortedDictionary> layout, SortPair pair, string? old) + { + var (flats, nested) = ItemRunSorts (layout, pair); + Assert.IsEmpty (flats.Where (f => f.Length > 0), $"the clear left {string.Join (",", flats)} for another reader"); + Assert.IsNull (nested, "the clear left a nested sort"); + if (old is not null) + Assert.IsFalse (flats.Contains (old)); + } + + static HashSet ItemRunLevels (SortedDictionary> layout, SortPair pair) => [.. ItemRun (layout, pair).Levels]; + + static (List Flats, string? Nested) ItemRunSorts (SortedDictionary> layout, SortPair pair) + { + var (run, head) = ItemRun (layout, pair); + var name = ValueName (layout, pair); + var flat = FlatName (layout, pair); + var flats = run.SelectMany (l => layout[l].Where (t => t.Name == flat).Select (t => t.Text)).ToList (); + var nested = head is ulong h ? layout[h].FirstOrDefault (t => t.Name == name && t.Text.Length > 0)?.Sorts.FirstOrDefault (s => s.Length > 0) : null; + return (flats, nested); + } + + static (List Levels, ulong? Head) ItemRun (SortedDictionary> layout, SortPair pair) + { + var name = ValueName (layout, pair); + var levels = layout.Keys.ToList (); + if (levels.Count == 0) + return ([], null); + var item = levels[0]; + var fixedAlbum = pair.Getter is Getter.AlbumArtistByArtist or Getter.AlbumArtistByName && !ByAlbumArtistName (layout, pair) && item < 50; + var run = new List (); + string? value = null; + ulong? head = null; + if (fixedAlbum) + return (AlbumRun (layout, name), layout.TryGetValue (50, out var album) && album.Exists (t => t.Name == name) ? 50UL : null); + foreach (var level in levels) { + var tags = layout[level]; + if (tags.Exists (t => t.Name == name)) { + var key = string.Join ("|", tags.Where (t => t.Name == name).Select (t => t.Text)); + if (value is null) { + value = key; + head = level; + } else if (value != key) { + break; + } + } + + run.Add (level); + } + + return (run, head); + } + + static List SortLevels (SortedDictionary> layout, string sort) => + [.. layout.Where (l => l.Value.Exists (t => t.Text == sort || t.Sorts.Contains (sort))).Select (l => l.Key)]; + + // The album's run: level 50 and each broader level up to the first whose value is not 50's. + static List AlbumRun (SortedDictionary> layout, string name) + { + // With no ARTIST at 50 the album has none, and any broader value, an empty one too, is another value's. + var album = ValuesAt (layout, 50, name); + var run = new List (); + foreach (var level in layout.Keys.Where (l => l >= 50)) { + if (level > 50 && ValuesAt (layout, level, name) is string value && value != album) + break; + run.Add (level); + } + + return run; + } + + // The sort set sits in the Tag of the value it sorts when that is at 50 or below, else at 50 or below. + static void AssertInTheValuesTag (SortedDictionary> layout, SortPair pair, string expected) + { + var (run, head) = ItemRun (layout, pair); + var flat = FlatName (layout, pair); + var at = run.Where (l => layout[l].Exists (t => t.Name == flat && t.Text == expected)).ToList (); + if (at.Count == 0) + return; + if (head is ulong h && h <= 50) + CollectionAssert.AreEqual (new[] { h }, at, "the flat sort is not in its value's Tag"); + else + Assert.IsTrue (at.TrueForAll (l => l <= 50), $"the flat sort is at {string.Join (",", at)}, above the album"); + } + + static bool IsOtherItems (ReadOnlySpan targets) + { + for (var i = 0; i < targets.Length && EbmlReader.TryRead (targets, i, targets.Length, out var child); i = child.End) { + if (child.Id is 0x63C5 or 0x63C9 or 0x63C4 or 0x63C6 && targets.Slice (child.DataOffset, (int)child.DataLength).IndexOfAnyExcept ((byte)0) >= 0) + return true; + } + + return false; + } + + // The Tags that target a chapter, attachment, track or edition, as bytes. + static List OtherItemTags (byte[] tagsElement) + { + var found = new List (); + if (tagsElement.Length == 0 || !EbmlReader.TryRead (tagsElement, 0, tagsElement.Length, out var tags)) + return found; + var body = tagsElement.AsSpan (tags.DataOffset, (int)tags.DataLength); + for (var at = 0; at < body.Length && EbmlReader.TryRead (body, at, body.Length, out var tag); at = tag.End) { + var inner = body.Slice (tag.DataOffset, (int)tag.DataLength); + for (var i = 0; i < inner.Length && EbmlReader.TryRead (inner, i, inner.Length, out var child); i = child.End) { + if (child.Id == MatroskaIds.Targets && IsOtherItems (inner.Slice (child.DataOffset, (int)child.DataLength))) + found.Add (Convert.ToHexString (body[at..tag.End])); + } + } + + return found; + } + + static SortedDictionary> ModelLayout (byte[] tagsElement) + { + var layout = new SortedDictionary> (); + if (tagsElement.Length == 0 || !EbmlReader.TryRead (tagsElement, 0, tagsElement.Length, out var tags)) + return layout; + var body = tagsElement.AsSpan (tags.DataOffset, (int)tags.DataLength); + for (var at = 0; at < body.Length && EbmlReader.TryRead (body, at, body.Length, out var tag); at = tag.End) { + if (tag.Id != MatroskaIds.Tag) + continue; + var inner = body.Slice (tag.DataOffset, (int)tag.DataLength); + ulong level = 50; + var other = false; + var entries = new List (); + for (var i = 0; i < inner.Length && EbmlReader.TryRead (inner, i, inner.Length, out var child); i = child.End) { + var payload = inner.Slice (child.DataOffset, (int)child.DataLength); + if (child.Id == MatroskaIds.Targets) { + level = TargetLevel (payload) ?? 50; + other = IsOtherItems (payload); + } else if (child.Id == MatroskaIds.SimpleTag) { + entries.Add (ModelTagOf (payload)); + } + } + + if (other) + continue; + + if (!layout.TryGetValue (level, out var list)) + layout[level] = list = []; + list.AddRange (entries); + } + + return layout; + } + + static ModelTag ModelTagOf (ReadOnlySpan simple) + { + var name = ""; + var text = ""; + var sorts = new List (); + for (var i = 0; i < simple.Length && EbmlReader.TryRead (simple, i, simple.Length, out var child); i = child.End) { + var payload = simple.Slice (child.DataOffset, (int)child.DataLength); + if (child.Id == MatroskaIds.TagName) + name = Encoding.UTF8.GetString (payload); + else if (child.Id == MatroskaIds.TagString) + text = Encoding.UTF8.GetString (payload); + else if (child.Id == MatroskaIds.SimpleTag) { + var inner = ModelTagOf (payload); + if (inner.Name == "SORT_WITH") + sorts.Add (inner.Text); + } + } + + return new ModelTag (name, text, sorts); + } + + // The 432 ownership shapes with distinct texts per level, the same 432 with one text repeated at every + // level, and the shapes the reviews built (ffmpeg's untargeted Tag, repeats, value-less sorts at 60/70). + static IEnumerable<(string Name, byte[] Data)> ModelShapes (SortPair pair) + { + foreach (var shape in OwnershipShapes (pair)) + yield return shape; + foreach (var (name, data) in OwnershipShapes (pair, sameText: true)) + yield return ($"same {name}", data); + // Empty texts (E): an empty value is a value, and "" is the value read only when no value holds text. + foreach (var pattern in new[] { "EBC", "AEC", "ABE", "EEC", "AEE", "EEE", "EAA", "AEA" }) { + foreach (var (name, data) in OwnershipShapes (pair, pattern: pattern, fillerOnly: true)) + yield return ($"empty {name}", data); + } + + foreach (var pattern in new[] { "AAB", "ABA", "ABB" }) { + foreach (var (name, data) in OwnershipShapes (pair, pattern: pattern)) + yield return ($"mixed {name}", data); + } + + // Tags of other items, holding the pair's names, beside every distinct shape with a track title. + byte[][] others = [ + ChapterTag (30, Chapter (1), Simple (pair.Value, "Ch"), Simple (pair.Flat, "ch")), + ChapterTag (50, Element (0x63C6, new byte[] { 1 }), Simple (pair.Value, "At"), Simple (pair.Flat, "at")), + ChapterTag (30, Track (1), Simple (pair.Value, "Tr"), Simple (pair.Flat, "tr")), + ChapterTag (50, Edition (1), Simple (pair.Value, "Ed"), SimpleSorted (pair.Value, "Ed2", "ed2"), Simple (pair.Flat, "ed")), + ]; + foreach (var (name, data) in OwnershipShapes (pair, others: others)) + yield return ($"with other items {name}", data); + + // Two values at a level: a run needs the whole list to repeat. + yield return ("two values at 50", FileWith (Tags (Tag (50, Simple (pair.Value, "X"), Simple (pair.Value, "Y"), Simple (pair.Flat, "xy")), Tag (30, Simple ("TITLE", "Song"), Simple (pair.Value, "X"))))); + yield return ("two values repeated", FileWith (Tags (Tag (50, Simple (pair.Value, "X"), Simple (pair.Value, "Y"), Simple (pair.Flat, "xy")), Tag (30, Simple ("TITLE", "Song"), Simple (pair.Value, "X"), Simple (pair.Value, "Y"))))); + yield return ("two values, the first repeated at 70", FileWith (Tags (Tag (70, Simple (pair.Value, "X"), Simple (pair.Flat, "x70")), Tag (50, Simple (pair.Value, "X"), Simple (pair.Value, "Y")), Tag (30, Simple ("TITLE", "Song"))))); + yield return ("value-less 70 album artist sort", FileWith (Tags (Tag (70, Simple (pair.Flat, "x")), Tag (50, Simple (pair.Value, "Band")), Tag (30, Simple ("ARTIST", "Solo"), Simple ("TITLE", "Song"))))); + yield return ("value-less 60 sort over an album", FileWith (Tags (Tag (60, Simple (pair.Flat, "x")), Tag (50, Simple (pair.Value, "Band"), Simple ("TITLE", "Alb"))))); + static byte[] Untargeted (params byte[][] simple) => Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), Concat (simple))); + yield return ("ffmpeg untargeted", FileWith (Tags (Untargeted (Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort"), + Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "Bach, J"), Simple ("ALBUM_ARTIST", "AA"), Simple ("ALBUM_ARTIST_SORT", "aa sort"))))); + yield return ("50 + 30 title", FileWith (Tags (Tag (50, Simple ("TITLE", "Alb"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort")), Tag (30, Simple ("TITLE", "Song"))))); + yield return ("nested 50 + 30 title", FileWith (Tags (Tag (50, Simple ("TITLE", "Alb"), SimpleSorted ("ARTIST", "Ada", "ada nested")), Tag (30, Simple ("TITLE", "Song"))))); + yield return ("R1 different composers", FileWith (Tags (Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "Bach, J")), Tag (30, Simple ("TITLE", "Song"), Simple ("COMPOSER", "Mozart"))))); + yield return ("R2 different artists", FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort")), Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Solo"))))); + yield return ("R3 different album artists", FileWith (Tags (Tag (50, Simple ("ALBUM_ARTIST", "AA50"), Simple ("ALBUM_ARTIST_SORT", "aa50 sort")), Tag (30, Simple ("TITLE", "Song"), Simple ("ALBUM_ARTIST", "AA30"))))); + yield return ("R4 value-less 50 sort", FileWith (Tags (Tag (50, Simple ("TITLE", "Alb"), Simple ("COMPOSER_SORT", "Bach, J")), Tag (30, Simple ("TITLE", "Song"), Simple ("COMPOSER", "Bach"))))); + yield return ("R5 repeated artist", FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort")), Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"))))); + yield return ("R5 repeated composer", FileWith (Tags (Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "Bach, J")), Tag (30, Simple ("TITLE", "Song"), Simple ("COMPOSER", "Bach"))))); + yield return ("R5 repeated album artist", FileWith (Tags (Tag (50, Simple ("ALBUM_ARTIST", "X"), Simple ("ALBUM_ARTIST_SORT", "x sort")), Tag (30, Simple ("TITLE", "Song"), Simple ("ALBUM_ARTIST", "X"))))); + yield return ("value-less 70 sort above the track", FileWith (Tags (Tag (70, Simple ("ARTIST_SORT", "x")), Tag (50, Simple ("TITLE", "Alb")), Tag (30, Simple ("ARTIST", "Solo"), Simple ("TITLE", "Song"))))); + yield return ("value-less 60 sort above the track", FileWith (Tags (Tag (60, Simple ("ARTIST_SORT", "x")), Tag (50, Simple ("TITLE", "Alb")), Tag (30, Simple ("ARTIST", "Solo"), Simple ("TITLE", "Song"))))); + yield return ("performers with sorts", FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada")), Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Solo"), Simple ("ARTIST_SORT", "solo"))))); + yield return ("70 collection artist", FileWith (Tags (Tag (70, Simple ("ARTIST", "Coll"), Simple ("ARTIST_SORT", "coll")), Tag (30, Simple ("TITLE", "Song"))))); + } + + [TestMethod] + public void SortModel_ValuesInAnotherOrder_AreAnotherValue () + { + // The same artists in another order are another list: the album's ARTIST_SORT is not the track's. + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "B"), Simple ("ARTIST", "A"), Simple ("ARTIST_SORT", "b, a")), + Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "A"), Simple ("ARTIST", "B"))))).File!.Tag; + Assert.IsNull (tag.ArtistSort); + + var same = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "A"), Simple ("ARTIST", "B"), Simple ("ARTIST_SORT", "a, b")), + Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "A"), Simple ("ARTIST", "B"))))).File!.Tag; + Assert.AreEqual ("a, b", same.ArtistSort); + } + + [TestMethod] + public void SortModel_RunsCompareTheDefaultLanguageTexts_EmptyOnesIncluded () + { + // A run compares the values the getter reads: the default-language ones, in order, an empty one included. + var languages = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST", "Ada-fr", isDefault: false), Simple ("ARTIST_SORT", "ada")), + Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"))))).File!.Tag; + Assert.AreEqual ("ada", languages.ArtistSort); + + var empty = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", ""), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada")), + Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"))))).File!.Tag; + Assert.IsNull (empty.ArtistSort); + } + + [TestMethod] + public void SortModel_FlatSet_GoesInTheValuesTag () + { + // One copy, beside the value it sorts: a value-less broader Tag's copy is replaced by one in the value's Tag. + var original = FileWith (Tags (Tag (50, Simple ("TITLE", "Alb"), Simple ("ARTIST_SORT", "old")), Tag (30, Simple ("TITLE", "Song"), Simple ("ARTIST", "Solo")))); + var tag = MatroskaFile.Read (original).File!.Tag; + Assert.AreEqual ("old", tag.ArtistSort); + + tag.ArtistSort = "new"; + + var bytes = FileWith (tag.Render ().ToArray ()); + Assert.IsTrue (FileTargetHas (bytes, 30, "ARTIST_SORT")); + Assert.IsFalse (FileTargetHas (bytes, 50, "ARTIST_SORT")); + Assert.AreEqual ("new", MatroskaFile.Read (bytes).File!.Tag.ArtistSort); + } + + [TestMethod] + public void SortSet_DoesNotMoveWhereLaterFieldsLand () + { + // The track's ARTIST_SORT goes beside its ARTIST at 30; a new field still goes to 50, as it did before. + foreach (var setFirst in new[] { false, true }) { + var original = FileWith ( + Tags (Tag (50, Simple ("GENRE", "Rock")), Tag (30, Simple ("ARTIST", "Solo"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + if (setFirst) + parsed.Tag.ArtistSort = "solo"; + parsed.Tag.Conductor = "Cond"; + + SaveAndReread (parsed, original, out var bytes); + Assert.IsTrue (FileTargetHas (bytes, 50, "CONDUCTOR"), $"sort set first: {setFirst}"); + } + } + + [TestMethod] + public void SortSet_ReplacesTheFlatCopyInPlace () + { + var tag = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "bach"), Simple ("GENRE", "Rock"))))).File!.Tag; + var before = tag.Render ().ToArray (); + + tag.ComposerSort = "BACH"; + + var after = tag.Render ().ToArray (); + Assert.AreEqual (before.Length, after.Length); + Assert.IsTrue (after.AsSpan ().IndexOf ("BACH"u8) < after.AsSpan ().IndexOf ("GENRE"u8), "the sort keeps its place"); + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSortNameTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortNameTests.cs new file mode 100644 index 00000000..bbc72959 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortNameTests.cs @@ -0,0 +1,436 @@ +// 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.Matroska; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Matroska; + +// AlbumArtistSort is SORT_WITH on the ARTIST that AlbumArtists reads; ComposerSort is SORT_WITH on the +// COMPOSER that Composers reads. Each falls back to a flat ALBUM_ARTIST_SORT / COMPOSER_SORT tag. +public partial class MatroskaFileTests +{ + static readonly string[] SortTheBand = ["The Band"]; + static readonly string[] SortBach = ["Bach"]; + + [TestMethod] + public void Read_NestedSortWith_FillsAlbumArtistAndComposerSort () + { + var file = FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "Band, The")), + Tag (30, + SimpleSorted ("ARTIST", "Ada", "ada"), + SimpleSorted ("COMPOSER", "J. S. Bach", "Bach, Johann Sebastian")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("ada", tag.ArtistSort); + Assert.AreEqual ("Bach, Johann Sebastian", tag.ComposerSort); + } + + [TestMethod] + public void Read_FlatSortNames_FillAlbumArtistAndComposerSort () + { + var file = FileWith (Tags ( + Tag (50, Simple ("ARTIST", "The Band"), Simple ("ALBUM_ARTIST_SORT", "flat band")), + Tag (30, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "flat bach")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + Assert.AreEqual ("flat band", tag.AlbumArtistSort); + Assert.AreEqual ("flat bach", tag.ComposerSort); + } + + [TestMethod] + public void Read_NestedSort_WinsOverTheFlatName () + { + var file = FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "nested band"), Simple ("ALBUM_ARTIST_SORT", "flat band")), + Tag (30, SimpleSorted ("COMPOSER", "Bach", "nested bach"), Simple ("COMPOSER_SORT", "flat bach")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + Assert.AreEqual ("nested band", tag.AlbumArtistSort); + Assert.AreEqual ("nested bach", tag.ComposerSort); + } + + [TestMethod] + public void Read_FlatComposerSort_InheritsFromTheAlbum () + { + var file = FileWith (Tags ( + Tag (50, Simple ("COMPOSER_SORT", "album bach")), + Tag (30, Simple ("COMPOSER", "Bach")))); + + Assert.AreEqual ("album bach", MatroskaFile.Read (file).File!.Tag.ComposerSort); + } + + [TestMethod] + public void Read_TrackArtistSort_IsNotTheAlbumArtistSort () + { + var file = FileWith (Tags ( + Tag (50, Simple ("ARTIST", "The Band")), + Tag (30, SimpleSorted ("ARTIST", "Ada", "ada"), Simple ("ALBUM_ARTIST_SORT", "track level")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + Assert.AreEqual ("ada", tag.ArtistSort); + Assert.IsNull (tag.AlbumArtistSort); + } + + [TestMethod] + public void Read_AlbumLevelOnly_AlbumArtistSortIsTheArtistSort () + { + // With no track-level tags the album ARTIST is both the artist and the album artist. + var file = FileWith (Tags (Tag (50, SimpleSorted ("ARTIST", "The Band", "Band, The")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + Assert.AreEqual ("Band, The", tag.ArtistSort); + } + + [TestMethod] + public void Read_CollectionArtist_SuppliesAlbumArtistSortWhenTheAlbumIsTheItem () + { + var file = FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "The Band", "Band, The")), + Tag (50, Simple ("TITLE", "The Album")))); + + var tag = MatroskaFile.Read (file).File!.Tag; + + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + Assert.AreEqual ("Band, The", tag.AlbumArtistSort); + + tag.AlbumArtistSort = "other"; + + Assert.AreEqual ("other", tag.AlbumArtistSort); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + + tag.AlbumArtistSort = null; + + Assert.IsNull (tag.AlbumArtistSort); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + } + + [TestMethod] + public void SortSet_ReplacesTheNestedAlbumArtistAndComposerSort () + { + var file = FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "band")), + Tag (30, + SimpleSorted ("ARTIST", "Ada", "ada"), + SimpleSorted ("COMPOSER", "Bach", "bach")))); + var tag = MatroskaFile.Read (file).File!.Tag; + + tag.AlbumArtistSort = "other band"; + tag.ComposerSort = "other bach"; + + Assert.AreEqual ("other band", tag.AlbumArtistSort); + Assert.AreEqual ("other bach", tag.ComposerSort); + Assert.AreEqual ("ada", tag.ArtistSort); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + CollectionAssert.AreEqual (SortBach, tag.Composers); + Assert.AreEqual ("Ada", tag.Artist); + + tag.AlbumArtistSort = null; + tag.ComposerSort = null; + + Assert.IsNull (tag.AlbumArtistSort); + Assert.IsNull (tag.ComposerSort); + Assert.AreEqual ("ada", tag.ArtistSort); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + CollectionAssert.AreEqual (SortBach, tag.Composers); + } + + [TestMethod] + public void SortSet_WithoutTheParent_WritesTheFlatName () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "The Song")))); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.AlbumArtistSort = "band"; + parsed.Tag.ComposerSort = "bach"; + + Assert.AreEqual ("band", parsed.Tag.AlbumArtistSort); + Assert.AreEqual ("bach", parsed.Tag.ComposerSort); + Assert.IsEmpty (parsed.Tag.AlbumArtists); + Assert.IsEmpty (parsed.Tag.Composers); + Assert.IsNull (parsed.Tag.ArtistSort); + + var rendered = parsed.Tag.Render ().ToArray (); + Assert.AreEqual (1, CountOf (rendered, "ALBUM_ARTIST_SORT"u8.ToArray ())); + Assert.AreEqual (1, CountOf (rendered, "COMPOSER_SORT"u8.ToArray ())); + Assert.AreEqual (0, CountOf (rendered, "SORT_WITH"u8.ToArray ())); + + var again = SaveAndRead (parsed, original); + Assert.AreEqual ("band", again.Tag.AlbumArtistSort); + Assert.AreEqual ("bach", again.Tag.ComposerSort); + Assert.AreEqual ("The Song", again.Tag.Title); + Assert.IsEmpty (again.Tag.AlbumArtists); + Assert.IsEmpty (again.Tag.Composers); + } + + [TestMethod] + public void SortSet_WithoutTheParent_PutsTheAlbumArtistSortAtTheAlbum () + { + // A flat album-artist sort written at the track would be invisible to the getter. + var parsed = MatroskaFile.Read (FileWith (Tags (Tag (30, Simple ("TITLE", "The Song"))))).File!; + + parsed.Tag.AlbumArtistSort = "band"; + + var rendered = MatroskaFile.Read (FileWith (parsed.Tag.Render ().ToArray ())).File!.Tag; + Assert.AreEqual ("band", rendered.AlbumArtistSort); + var trackOnly = MatroskaFile.Read (FileWith (Tags ( + Tag (30, Simple ("TITLE", "The Song"), Simple ("ALBUM_ARTIST_SORT", "band"))))).File!.Tag; + Assert.IsNull (trackOnly.AlbumArtistSort); + } + + [TestMethod] + public void SortSet_ParentWithoutNestedSort_KeepsTheParent () + { + var original = FileWith (Tags ( + Tag (50, Simple ("ARTIST", "The Band")), + Tag (30, Simple ("ARTIST", "Ada"), Simple ("COMPOSER", "Bach")))); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.AlbumArtistSort = "band"; + parsed.Tag.ComposerSort = "bach"; + + var again = SaveAndRead (parsed, original); + Assert.AreEqual ("band", again.Tag.AlbumArtistSort); + Assert.AreEqual ("bach", again.Tag.ComposerSort); + Assert.IsNull (again.Tag.ArtistSort); + Assert.AreEqual ("Ada", again.Tag.Artist); + CollectionAssert.AreEqual (SortTheBand, again.Tag.AlbumArtists); + CollectionAssert.AreEqual (SortBach, again.Tag.Composers); + } + + [TestMethod] + public void SortSet_Null_ClearsEveryVisibleAlbumArtistSort () + { + var original = FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "nested"), Simple ("ALBUM_ARTIST_SORT", "flat")), + Tag (30, Simple ("ARTIST", "Ada")))); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("nested", parsed.Tag.AlbumArtistSort); + + parsed.Tag.AlbumArtistSort = null; + + Assert.IsNull (parsed.Tag.AlbumArtistSort); + var again = SaveAndRead (parsed, original); + Assert.IsNull (again.Tag.AlbumArtistSort); + CollectionAssert.AreEqual (SortTheBand, again.Tag.AlbumArtists); + Assert.AreEqual ("Ada", again.Tag.Artist); + } + + [TestMethod] + public void SortSet_Null_ClearsAFlatAlbumArtistSortAboveTheAlbumItem () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (70, Simple ("ALBUM_ARTIST_SORT", "collection")), + Tag (50, Simple ("ARTIST", "The Band"), Simple ("ALBUM_ARTIST_SORT", "album"))))).File!.Tag; + Assert.AreEqual ("album", tag.AlbumArtistSort); + + tag.AlbumArtistSort = null; + + Assert.IsNull (tag.AlbumArtistSort); + CollectionAssert.AreEqual (SortTheBand, tag.AlbumArtists); + } + + [TestMethod] + public void SortSet_Null_ClearsEveryVisibleComposerSort () + { + var original = FileWith (Tags ( + Tag (50, Simple ("COMPOSER_SORT", "album flat")), + Tag (30, SimpleSorted ("COMPOSER", "Bach", "nested"), Simple ("COMPOSER_SORT", "track flat")))); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("nested", parsed.Tag.ComposerSort); + + parsed.Tag.ComposerSort = null; + + Assert.IsNull (parsed.Tag.ComposerSort); + var again = SaveAndRead (parsed, original); + Assert.IsNull (again.Tag.ComposerSort); + CollectionAssert.AreEqual (SortBach, again.Tag.Composers); + } + + [TestMethod] + public void SortSet_AlbumArtistSort_LeavesTheTrackArtistSort () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "band")), + Tag (30, SimpleSorted ("ARTIST", "Ada", "ada"))))).File!.Tag; + + tag.ArtistSort = "artist"; + tag.AlbumArtistSort = "album artist"; + + Assert.AreEqual ("artist", tag.ArtistSort); + Assert.AreEqual ("album artist", tag.AlbumArtistSort); + + tag.ArtistSort = null; + + Assert.IsNull (tag.ArtistSort); + Assert.AreEqual ("album artist", tag.AlbumArtistSort); + } + + [TestMethod] + public void Clear_RemovesAlbumArtistAndComposerSort () + { + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "band")), + Tag (30, SimpleSorted ("COMPOSER", "Bach", "bach"))))).File!.Tag; + + tag.Clear (); + + Assert.IsNull (tag.AlbumArtistSort); + Assert.IsNull (tag.ComposerSort); + } + + [TestMethod] + public void MediaFileView_ForwardsAlbumArtistAndComposerSort () + { + var file = FileWith (Tags ( + Tag (50, SimpleSorted ("ARTIST", "The Band", "band")), + Tag (30, SimpleSorted ("COMPOSER", "Bach", "bach")))); + var fs = new MockFileSystem (); + fs.AddFile ("/sort.mkv", file); + + var read = MediaFile.Read ("/sort.mkv", fs); + + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.AreEqual (MediaFormat.Matroska, read.Format); + Assert.AreEqual ("band", read.Tag!.AlbumArtistSort); + Assert.AreEqual ("bach", read.Tag.ComposerSort); + } + + [TestMethod] + public void CopyTo_CarriesAlbumArtistAndComposerSortIntoMatroska () + { + var source = new VorbisComment { AlbumArtistSort = "band", ComposerSort = "bach" }; + var target = MatroskaFile.Read (FileWith (Tags (Tag (30, Simple ("TITLE", "The Song"))))).File!.Tag; + + source.CopyTo (target); + + Assert.AreEqual ("band", target.AlbumArtistSort); + Assert.AreEqual ("bach", target.ComposerSort); + } + + // The real-file round trip in MatroskaIntegrationTests, run on built files so CI covers it. + static readonly byte[] SortClusterMarker = [0x5A, 0xA5, 0x5A, 0xA5, 0x5A]; + + static byte[] NestedSortFile () => FileWith ( + Tags ( + Tag (50, Simple ("TITLE", "The Album"), SimpleSorted ("ARTIST", "The Band", "band")), + Tag (30, + Simple ("TITLE", "The Song"), + SimpleSorted ("ARTIST", "Ada", "ada"), + SimpleSorted ("COMPOSER", "Bach", "bach"))), + Master (0x1F43B675, SortClusterMarker)); + + static byte[] FlatSortFile () => FileWith ( + Tags ( + Tag (50, Simple ("TITLE", "The Album"), Simple ("ARTIST", "The Band"), Simple ("ALBUM_ARTIST_SORT", "band")), + Tag (30, Simple ("TITLE", "The Song"), Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "bach"))), + Master (0x1F43B675, SortClusterMarker)); + + static void AssertNestedSortSaved (byte[] saved) + { + Assert.AreEqual (1, CountOf (saved, SortClusterMarker)); + Assert.AreEqual (0, CountOf (saved, "ALBUM_ARTIST_SORT"u8.ToArray ())); + Assert.AreEqual (0, CountOf (saved, "COMPOSER_SORT"u8.ToArray ())); + Assert.AreEqual (3, CountOf (saved, "SORT_WITH"u8.ToArray ())); + Assert.AreEqual (1, CountOf (saved, Encoding.UTF8.GetBytes (MatroskaSortRoundTrip.AlbumArtistSort))); + Assert.AreEqual (1, CountOf (saved, Encoding.UTF8.GetBytes (MatroskaSortRoundTrip.ComposerSort))); + Assert.AreEqual (1, CountOf (saved, "ada"u8.ToArray ())); + } + + static void AssertFlatSortSaved (byte[] saved) + { + Assert.AreEqual (1, CountOf (saved, SortClusterMarker)); + Assert.AreEqual (1, CountOf (saved, "ALBUM_ARTIST_SORT"u8.ToArray ())); + Assert.AreEqual (1, CountOf (saved, "COMPOSER_SORT"u8.ToArray ())); + Assert.AreEqual (0, CountOf (saved, "SORT_WITH"u8.ToArray ())); + Assert.AreEqual (1, CountOf (saved, Encoding.UTF8.GetBytes (MatroskaSortRoundTrip.AlbumArtistSort))); + Assert.AreEqual (1, CountOf (saved, Encoding.UTF8.GetBytes (MatroskaSortRoundTrip.ComposerSort))); + } + + static string WriteTempMatroska (byte[] data) + { + var path = Path.Combine (Path.GetTempPath (), $"taglibsharp2-built-{Guid.NewGuid ():N}.mkv"); + File.WriteAllBytes (path, data); + return path; + } + + [TestMethod] + public void RoundTrip_NestedSortWith_OnDisk () + { + var path = WriteTempMatroska (NestedSortFile ()); + try { + MatroskaSortRoundTrip.VerifyOnCopy (path, AssertNestedSortSaved); + } finally { + File.Delete (path); + } + } + + [TestMethod] + public async Task RoundTrip_NestedSortWith_OnDiskAsync () + { + var path = WriteTempMatroska (NestedSortFile ()); + try { + await MatroskaSortRoundTrip.VerifyOnCopyAsync (path, AssertNestedSortSaved); + } finally { + File.Delete (path); + } + } + + [TestMethod] + public void RoundTrip_FlatSortNames_OnDisk () + { + var path = WriteTempMatroska (FlatSortFile ()); + try { + MatroskaSortRoundTrip.VerifyOnCopy (path, AssertFlatSortSaved); + } finally { + File.Delete (path); + } + } + + [TestMethod] + public async Task RoundTrip_FlatSortNames_OnDiskAsync () + { + var path = WriteTempMatroska (FlatSortFile ()); + try { + await MatroskaSortRoundTrip.VerifyOnCopyAsync (path, AssertFlatSortSaved); + } finally { + File.Delete (path); + } + } + + [TestMethod] + public void RoundTrip_WithoutParents_OnDisk () + { + var path = WriteTempMatroska (FileWith ( + Tags (Tag (30, Simple ("TITLE", "The Song"))), + Master (0x1F43B675, SortClusterMarker))); + try { + MatroskaSortRoundTrip.VerifyOnCopy (path, AssertFlatSortSaved); + } finally { + File.Delete (path); + } + } + + static MatroskaFile SaveAndRead (MatroskaFile parsed, byte[] original) + { + var fs = new MockFileSystem (); + fs.AddFile ("/sort.mkv", original); + var saved = parsed.SaveToFile ("/sort.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var again = MatroskaFile.Read (fs.ReadAllBytes ("/sort.mkv")); + Assert.IsTrue (again.IsSuccess, again.Error); + return again.File!; + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSortOwnershipTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortOwnershipTests.cs new file mode 100644 index 00000000..3ba27478 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSortOwnershipTests.cs @@ -0,0 +1,523 @@ +// 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.Matroska; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Matroska; + +// Invariant: a sort sits with the value it sorts. A flat *_SORT belongs to the value in its own Tag +// (the ffmpeg convention) and is inherited by narrower levels (tagging.html, "Target types") up to the +// next broader Tag that holds a value of its own. Writing a sort or a value never changes a value or a +// sort that belongs to another level. +public partial class MatroskaFileTests +{ + enum Getter { Artist, AlbumArtistByArtist, Composer, AlbumArtistByName } + + sealed record SortPair (string Name, string Value, string Flat, Getter Getter, bool WithAda); + + static readonly SortPair[] SortPairs = [ + new ("ARTIST", "ARTIST", "ARTIST_SORT", Getter.Artist, false), + new ("ARTIST for the album", "ARTIST", "ALBUM_ARTIST_SORT", Getter.AlbumArtistByArtist, false), + new ("COMPOSER", "COMPOSER", "COMPOSER_SORT", Getter.Composer, false), + new ("ALBUM_ARTIST", "ALBUM_ARTIST", "ALBUM_ARTIST_SORT", Getter.AlbumArtistByName, true), + ]; + + // Each level 30, 50, 70: absent, value, value + flat sort, value with SORT_WITH, both, flat sort only. + static IEnumerable<(string Name, byte[] Data)> OwnershipShapes (SortPair pair, bool sameText = false, string? pattern = null, byte[][]? others = null, bool fillerOnly = false) + { + string[] kinds = ["-", "v", "vf", "n", "nf", "f"]; + ulong[] levels = [30, 50, 70]; + for (var i = 0; i < 6 * 6 * 6 * 2; i++) { + var picks = new[] { i % 6, i / 6 % 6, i / 36 % 6 }; + var filler = i / 216 == 1; + if ((others is not null || fillerOnly) && !filler) + continue; + var blocks = new List (); + for (var at = 2; at >= 0; at--) { + var level = levels[at]; + var simple = new List (); + var kind = kinds[picks[at]]; + var text = pattern is not null ? (pattern[at] == 'E' ? "" : $"{pair.Value}{pattern[at]}") : sameText ? pair.Value : $"{pair.Value}{level}"; + if (kind is "v" or "vf") + simple.Add (Simple (pair.Value, text)); + if (kind is "n" or "nf") + simple.Add (SimpleSorted (pair.Value, text, $"n{level}")); + if (kind is "vf" or "nf" or "f") + simple.Add (Simple (pair.Flat, $"f{level}")); + if (level == 50 && pair.WithAda) + simple.Add (Simple ("ARTIST", "Ada")); + if (level == 30 && filler) + simple.Add (Simple ("TITLE", "Song")); + if (simple.Count > 0) + blocks.Add (Tag (level, [.. simple])); + } + + if (blocks.Count == 0) + continue; + if (others is not null) + blocks.AddRange (others); + yield return ($"{pattern}30={kinds[picks[0]]} 50={kinds[picks[1]]} 70={kinds[picks[2]]} filler={filler}", FileWith (Tags ([.. blocks]))); + } + } + + static string? ReadSort (MatroskaTag tag, SortPair pair) => pair.Getter switch { + Getter.Artist => tag.ArtistSort, + Getter.Composer => tag.ComposerSort, + _ => tag.AlbumArtistSort, + }; + + static ulong? TargetLevel (ReadOnlySpan targets) + { + for (var i = 0; i < targets.Length && EbmlReader.TryRead (targets, i, targets.Length, out var child); i = child.End) { + if (child.Id == MatroskaIds.TargetTypeValue) + return EbmlReader.ReadUInt (targets.Slice (child.DataOffset, (int)child.DataLength)); + } + + return null; + } + + [TestMethod] + public void ArtistSort_OnAnFfmpegFile_AfterANewTrackArtist_StaysWithTheTrackArtist () + { + // ffmpeg's untargeted Tag holds ARTIST and its ARTIST_SORT. A track ARTIST at 30 is a different + // value, so its sort goes beside it and the album's pair is kept. + var original = FileWith ( + Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), + Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort")))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.Artist = "Solo"; + Assert.IsNull (parsed.Tag.ArtistSort, "Ada's sort is not Solo's"); + parsed.Tag.ArtistSort = "Solo, X"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("Solo", again.Artist); + Assert.AreEqual ("Solo, X", again.ArtistSort); + Assert.IsTrue (FileTargetHas (bytes, 30, "ARTIST_SORT")); + Assert.IsTrue (HasTagString (bytes, "Ada sort"), "the album's sort is kept"); + + again.ArtistSort = null; + Assert.IsNull (again.ArtistSort); + Assert.IsTrue (HasTagString (again.Render ().ToArray (), "Ada sort"), "a clear keeps the album's sort"); + } + + [TestMethod] + public void ItemField_InheritedFromACollection_IsWrittenAtTheAlbum () + { + // A target broader than the album is not where ordinary fields are written: the set goes to 50 + // and shadows the collection value, which stays as it was. + foreach (var (name, set, get) in new (string, Action, Func)[] { + ("GENRE", t => t.Genre = "Jazz", t => t.Genre), + ("COMPOSER", t => t.Composers = ["Jazz"], t => t.Composers.FirstOrDefault ()), + }) { + var original = FileWith (Tags (Tag (70, Simple (name, "Rock")), Tag (30, Simple ("TITLE", "Song"))), Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + set (parsed.Tag); + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("Jazz", get (again), name); + Assert.IsTrue (FileTargetHas (bytes, 70, name), name); + Assert.IsTrue (HasTagString (bytes, "Rock"), $"{name}: the collection value is kept"); + Assert.AreEqual (2, CountOf (bytes, TagNameElement (name)), name); + Assert.IsTrue (FileTargetHas (bytes, 30, name) || FileTargetHas (bytes, 50, name), name); + } + } + + [TestMethod] + public void NewField_BesideAReadEmptyTrackTag_GoesToTheTrack () + { + // A Tag that was empty when read is kept (#132) and is the item, so it is not skipped like an + // ARTIST-only copy. + var original = FileWith ( + Tags (Tag (50, Simple ("GENRE", "Rock")), Master (0x7373, Master (0x63C0, Element (0x68CA, new byte[] { 30 })))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.Conductor = "Cond"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("Cond", again.Conductor); + Assert.IsTrue (FileTargetHas (bytes, 30, "CONDUCTOR")); + } + + [TestMethod] + public void NewField_AfterAClearEmptiesTheTrackTag_GoesToTheAlbum () + { + var original = FileWith ( + Tags (Tag (50, Simple ("TITLE", "The Album")), Tag (30, Simple ("TITLE", "The Song"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + parsed.Tag.Title = null; + parsed.Tag.Conductor = "Cond"; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("Cond", again.Conductor); + CollectionAssert.AreEqual (new ulong[] { 50 }, TargetLevelsInOrder (bytes)); + } + + [TestMethod] + public void FlatSort_ForACollectionValue_IsWrittenBelowIt () + { + // A target broader than the album is not where ordinary fields go; the sort is written below its + // value, where it still pairs with it, and the collection Tag is left as it was. + foreach (var (name, flat, set, get) in new (string, string, Action, Func)[] { + ("ARTIST", "ARTIST_SORT", t => t.ArtistSort = "NEW", t => t.ArtistSort), + ("COMPOSER", "COMPOSER_SORT", t => t.ComposerSort = "NEW", t => t.ComposerSort), + }) { + var original = FileWith (Tags (Tag (70, Simple (name, "Collection")), Tag (30, Simple ("TITLE", "Song"))), Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + + set (parsed.Tag); + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("NEW", get (again), name); + Assert.IsFalse (FileTargetHas (bytes, 70, flat), name); + } + } + + [TestMethod] + public void SortSplit_CarriesTheFlatSortsWithEachCopy () + { + // An empty SORT_WITH leaves the flat sorts in charge. The track copy repeats the value, so ARTIST_SORT + // still reads; a copy from above the album takes ALBUM_ARTIST_SORT; new fields go beside the others. + var single = FileWith ( + Tags (Tag (50, SimpleSorted ("ARTIST", "The Band", ""), Simple ("ARTIST_SORT", "flat artist"), Simple ("GENRE", "Rock"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (single).File!; + Assert.AreEqual ("flat artist", parsed.Tag.ArtistSort); + + parsed.Tag.AlbumArtistSort = "album"; + parsed.Tag.Conductor = "Cond"; + + var again = SaveAndReread (parsed, single, out var bytes); + Assert.AreEqual ("flat artist", again.ArtistSort); + Assert.AreEqual ("album", again.AlbumArtistSort); + Assert.IsTrue (FileTargetHas (bytes, 50, "CONDUCTOR")); + Assert.IsFalse (FileTargetHas (bytes, 30, "CONDUCTOR")); + + var collection = FileWith ( + Tags (Tag (70, SimpleSorted ("ARTIST", "The Band", ""), Simple ("ALBUM_ARTIST_SORT", "flat album")), Tag (50, Simple ("TITLE", "The Album"))), + Master (0x1F43B675, SortClusterMarker)); + var fromCollection = MatroskaFile.Read (collection).File!; + Assert.AreEqual ("flat album", fromCollection.Tag.AlbumArtistSort); + + fromCollection.Tag.ArtistSort = "track"; + + var reread = SaveAndReread (fromCollection, collection, out _); + Assert.AreEqual ("track", reread.ArtistSort); + Assert.AreEqual ("flat album", reread.AlbumArtistSort); + } + + [TestMethod] + public void ValueClear_TakesTheFlatSortsOfItsTagWithIt () + { + var album = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "A50"), Simple ("ARTIST_SORT", "a50 sort"), Simple ("ALBUM_ARTIST_SORT", "aa50 sort")), + Tag (30, Simple ("TITLE", "Song"))))).File!.Tag; + album.AlbumArtists = []; + Assert.IsNull (album.ArtistSort); + Assert.IsNull (album.AlbumArtistSort); + Assert.IsFalse (HasTagName (FileWith (album.Render ().ToArray ()), "ARTIST_SORT")); + Assert.IsFalse (HasTagName (FileWith (album.Render ().ToArray ()), "ALBUM_ARTIST_SORT")); + + var track = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada")), + Tag (30, Simple ("ARTIST", "Solo"), Simple ("ARTIST_SORT", "solo"))))).File!.Tag; + track.Artist = null; + Assert.AreEqual ("Ada", track.Artist); + Assert.AreEqual ("ada", track.ArtistSort, "the track now inherits the album's pair"); + Assert.IsFalse (HasTagString (FileWith (track.Render ().ToArray ()), "solo")); + + var titles = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("TITLE", "Album"), Simple ("ALBUM_SORT", "album sort")), + Tag (30, Simple ("TITLE", "Song"), Simple ("TITLE_SORT", "song sort"), Simple ("GENRE", "Rock"))))).File!.Tag; + titles.Title = null; + titles.Album = null; + Assert.IsNull (titles.TitleSort); + Assert.IsNull (titles.AlbumSort); + var rendered = FileWith (titles.Render ().ToArray ()); + Assert.IsFalse (HasTagName (rendered, "TITLE_SORT")); + Assert.IsFalse (HasTagName (rendered, "ALBUM_SORT")); + + var composers = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "bach")), + Tag (30, Simple ("TITLE", "Song"))))).File!.Tag; + composers.Composers = []; + Assert.IsNull (composers.ComposerSort); + Assert.IsFalse (HasTagName (FileWith (composers.Render ().ToArray ()), "COMPOSER_SORT")); + + // A sort with no value is not removed by clearing values that do not exist. + var orphan = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("TITLE", "Album"), Simple ("COMPOSER_SORT", "bach"))))).File!.Tag; + orphan.Composers = []; + Assert.AreEqual ("bach", orphan.ComposerSort); + } + + [TestMethod] + public void ValueSet_InATagWhoseSortTheTrackInherits_LeavesTheSortWithTheTrack () + { + // The 50 ARTIST_SORT has no ARTIST beside it, so the track's ARTIST inherits it. A new album ARTIST + // in that Tag would take it over; it moves to the track instead. + var original = FileWith ( + Tags (Tag (50, Simple ("TITLE", "Album"), Simple ("ARTIST_SORT", "track sort")), Tag (30, Simple ("ARTIST", "Solo"))), + Master (0x1F43B675, SortClusterMarker)); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("track sort", parsed.Tag.ArtistSort); + + parsed.Tag.AlbumArtists = ["Band"]; + + var again = SaveAndReread (parsed, original, out var bytes); + Assert.AreEqual ("track sort", again.ArtistSort); + Assert.AreEqual ("Band", string.Join ("|", again.AlbumArtists)); + Assert.IsTrue (FileTargetHas (bytes, 30, "ARTIST_SORT")); + Assert.IsFalse (FileTargetHas (bytes, 50, "ARTIST_SORT")); + } + + [TestMethod] + public void SortPairing_IsLinearInTheTags () + { + // Thousands of Tags at distinct TargetTypeValues, each with a flat sort the file controls. Pairing a + // sort visits each Tag a bounded number of times; a per-level rescan would visit them squared. + const int count = 3000; + var blocks = new List { + Tag (30, Simple ("ARTIST", "Solo"), Simple ("COMPOSER", "Bach"), Simple ("TITLE", "Song")), + }; + for (var i = 0; i < count; i++) { + var level = (ushort)(1000 + i); + var target = Master (0x63C0, Element (0x68CA, [(byte)(level >> 8), (byte)level])); + blocks.Add (Master (0x7373, Concat (target, + Simple ("ARTIST_SORT", $"a{i}"), Simple ("COMPOSER_SORT", $"c{i}"), Simple ("ALBUM_ARTIST_SORT", $"aa{i}")))); + } + + var data = Matroska (WideElement (0x18538067, WideElement (0x1254C367, Concat ([.. blocks])))); + Assert.IsTrue (MatroskaFile.Read (data).File!.Tag.Render ().Length > count * 20, "every Tag is read"); + foreach (var (name, op) in new (string, Action)[] { + ("ArtistSort get", t => _ = t.ArtistSort), + ("ArtistSort set", t => t.ArtistSort = "x"), + ("ArtistSort clear", t => t.ArtistSort = null), + ("ComposerSort set", t => t.ComposerSort = "x"), + ("ComposerSort clear", t => t.ComposerSort = null), + ("AlbumArtistSort set", t => t.AlbumArtistSort = "x"), + ("AlbumArtistSort clear", t => t.AlbumArtistSort = null), + ("Artist clear", t => t.Artist = null), + ("AlbumArtists set", t => t.AlbumArtists = ["Band"]), + ("Composers clear", t => t.Composers = []), + }) { + var tag = MatroskaFile.Read (data).File!.Tag; + MatroskaTag.LevelSteps = 0; + + op (tag); + + var steps = MatroskaTag.LevelSteps; + Assert.IsTrue (steps >= count, $"{name}: visited only {steps} Tags of {count}; the counter is not counting"); + Assert.IsTrue (steps <= 64L * count, $"{name}: visited {steps} Tags for {count}; pairing is not linear"); + } + } + + [TestMethod] + public void SortAndValueWrites_OnHostileAndEmptyFields_StayConsistent () + { + static byte[] Bare (string name) => Master (0x67C8, Element (0x45A3, Encoding.UTF8.GetBytes (name))); + static byte[] Nested (string name, string text, int depth) + { + var inner = Simple ("SORT_WITH", "deep"); + for (var i = 0; i < depth; i++) + inner = Master (0x67C8, Concat (Element (0x45A3, "SORT_WITH"u8), Element (0x4487, "d"u8), inner)); + return Master (0x67C8, Concat (Element (0x45A3, Encoding.UTF8.GetBytes (name)), Element (0x4487, Encoding.UTF8.GetBytes (text)), inner)); + } + + var emptyTarget = Master (0x63C0, Element (0x68CA, Array.Empty ())); + var shapes = new (string, byte[])[] { + ("empty ARTIST blocks the album's", FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada")), Tag (30, Simple ("ARTIST", ""))))), + ("ARTIST without a TagString", FileWith (Tags (Tag (50, Bare ("ARTIST"), Simple ("ARTIST_SORT", "flat")), Tag (30, Simple ("TITLE", "Song"))))), + ("empty TagName", FileWith (Tags (Tag (50, Bare (""), Simple ("ARTIST", "Ada"))))), + ("empty TargetTypeValue is 50", FileWith (Tags (Master (0x7373, Concat (emptyTarget, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada"))), Tag (30, Simple ("ARTIST", "Solo"))))), + ("empty SORT_WITH", FileWith (Tags (Tag (50, SimpleSorted ("ARTIST", "Ada", ""), SimpleSorted ("COMPOSER", "Bach", ""))))), + ("SORT_WITH without a TagString", FileWith (Tags (Tag (50, Master (0x67C8, Concat (Element (0x45A3, "ARTIST"u8), Element (0x4487, "Ada"u8), Bare ("SORT_WITH"))))))), + ("SORT_WITH nested 3 deep", FileWith (Tags (Tag (50, Nested ("ARTIST", "Ada", 3)), Tag (30, Simple ("TITLE", "Song"))))), + ("SORT_WITH nested 200 deep", FileWith (Tags (Tag (50, Nested ("COMPOSER", "Bach", 200), Nested ("ARTIST", "Ada", 200))))), + ("read-empty Tags only", FileWith (Tags (Master (0x7373, Master (0x63C0, Element (0x68CA, new byte[] { 30 }))), Master (0x7373, emptyTarget)))), + ("empty flat sorts", FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", ""), Simple ("ALBUM_ARTIST_SORT", ""), Simple ("COMPOSER_SORT", ""))))), + }; + var ops = new (string, Action)[] { + ("sorts set", t => { t.ArtistSort = "x"; t.AlbumArtistSort = "y"; t.ComposerSort = "z"; }), + ("sorts cleared", t => { t.ArtistSort = null; t.AlbumArtistSort = ""; t.ComposerSort = null; }), + ("values set", t => { t.Artist = "A"; t.AlbumArtists = ["B"]; t.Composers = ["C"]; }), + ("values cleared", t => { t.Artist = null; t.AlbumArtists = []; t.Composers = []; t.Title = null; }), + ("write back", t => { t.ArtistSort = t.ArtistSort; t.AlbumArtistSort = t.AlbumArtistSort; t.Artist = t.Artist; t.AlbumArtists = t.AlbumArtists; }), + }; + foreach (var (shape, data) in shapes) { + foreach (var (name, op) in ops) { + var label = $"{shape}: {name}"; + var read = MatroskaFile.Read (data); + Assert.IsTrue (read.IsSuccess, $"{label}: {read.Error}"); + var tag = read.File!.Tag; + + op (tag); + + var again = MatroskaFile.Read (FileWith (tag.Render ().ToArray ())); + Assert.IsTrue (again.IsSuccess, $"{label}: {again.Error}"); + var reread = again.File!.Tag; + Assert.AreEqual (tag.ArtistSort, reread.ArtistSort, label); + Assert.AreEqual (tag.AlbumArtistSort, reread.AlbumArtistSort, label); + Assert.AreEqual (tag.ComposerSort, reread.ComposerSort, label); + Assert.AreEqual (string.Join ("|", tag.AlbumArtists), string.Join ("|", reread.AlbumArtists), label); + if (name == "sorts set") { + Assert.AreEqual ("x", tag.ArtistSort, label); + Assert.AreEqual ("y", tag.AlbumArtistSort, label); + Assert.AreEqual ("z", tag.ComposerSort, label); + } + + if (name == "sorts cleared") { + Assert.IsNull (tag.ArtistSort, label); + Assert.IsNull (tag.AlbumArtistSort, label); + Assert.IsNull (tag.ComposerSort, label); + } + } + } + } + + [TestMethod] + public void ValueClear_OfARepeat_LeavesTheBroaderValuesSort () + { + // The 70 ARTIST still applies to the track once the album's repeat goes (tagging.html, "Target types"), so + // its own ARTIST_SORT stays with it: a clear takes its own Tag's sorts and the value-less ones above it. + foreach (var albumArtistSort in new[] { false, true }) { + var flat = albumArtistSort ? "ALBUM_ARTIST_SORT" : "ARTIST_SORT"; + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (70, Simple ("ARTIST", "Ada"), Simple (flat, "x")), + Tag (50, Simple ("ARTIST", "Ada"), Simple ("TITLE", "Al")), + Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + var before = albumArtistSort ? tag.AlbumArtistSort : tag.ArtistSort; + + tag.AlbumArtists = []; + + var again = MatroskaFile.Read (FileWith (tag.Render ().ToArray ())).File!.Tag; + Assert.AreEqual ("Ada", again.Artist); + Assert.AreEqual ("x", before); + Assert.AreEqual ("x", albumArtistSort ? FirstTagString (tag, 70, flat) : again.ArtistSort, flat); + } + } + + [TestMethod] + public void ValueSet_EqualToTheBroaderValue_RepeatsItsSortWith () + { + // The repeat compares the texts the getter reads, the default-language ones (rule 2): a French name beside + // the collection artist does not make AlbumArtists = ["Coll"] another value. + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "Coll", "coll"), Simple ("ARTIST", "Coll-fr", isDefault: false)), + Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + + tag.AlbumArtists = ["Coll"]; + + Assert.AreEqual ("coll", tag.ArtistSort); + Assert.AreEqual ("coll", tag.AlbumArtistSort); + + // The track ARTIST shadows the collection's too when the item is below the track. + var part = MatroskaFile.Read (FileWith (Tags ( + Tag (70, SimpleSorted ("ARTIST", "Coll", "coll")), + Tag (20, Simple ("ARTIST", "Part"))))).File!.Tag; + + part.Artist = "Coll"; + + var bytes = FileWith (part.Render ().ToArray ()); + Assert.IsTrue (FileTargetHas (bytes, 30, "ARTIST")); + Assert.AreEqual (2, CountOf (bytes, "coll"u8.ToArray ()), "the track's repeat carries the SORT_WITH"); + } + + static string? FirstTagString (MatroskaTag tag, ulong level, string name) + { + var layout = ModelLayout (tag.Render ().ToArray ()); + return layout.TryGetValue (level, out var tags) ? tags.FirstOrDefault (t => t.Name == name)?.Text : null; + } + + [TestMethod] + public void ValueSet_ForAnAlbumTitle_DoesNotRepeatACollectionSort () + { + // Album reads level 50 alone, so an album title equal to the collection's does not shadow it: the + // collection title's SORT_WITH stays its own (rule 1). + var tag = MatroskaFile.Read (FileWith (Tags (Tag (70, SimpleSorted ("TITLE", "Coll", "coll sort")), Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + + tag.Album = "Coll"; + + Assert.IsNull (tag.AlbumSort); + Assert.AreEqual (1, CountOf (tag.Render ().ToArray (), "coll sort"u8.ToArray ())); + } + + [TestMethod] + public void Runs_CountAValueWithoutText_AsEmpty () + { + // A SimpleTag with no TagString holds an empty value, the same as TagString "" (RFC 9559 section 5.1.8.1.2). + var noText = Master (0x67C8, Element (0x45A3, "ARTIST"u8)); + var tag = MatroskaFile.Read (FileWith (Tags ( + Tag (50, noText, Simple ("ARTIST_SORT", "s")), + Tag (30, Simple ("TITLE", "S"), Simple ("ARTIST", ""))))).File!.Tag; + + Assert.AreEqual ("s", tag.ArtistSort); + + // The same when no value is in the default language, so the run compares every language's values. + var other = Master (0x67C8, Element (0x45A3, "ARTIST"u8), Element (0x4484, new byte[] { 0 })); + var languages = MatroskaFile.Read (FileWith (Tags ( + Tag (50, other, Simple ("ARTIST_SORT", "s")), + Tag (30, Simple ("TITLE", "S"), Simple ("ARTIST", "", isDefault: false))))).File!.Tag; + Assert.AreEqual ("s", languages.ArtistSort); + } + + [TestMethod] + public void CustomField_ForASortName_BehavesAsTheSortProperty () + { + // A custom field named ARTIST_SORT (or any flat sort name) reads, sets and removes what the sort property + // does, on every ownership shape: the same value read and the same bytes after. + var failures = new List (); + foreach (var pair in SortPairs) { + foreach (var (shape, data) in OwnershipShapes (pair)) { + var byProperty = MatroskaFile.Read (data).File!.Tag; + var byName = MatroskaFile.Read (data).File!.Tag; + var read = ReadSort (byProperty, pair); + if (!byName.GetCustomField (pair.Flat).SequenceEqual (read is null ? [] : [read])) + failures.Add ($"{pair.Name} {shape}: get"); + + foreach (var value in new[] { "NEW", null }) { + var p = MatroskaFile.Read (data).File!.Tag; + var n = MatroskaFile.Read (data).File!.Tag; + SetSortOf (p, pair, value); + if (value is null) + n.RemoveCustomField (pair.Flat); + else + n.SetCustomField (pair.Flat, value); + if (ReadSort (n, pair) != ReadSort (p, pair) || !n.Render ().ToArray ().AsSpan ().SequenceEqual (p.Render ().ToArray ())) + failures.Add ($"{pair.Name} {shape}: {(value is null ? "remove" : "set")}"); + } + } + } + + var titles = MatroskaFile.Read (FileWith (Tags (Tag (50, SimpleSorted ("TITLE", "Al", "al")), Tag (30, Simple ("TITLE", "S"), Simple ("TITLE_SORT", "s"))))).File!.Tag; + Assert.AreEqual ("s", string.Join ("|", titles.GetCustomField ("TITLE_SORT"))); + Assert.AreEqual ("al", string.Join ("|", titles.GetCustomField ("ALBUM_SORT"))); + Assert.IsFalse (titles.SetCustomField ("ARTIST_SORT", "a", "b"), "a sort is one name"); + Assert.IsTrue (titles.SetCustomField ("TITLE_SORT", "t")); + Assert.AreEqual ("t", titles.TitleSort); + Assert.IsTrue (titles.RemoveCustomField ("ALBUM_SORT")); + Assert.IsNull (titles.AlbumSort); + Assert.IsEmpty (failures, $"{failures.Count} differ, e.g. {string.Join ("; ", failures.Take (5))}"); + } + + static void SetSortOf (MatroskaTag tag, SortPair pair, string? value) + { + switch (pair.Getter) { + case Getter.Artist: + tag.ArtistSort = value; + break; + case Getter.Composer: + tag.ComposerSort = value; + break; + default: + tag.AlbumArtistSort = value; + break; + } + } +} diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs new file mode 100644 index 00000000..b32a99e6 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaWriteBackTests.cs @@ -0,0 +1,224 @@ +// 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.Matroska; + +namespace TagLibSharp2.Tests.Matroska; + +// Library rule: writing back the value read changes nothing. Every setter this PR reaches, on every +// ownership shape plus item fields at 30, 50, 70 and untargeted, renders byte for byte as before. +public partial class MatroskaFileTests +{ + // Each property's value as the getter reads it, joined for arrays; writing it back is the operation. + static readonly (string Name, Func Read, Action WriteBack)[] WriteBacks = [ + ("ArtistSort", t => t.ArtistSort, t => t.ArtistSort = t.ArtistSort), + ("AlbumArtistSort", t => t.AlbumArtistSort, t => t.AlbumArtistSort = t.AlbumArtistSort), + ("ComposerSort", t => t.ComposerSort, t => t.ComposerSort = t.ComposerSort), + ("TitleSort", t => t.TitleSort, t => t.TitleSort = t.TitleSort), + ("AlbumSort", t => t.AlbumSort, t => t.AlbumSort = t.AlbumSort), + ("Artist", t => t.Artist, t => t.Artist = t.Artist), + ("Performers", t => Joined (t.Performers), t => t.Performers = t.Performers), + ("AlbumArtists", t => Joined (t.AlbumArtists), t => t.AlbumArtists = t.AlbumArtists), + ("Composers", t => Joined (t.Composers), t => t.Composers = t.Composers), + ("Title", t => t.Title, t => t.Title = t.Title), + ("Album", t => t.Album, t => t.Album = t.Album), + ("Genre", t => t.Genre, t => t.Genre = t.Genre), + ("Genres", t => Joined (t.Genres), t => t.Genres = t.Genres), + ("Year", t => t.Year, t => t.Year = t.Year), + ("Comment", t => t.Comment, t => t.Comment = t.Comment), + ("BeatsPerMinute", t => t.BeatsPerMinute?.ToString (System.Globalization.CultureInfo.InvariantCulture), t => t.BeatsPerMinute = t.BeatsPerMinute), + ("Publisher", t => t.Publisher, t => t.Publisher = t.Publisher), + ("ReplayGainTrackGain", t => t.ReplayGainTrackGain, t => t.ReplayGainTrackGain = t.ReplayGainTrackGain), + ("ReplayGainTrackPeak", t => t.ReplayGainTrackPeak, t => t.ReplayGainTrackPeak = t.ReplayGainTrackPeak), + ]; + + static string? Joined (string[] values) => values.Length == 0 ? null : string.Join ("|", values); + + // A value read back unchanged is a no-op: the bytes stay. Null is a clear: it still reads null afterwards, + // and may remove a value a broader level held behind it. + [TestMethod] + public void WritingBackTheValueRead_ChangesNoBytes () + { + var failures = new List (); + foreach (var (shape, data) in WriteBackShapes ()) { + foreach (var (name, read, writeBack) in WriteBacks) { + var tag = MatroskaFile.Read (data).File!.Tag; + var before = tag.Render ().ToArray (); + var value = read (tag); + + writeBack (tag); + + if (value is not null && !before.AsSpan ().SequenceEqual (tag.Render ().ToArray ())) + failures.Add ($"{shape}: {name}"); + if (value is null && read (tag) is not null) + failures.Add ($"{shape}: {name} null"); + } + } + + var byName = failures.GroupBy (f => f[(f.LastIndexOf (": ", StringComparison.Ordinal) + 2)..]).Select (g => $"{g.Key}={g.Count ()}"); + Assert.IsEmpty (failures, $"{failures.Count} write-backs changed bytes ({string.Join (", ", byName)}), e.g. {string.Join ("; ", failures.Take (4))}"); + } + + static IEnumerable<(string Name, byte[] Data)> WriteBackShapes () + { + foreach (var pair in SortPairs) { + foreach (var (shape, data) in OwnershipShapes (pair)) + yield return ($"{pair.Name} {shape}", data); + } + + foreach (var (shape, data) in ItemFieldShapes ()) + yield return ($"item {shape}", data); + foreach (var (name, build) in SortShapes) + yield return ($"sort {name}", build ()); + yield return ("genre at 70", FileWith (Tags (Tag (70, Simple ("GENRE", "Rock")), Tag (30, Simple ("TITLE", "Song"))))); + yield return ("untargeted ffmpeg", FileWith (Tags (Master (0x7373, Concat (Master (0x63C0, Array.Empty ()), + Simple ("TITLE", "Song"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "Ada sort"), Simple ("GENRE", "Rock")))))); + yield return ("fallback names", FileWith (Tags (Tag (50, Simple ("BPM", "120.0"), Simple ("LABEL", "Lbl"), + Simple ("REPLAYGAIN_GAIN", "-3 dB"), Simple ("REPLAYGAIN_PEAK", "0.9")), Tag (30, Simple ("TITLE", "Song"))))); + yield return ("blockers at 30", FileWith (Tags ( + Tag (50, Simple ("GENRE", "Rock"), Simple ("COMPOSER", "Bach"), Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "ada")), + Tag (30, Simple ("TITLE", "Song"), Simple ("GENRE", ""), Simple ("COMPOSER", ""), Simple ("ARTIST", ""), Simple ("ARTIST_SORT", ""))))); + yield return ("titles with sorts", FileWith (Tags ( + Tag (50, SimpleSorted ("TITLE", "Album", "album"), Simple ("ALBUM_SORT", "flat album")), + Tag (30, Simple ("TITLE", "Song"), Simple ("TITLE_SORT", "song"))))); + // A nested sort beside a flat one, and a value-less title sort above its title: the write-back reads the + // nested sort first and the run above, so neither moves. + yield return ("title sorts nested and flat", FileWith (Tags ( + Tag (50, SimpleSorted ("TITLE", "Album", "album"), Simple ("ALBUM_SORT", "flat album")), + Tag (30, SimpleSorted ("TITLE", "Song", "song"), Simple ("TITLE_SORT", "flat song"))))); + yield return ("title sorts above their titles", FileWith (Tags ( + Tag (60, Simple ("ALBUM_SORT", "x")), Tag (50, Simple ("TITLE", "Al")), + Tag (40, Simple ("TITLE_SORT", "y")), Tag (30, Simple ("TITLE", "S"))))); + // Two values of a name a fallback getter reads, and a value at the collection level: writing back the + // first keeps the list and its level. + yield return ("lists of fallback names", FileWith (Tags (Tag (50, Simple ("PUBLISHER", "P"), Simple ("PUBLISHER", "Q"), + Simple ("REPLAYGAIN_TRACK_GAIN", "-6 dB"), Simple ("REPLAYGAIN_TRACK_GAIN", "-7 dB"), Simple ("BPM", "120"), Simple ("BPM", "130")), + Tag (30, Simple ("TITLE", "Song"))))); + yield return ("fields at 70", FileWith (Tags (Tag (70, Simple ("PUBLISHER", "P"), Simple ("REPLAYGAIN_TRACK_GAIN", "-6 dB"), Simple ("BPM", "120")), + Tag (30, Simple ("TITLE", "Song"))))); + } + + [TestMethod] + public void NullList_Clears_WithItsSorts () + { + // Null is a clear (Tag.IsWriteBack never matches null), for a list too. + var performers = MatroskaFile.Read (FileWith (Tags (Tag (30, Simple ("ARTIST", "A"), Simple ("ARTIST_SORT", "x"))))).File!.Tag; + performers.Performers = null!; + Assert.IsFalse (HasTagName (FileWith (performers.Render ().ToArray ()), "ARTIST_SORT")); + Assert.IsEmpty (performers.Performers); + + var albumArtists = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("ARTIST", "Ada"), Simple ("ARTIST_SORT", "x")), Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + albumArtists.AlbumArtists = null!; + Assert.IsFalse (HasTagName (FileWith (albumArtists.Render ().ToArray ()), "ARTIST")); + Assert.IsFalse (HasTagName (FileWith (albumArtists.Render ().ToArray ()), "ARTIST_SORT")); + + var composers = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "x"))))).File!.Tag; + composers.Composers = null!; + Assert.IsFalse (HasTagName (FileWith (composers.Render ().ToArray ()), "COMPOSER_SORT")); + Assert.IsEmpty (composers.Composers); + + var genres = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("GENRE", "Rock")), Tag (30, Simple ("GENRE", ""), Simple ("TITLE", "S"))))).File!.Tag; + Assert.IsEmpty (genres.Genres); + genres.Genres = null!; + Assert.IsFalse (HasTagName (FileWith (genres.Render ().ToArray ()), "GENRE"), "the clear removes what the empty one hides"); + } + + [TestMethod] + public void ListWrite_WithEmptyEntries_IsTheListRead () + { + // Empty entries are not values: the rest, in order, is what the getter reads, here from the collection level, + // where a write would otherwise add a copy at the album level. + var tag = MatroskaFile.Read (FileWith (Tags (Tag (70, Simple ("GENRE", "Rock"), Simple ("GENRE", "Pop")), Tag (30, Simple ("TITLE", "S"))))).File!.Tag; + var before = tag.Render ().ToArray (); + + tag.Genres = ["", "Rock", "", "Pop"]; + + CollectionAssert.AreEqual (before, tag.Render ().ToArray ()); + } + + [TestMethod] + public void WritingBackOtherValues_StillWrites () + { + // The no-op is only for the values read, in order: a reorder, a subset or a new value is written. + var tag = MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("GENRE", "A"), Simple ("GENRE", "B"))))).File!.Tag; + + tag.Genres = ["B", "A"]; + Assert.AreEqual ("B|A", string.Join ("|", tag.Genres)); + tag.Genres = ["B"]; + Assert.AreEqual ("B", string.Join ("|", tag.Genres)); + tag.Genres = ["B", "C"]; + Assert.AreEqual ("B|C", string.Join ("|", tag.Genres)); + } + + [TestMethod] + public void Clear_OfANullField_RemovesWhatABroaderLevelHides () + { + // A "" at 30 hides the album's GENRE from us (RFC 9559 section 24.2) but not from readers that ignore + // levels. Writing null back is a clear, so the hidden value goes too, and so is "" or an empty list, as a value + // still holds text (#136). A cleared track ARTIST keeps its + // blocker, or the album's ARTIST would show through as the track's. + var data = FileWith (Tags ( + Tag (50, Simple ("GENRE", "Rock"), Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "bach"), Simple ("ARTIST", "Ada")), + Tag (30, Simple ("TITLE", "Song"), Simple ("GENRE", ""), Simple ("COMPOSER", ""), Simple ("ARTIST", "")))); + var tag = MatroskaFile.Read (data).File!.Tag; + Assert.IsNull (tag.Genre); + Assert.IsEmpty (tag.Composers); + Assert.IsNull (tag.Artist); + + tag.Genre = null; + tag.Composers = []; + tag.Artist = null; + tag.ComposerSort = null; + + var rendered = FileWith (tag.Render ().ToArray ()); + Assert.IsFalse (HasTagName (rendered, "GENRE")); + Assert.IsFalse (HasTagName (rendered, "COMPOSER")); + Assert.IsFalse (HasTagName (rendered, "COMPOSER_SORT")); + Assert.IsNull (tag.Artist); + Assert.IsTrue (HasTagString (rendered, "Ada"), "the album artist is kept"); + } + + [TestMethod] + public void Clear_OfANullSortOrAlbumArtist_RemovesWhatABroaderLevelHides () + { + var sorts = MatroskaFile.Read (FileWith (Tags ( + Tag (50, Simple ("COMPOSER", "Bach"), Simple ("COMPOSER_SORT", "bach")), + Tag (30, Simple ("TITLE", "Song"), Simple ("COMPOSER_SORT", ""))))).File!.Tag; + Assert.IsNull (sorts.ComposerSort); + sorts.ComposerSort = null; + Assert.IsFalse (HasTagName (FileWith (sorts.Render ().ToArray ()), "COMPOSER_SORT")); + + var albumArtist = MatroskaFile.Read (FileWith (Tags ( + Tag (70, Simple ("ALBUM_ARTIST", "AA70")), + Tag (50, Simple ("TITLE", "Album"), Simple ("ALBUM_ARTIST", ""))))).File!.Tag; + Assert.IsEmpty (albumArtist.AlbumArtists); + albumArtist.AlbumArtists = []; + Assert.IsFalse (HasTagName (FileWith (albumArtist.Render ().ToArray ()), "ALBUM_ARTIST")); + } + + [TestMethod] + public void FallbackNames_ClearAndReplaceWithTheirField () + { + static MatroskaTag Read () => MatroskaFile.Read (FileWith (Tags (Tag (50, Simple ("LABEL", "Lbl"), + Simple ("REPLAYGAIN_GAIN", "-3 dB"), Simple ("REPLAYGAIN_PEAK", "0.9"))))).File!.Tag; + + var cleared = Read (); + cleared.Publisher = null; + cleared.ReplayGainTrackGain = null; + cleared.ReplayGainTrackPeak = null; + Assert.IsNull (cleared.Publisher); + Assert.IsNull (cleared.ReplayGainTrackGain); + Assert.IsNull (cleared.ReplayGainTrackPeak); + + var set = Read (); + set.Publisher = "Pub"; + set.ReplayGainTrackGain = "-6 dB"; + set.ReplayGainTrackPeak = "0.5"; + var rendered = FileWith (set.Render ().ToArray ()); + Assert.AreEqual ("Pub", set.Publisher); + Assert.IsTrue (HasTagName (rendered, "LABEL"), "LABEL is its own tag"); + Assert.IsFalse (HasTagName (rendered, "REPLAYGAIN_GAIN"), "the older copy goes"); + Assert.IsFalse (HasTagName (rendered, "REPLAYGAIN_PEAK"), "the older copy goes"); + Assert.AreEqual ("-6 dB", set.ReplayGainTrackGain); + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 1f4e30df..e758be6a 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -2510,6 +2510,7 @@ namespace TagLibSharp2.Matroska public sealed class MatroskaTag : TagLibSharp2.Core.Tag { public override string? Album { get; set; } + public override string? AlbumArtistSort { get; set; } public override string[] AlbumArtists { get; set; } public override string? AlbumSort { get; set; } public override string? Artist { get; set; } @@ -2518,6 +2519,7 @@ namespace TagLibSharp2.Matroska public override uint? BeatsPerMinute { get; set; } public override string? CatalogNumber { get; set; } public override string? Comment { 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; }