From 8e721d0d0e3e47d1f1184a218a1c445ec9bd695e Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:25:30 -0700 Subject: [PATCH 01/12] fix: Type RIFF data as WebP only when its form type is WEBP (#234) Cause: Picture.DetectMimeType returned image/webp for any data that starts with "RIFF", so WAV or AVI bytes, or a mislabelled picture, were typed as WebP, and the file extension was never consulted. Fix: RIFF data is image/webp only when bytes 8-11 are "WEBP" (RFC 9649 section 2.4: "RIFF", the file size, then "WEBP"). Any other RIFF form, or a header cut off before its form type, falls through to the extension, or application/octet-stream without one. Every caller that types a picture from its bytes takes the rule: PictureFrame and FlacPicture FromBytes/FromFile, ApePicture, the Audible cover, and Matroska's MediaTypeOf (a picture given no MIME type), whose save now refuses WAV bytes as "not an image/ media type" instead of writing them as an image/webp attachment. Tests: PictureTests.DetectMimeType_RiffIsWebPOnlyWithTheWebPFormType ({WEBP, WAVE, AVI, webp, WEBQ, none, cut} x {no path, .webp, .jpg, .bin}), DetectMimeType_RiffPrefix_IsWebPOnceTheFormTypeIsThere (every prefix, no read past the end), DetectingPictures_TypeRiffByItsFormType (ID3v2, FLAC, APE, Audible, Matroska x {WEBP, WAVE, AVI}). PictureFrameTests.DetectMimeType_WebP now uses a real WebP header; its six-byte "RIFF" input pinned the bug. Red: 28 of the new cases failed on main with "image/webp". --- CHANGELOG.md | 1 + src/TagLibSharp2/Core/Picture.cs | 11 ++- tests/TagLibSharp2.Tests/Core/PictureTests.cs | 73 ++++++++++++++++++- .../Id3/Id3v2/Frames/PictureFrameTests.cs | 2 +- 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a62c0c54..66b5aa3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -123,6 +123,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- `Picture.DetectMimeType` no longer types any RIFF data as WebP (#234). RIFF data is `image/webp` only when its form type at offset 8 is `WEBP` (RFC 9649 §2.4); WAV, AVI and other RIFF forms, and a RIFF header cut off before its form type, fall through to the file extension, or `application/octet-stream` without one. This reaches every picture typed from its bytes: `PictureFrame.FromBytes` and `FromFile`, `FlacPicture.FromBytes` and `FromFile`, `ApePicture`, the Audible cover, and a Matroska picture given no MIME type, whose save now fails with "is not an image/ media type" instead of writing WAV or AVI bytes as an `image/webp` attachment - A Matroska save no longer grows quadratically with the pictures a file holds, and the Tags read is bounded (#247). Each picture now finds its own attachment by its content in an ordered index, the UIDs and names a save keeps are in ordered sets, and new pictures of one type are numbered in one pass, so no content a file holds, its attachments' data or UIDs included, can make a hash collide; setting the pictures back on a file with many image attachments took time quadratic in them. A read models at most 65,536 Tags and SimpleTags, as Chapters bounds its entries; the Tags past that are kept as their bytes and written back unread. A save that would write a Tag, a SimpleTag, a chapter or a chapter's value past what a read models (a new Tag or chapter in a file at the budget, or an edit that pushes the last one read, or only its title, language, times or flags, past it) now fails with a result saying so, and leaves the file and the object's edits as they were; it used to report success for a value no read could show. A chapter title edit at the budget counts too when the display was read without a language, as the save writes the default "eng". An edit that writes as many elements, such as a value replaced in place, is saved. - A second save of a Matroska file from the same object writes a clear or an undone edit (#244). Read a file, set `Title`, save it over its source, then clear `Title` and save again: the file kept the title. A save left the `Tags` element as it was when the tags matched the ones the object first read, but after a save over the source the file holds the saved tags. The same held for every tag field, and for a chapter edit undone, or a chapter or edition added and then removed. A save now compares with the `Tags` and `Chapters` elements in the bytes it rewrites, on all six save entry points. A chapter read without a `ChapterUID`, or with 0, now reads `Uid` 0 and is written as it was (a read gave it a random UID, so no two reads of the file were the same); a save that writes the chapter changed gives it a new random UID, as RFC 9559 requires one that is not 0, and the chapter keeps it once a save over the source has written it. Setting `MatroskaChapter.Uid` to 0 now means the same, no UID yet, where it threw. After a save over its source the object holds the tags and chapters it wrote, as a read of the saved file would, so a later save writes what a fresh object would; a save that fails or goes elsewhere leaves it as it was. A UID the library draws for a new chapter, edition or picture attachment is now always 8 bytes wide, so the size of a save no longer depends on the draw. A save finds the empty Tags it keeps by their content in an ordered set, in O(log n) comparisons each whatever the Tags hold, with no hash a file could make collide. - A Matroska file whose only title is a `TITLE` in a Tag with an empty Targets, such as the Matroska test suite's test1.mkv, no longer reads that title as its `Album` too (#221). A Tag with no `TargetTypeValue` is target 50 by default, but ffprobe, exiftool and MediaInfo show its `TITLE` as the title and no album, so `Album` now reads an explicit target-50 `TITLE`, then ffmpeg's `ALBUM`, and nothing else; clearing the album leaves that `TITLE`, and `AlbumSort` no longer reads the sort nested in it, which `TitleSort` now reads. Setting `Title` on such a file replaced nothing: it added a `TITLE` at target 30 and kept the old one, which exiftool, showing the first, still showed (and `Album` still read), with a segment title too, and when a save left out an Info/Title too long to rewrite in place. The new title now replaces the untargeted `TITLE` in place, in the language `Title` reads (a `TITLE` in another language stays), and the segment title with it; where a narrower `TITLE` or an explicit album `TITLE` could be the one a reader shows, the title is also written at target 30, with its languages and sort, so ffprobe, exiftool and MediaInfo show only the new title. An album edit keeps the title's sort. diff --git a/src/TagLibSharp2/Core/Picture.cs b/src/TagLibSharp2/Core/Picture.cs index 16b24a3f..a7f22562 100644 --- a/src/TagLibSharp2/Core/Picture.cs +++ b/src/TagLibSharp2/Core/Picture.cs @@ -41,6 +41,10 @@ public abstract class Picture : IPicture /// /// Detects the MIME type from image data by examining magic bytes. /// + /// + /// RIFF data is WebP only when its form type is WEBP; WAV, AVI or any other RIFF form falls through to the + /// extension of . + /// /// The image data. /// Optional file path to use extension as fallback. /// The detected MIME type, or "application/octet-stream" if unknown. @@ -61,8 +65,11 @@ public static string DetectMimeType (ReadOnlySpan data, string? filePath = if (data.Length >= 2 && data[0] == 0x42 && data[1] == 0x4D) return "image/bmp"; - if (data.Length >= 4 && data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46) - return "image/webp"; // RIFF header (WebP) + // "RIFF", the file size, then the form type "WEBP" (RFC 9649 §2.4). A RIFF of another form, such as WAVE or AVI, + // is not a WebP image. + if (data.Length >= 12 && data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 && + data[8] == 0x57 && data[9] == 0x45 && data[10] == 0x42 && data[11] == 0x50) + return "image/webp"; // Fall back to file extension if provided if (!string.IsNullOrEmpty (filePath)) { diff --git a/tests/TagLibSharp2.Tests/Core/PictureTests.cs b/tests/TagLibSharp2.Tests/Core/PictureTests.cs index c8c4275e..6bf22963 100644 --- a/tests/TagLibSharp2.Tests/Core/PictureTests.cs +++ b/tests/TagLibSharp2.Tests/Core/PictureTests.cs @@ -39,13 +39,80 @@ public void DetectMimeType_Bmp_ReturnsCorrectType () Assert.AreEqual ("image/bmp", Picture.DetectMimeType (bmpData)); } + /// + /// A RIFF file is WebP only when its form type at offset 8 is WEBP (RFC 9649 §2.4: "RIFF", the file size, + /// then "WEBP"). Any other form (WAVE, AVI, a cut-off header) is not an image the bytes identify, so the extension + /// decides, and without one the type is unknown (#234). + /// + [TestMethod] + [DynamicData (nameof (RiffForms))] + public void DetectMimeType_RiffIsWebPOnlyWithTheWebPFormType (string form, string? path, string expected) + { + Assert.AreEqual (expected, Picture.DetectMimeType (Riff (form), path), $"form '{form}', path '{path}'"); + } + + /// Every prefix of a WebP file is typed without reading past it: WebP from the twelfth byte on, unknown before. + [TestMethod] + public void DetectMimeType_RiffPrefix_IsWebPOnceTheFormTypeIsThere () + { + var webp = Riff ("WEBP"); + for (var length = 0; length <= webp.Length; length++) { + var expected = length >= 12 ? "image/webp" : "application/octet-stream"; + Assert.AreEqual (expected, Picture.DetectMimeType (webp.AsSpan (0, length)), $"{length} bytes"); + } + } + + public static IEnumerable RiffForms () + { + foreach (var path in new string?[] { null, "cover.webp", "cover.jpg", "cover.bin" }) { + var byExtension = path switch { + "cover.webp" => "image/webp", + "cover.jpg" => "image/jpeg", + _ => "application/octet-stream" + }; + yield return ["WEBP", path, "image/webp"]; + foreach (var form in new[] { "WAVE", "AVI ", "webp", "WEBQ", "", "WEB" }) + yield return [form, path, byExtension]; + } + } + + /// + /// Every picture type that detects its MIME type from the bytes (ID3v2, FLAC, APE, the Audible cover, and a Matroska + /// picture given no type) types WAV and AVI bytes as anything but WebP, and a WebP image as WebP (#234). + /// [TestMethod] - public void DetectMimeType_WebP_ReturnsCorrectType () + [DynamicData (nameof (DetectingPictures))] + public void DetectingPictures_TypeRiffByItsFormType (string carrier, string form, string? expected) { - var webpData = new byte[] { 0x52, 0x49, 0x46, 0x46, 0x00, 0x00 }; - Assert.AreEqual ("image/webp", Picture.DetectMimeType (webpData)); + var data = Riff (form); + var mime = carrier switch { + "id3v2" => TagLibSharp2.Id3.Id3v2.Frames.PictureFrame.FromBytes (data).MimeType, + "flac" => TagLibSharp2.Xiph.FlacPicture.FromBytes (data).MimeType, + "ape" => new TagLibSharp2.Ape.ApePicture ("cover", PictureType.FrontCover, new BinaryData (data)).MimeType, + "audible" => new TagLibSharp2.Audible.AudibleCoverPicture (data).MimeType, + "matroska" => TagLibSharp2.Matroska.MatroskaAttachments.MediaTypeOf ( + new TestPicture ("", PictureType.FrontCover, "", new BinaryData (data))), + _ => throw new ArgumentOutOfRangeException (nameof (carrier)) + }; + Assert.AreEqual (expected, mime, $"{carrier}, form '{form}'"); } + public static IEnumerable DetectingPictures () + { + foreach (var carrier in new[] { "id3v2", "flac", "ape", "audible", "matroska" }) { + yield return [carrier, "WEBP", "image/webp"]; + // A Matroska picture's attachment needs an image/ type; bytes that are not one get none. + var other = carrier == "matroska" ? null : "application/octet-stream"; + yield return [carrier, "WAVE", other]; + yield return [carrier, "AVI ", other]; + } + } + + /// A RIFF header with as its form type, followed by a chunk. + static byte[] Riff (string form) => + [.. "RIFF"u8, 0x1C, 0x00, 0x00, 0x00, .. System.Text.Encoding.ASCII.GetBytes (form), .. "VP8L"u8, 0x0A, 0x00, 0x00, 0x00, + 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + [TestMethod] public void DetectMimeType_Unknown_ReturnsOctetStream () { diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs index 7126ce57..798184e8 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs @@ -398,7 +398,7 @@ public void DetectMimeType_Bmp_ReturnsCorrectType () [TestMethod] public void DetectMimeType_WebP_ReturnsCorrectType () { - var webpData = new byte[] { 0x52, 0x49, 0x46, 0x46, 0x00, 0x00 }; + var webpData = new byte[] { 0x52, 0x49, 0x46, 0x46, 0x04, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50 }; Assert.AreEqual ("image/webp", PictureFrame.DetectMimeType (webpData)); } From e413fee38a4841a38e36fb1fab126130bea2da36 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:28:18 -0700 Subject: [PATCH 02/12] fix: Give WavFile and AiffFile a SaveToFile () to their source, and WAV and AVI a public Tag (#235) Cause: every other format has SaveToFile (IFileSystem?) that writes back to SourcePath; WAV and AIFF had only SaveToFile (path) and the async SaveToFileAsync (). WavFile's tag view was only the explicit IMediaFile.Tag, so `wav.Tag.Title = x` did not compile on a WavFile (Stephen's comment on the issue). AviFile had the same gap: its view was only IMediaFile.Tag, over an internal UnifiedTag. Fix: SaveToFile (IFileSystem? fileSystem = null) on both, the twin of their SaveToFileAsync (): a SkipPictures read refuses, a file with no SourcePath fails with "No source path available", and the save goes through the file system the file was read with unless one is given. WavFile.Tag is public (same view, same remarks). AviFile.Tag is public too: the same view (the INFO tag, combined with the ID3v2 tag when there is one), never null because InfoTag always exists, so typed Tag as AsfFile.Tag and MatroskaFile.Tag are; IMediaFile.Tag returns it and the internal UnifiedTag, which had no other caller, is folded in. The public API snapshot gains exactly these four members. The views had to reach every store a reader shows (review 1 N6, N7): - A WAV file with both an ID3v2 tag and an INFO list (sample.wav) had the ID3v2 tag alone as its view, so a title set left the INFO title (MediaInfo showed the old one, ffprobe both) and Clear left the whole INFO list. Tag is now a CombinedTag over both, ID3v2 first, as MP3's is over ID3v2 and ID3v1; with only one of them it is that tag, and with neither the view that creates ID3v2, as before. - After a successful save, WAV drops an ID3v2 tag or INFO list it emptied, and AVI and AIFF an ID3v2 tag they emptied: the save wrote none, a fresh read of the saved file holds none, so the next value set goes where that read's would (a kept emptied v2.3 tag wrote a v2.3 tag where a fresh read's view creates a v2.4 one). Before, a Clear and a save left the AVI object with an empty ID3v2 tag that stored a MusicBrainz ID the fresh read dropped. WAV also forgets an id3 chunk it could not parse once an empty tag replaced it, so a later save does not bring it back. - On an AVI with no ID3v2 tag, a field INFO cannot hold is not stored; AviFile.Tag says so and how to keep one (assign Id3v2Tag), and that it is never null, after Dispose too, as AsfFile.Tag and MatroskaFile.Tag. AIFF's view already covered its ID3 chunk and text chunks (ffprobe, ExifTool and MediaInfo show the new title only); only an emptied tag needed handling, which the review's harness found on sample.aif. A save writes no empty tag; the object keeps the emptied instance, so a reference the caller holds (Id3v2Tag, InfoTag) stays the file's tag and a value set later through it is written (review 2 B1; a first version dropped it). After a save over the source that wrote none (SavedOverSource.HoldsFile: the source now holds, byte for byte, the file written) the view goes on without it while it stays empty (ViewId3, ViewInfo), as a fresh read of that file has no such tag, so the next value set through Tag goes where that read's would; an assignment, or a later save over the source that writes the tag, ends that. That save also makes the kept ID3v2 tag a new one (Id3v2Tag.ResetToNew, internal: no frame, version 4), so its next value, through the held reference or the view, is written as a fresh read's view-created tag is; and a view write that needs an ID3v2 tag takes the kept instance rather than creating another, so the caller's reference stays the file's tag (review 3 B1: a view write after a clear-and-save replaced it, and the next edit through the held tag was lost). A view write that empties it again hides it again rather than dropping it. A save to another path changes none of it: the object still describes its source, which holds the tag (contract suite round 3, R2: a WAV cleared, saved elsewhere, then given a custom field wrote an ID3v2 tag where a fresh read wrote none). The fresh read in that report stores no custom field because SetCustomField on an INFO-only WAV (and AVI) returns false for a name that is not a FOURCC, as on main; the contract's Edit ignores that return value. Tests: SaveToSourceTests over every format in TaglessFixtures (19): PublicTag_IsTheView, SaveToFile_NoPath_SavesBackToTheSourceAsTheAsyncSaveDoes (the sync save writes the same bytes as SaveToFileAsync ()), SaveToFile_NoPath_WritesToTheFileSystemGiven, and for WAV and AIFF SaveToFile_NoPath_RefusesAsTheAsyncSaveDoes (not from a path, and SkipPictures). Members are reached through dynamic, so the next format without them fails a row rather than compiling away. MP4 is skipped in PublicTag_IsTheView (its public Tag is the ilst, null until created, as documented). RiffTagViewTests: Wav_SetThroughTag_WritesBothTags over seven INFO fields, Wav_ClearThroughTag_RemovesBothTags, SaveAfterSave_IsTheFreshReadsSave over {WAV, AVI, AIFF} x {Clear, title, MusicBrainz ID} x {the same}, Wav_UnparsedId3ReplacedByAnEmptyTag_StaysGoneAfterTheNextSave, Avi_FieldInfoCannotHold_IsStoredOnlyWithAnId3v2Tag, ClearSave_ThenViewAndHeldEdits_AreBothWritten over {WAV, AVI, AIFF} x {held edit first, view edit first} (both values on disk, the held tag still the file's, the bytes a fresh read's with its ID3v2 tag, or a new one assigned, standing for the held one), ViewWriteThatEmptiesTheKeptTag_LeavesTheHeldReferenceLive (WAV, AIFF), SaveElsewhereTwice_IsTheFreshReadsSave over {WAV with both tags, WAV with INFO only, AVI, AIFF} x {Clear, Title = null} x {title, custom field, MusicBrainz ID}, each saved twice to another path by the sync and the async path save (Core/SaveElsewhere, the contract suite's C2 shape). Black box on sample.wav: after a title set ffprobe, ExifTool (RIFF and ID3v2_3) and MediaInfo show only the new title; after Clear none shows a tag. Red: 9 rows failed on main with RuntimeBinderException ("No overload for method 'SaveToFile' takes 0 arguments"; "WavFile does not contain a definition for 'Tag'"); with the AVI row included, PublicTag_IsTheView ("avi") failed the same way ("AviFile does not contain a definition for 'Tag'"). Of RiffTagViewTests, 13 rows failed at the round-1 head, and the two AIFF Clear rows (with a v2.3 fixture) without the AIFF drop. Of SaveElsewhereTwice_IsTheFreshReadsSave, 15 of 24 rows failed at the round-2 head (every row whose first edit empties a tag). Of ClearSave_ThenViewAndHeldEdits_AreBothWritten, all 6 rows failed at the round-3 head. SavedOverSource.HoldsFile skips its compare when the save went to the source's own full path on the same file system (review 3: a save over the source compared the file with itself while a tag was empty); another spelling is still compared (HoldsFileTests). A source another process rewrites between the save and the compare gets the answer its bytes give; a wrong false keeps the earlier bookkeeping, as a save elsewhere does (noted in the code). --- CHANGELOG.md | 1 + src/TagLibSharp2/Aiff/AiffFile.cs | 99 +++++- src/TagLibSharp2/Aiff/AiffTag.cs | 2 +- src/TagLibSharp2/Core/SavedOverSource.cs | 75 ++++ src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 16 +- src/TagLibSharp2/Riff/AviFile.cs | 64 +++- src/TagLibSharp2/Riff/WavFile.cs | 150 +++++++- .../TagLibSharp2.Tests/Core/HoldsFileTests.cs | 61 ++++ .../TagLibSharp2.Tests/Core/SaveElsewhere.cs | 56 +++ .../Core/SaveToSourceTests.cs | 123 +++++++ .../TagLibSharp2.PublicApi.verified.txt | 4 + .../Riff/RiffTagViewTests.cs | 334 ++++++++++++++++++ 12 files changed, 951 insertions(+), 34 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/HoldsFileTests.cs create mode 100644 tests/TagLibSharp2.Tests/Core/SaveElsewhere.cs create mode 100644 tests/TagLibSharp2.Tests/Core/SaveToSourceTests.cs create mode 100644 tests/TagLibSharp2.Tests/Riff/RiffTagViewTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 66b5aa3d..32a417cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `WavFile.SaveToFile ()` and `AiffFile.SaveToFile ()` save back to `SourcePath` through the file system the file was read with (or the one given), as every other format does, so `file.Tag.Title = x; file.SaveToFile ();` works on WAV and AIFF (#235). They refuse as `SaveToFileAsync ()` does: a file not read from a path, or read with `SkipPictures`. `WavFile.Tag` and `AviFile.Tag` are public; each was only the explicit `IMediaFile.Tag`, so `wav.Tag` and `avi.Tag` did not compile on a `WavFile` or `AviFile` variable. On a WAV file with both an ID3v2 tag and an INFO list, `Tag` is now a view over both, ID3v2 first, so a set or `Clear` reaches both and ffprobe, ExifTool and MediaInfo show no stale copy (it was the ID3v2 tag alone, and the INFO list kept the old values). `AviFile.Tag` is the INFO tag, combined with the ID3v2 tag when there is one, and is never null, after `Dispose` too; on an AVI with no ID3v2 tag a field INFO cannot hold, such as a MusicBrainz ID, is not stored. After a successful save over its source a WAV, AVI or AIFF file's view goes on without a tag the save emptied and did not write, as a fresh read of the saved file has none, so the next value set through `Tag` goes where that read's would; the emptied tag stays the file's, so a value set later through a reference to it is written; a kept ID3v2 tag becomes a new ID3v2.4 tag, as a view creates one, and the view's next write that needs an ID3v2 tag uses it. After a save to another path the object still describes its source - `Mp4File.VideoProperties` (`VideoProperties?`) gives the width, height, codec, duration and rotation of the first video track, or null without one. Width and height are the sample entry's coded size, as ffprobe and MediaInfo report it: the track matrix is not applied and the pixel aspect ratio is ignored. An `mp4v` track's codec comes from its `esds` object type (MPEG-4, MPEG-1 Video, MPEG-2 Video, JPEG, PNG, JPEG 2000) - `VideoProperties.Rotation`: the clockwise rotation, 0 to 359 degrees, that the file asks a player to apply. MP4 and QuickTime read it from the track header matrix (0 when the matrix mirrors or skews the picture); Matroska reads `ProjectionPoseRoll` for a rectangular projection with no yaw or pitch. Other formats report 0 - JPEG `Tag.Title` reads and writes the title. It is stored in XMP `dc:title` as one `x-default` item, in a new XMP segment after the JFIF and Exif segments when the file has none, and read from there or from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A set or a clear removes every `XPTitle` through the plain-structure Exif edit, so ExifTool, Exiv2, macOS ImageIO, Spotlight and TagLib# show the new title. A title whose XMP would not fit in one 64 KB APP1 segment, or that XML cannot hold, is refused, as is an edit when extended XMP holds a title. IPTC `ObjectName` and Exif `ImageDescription` are not changed, so after a clear ImageIO can still show an IPTC `ObjectName` as the title diff --git a/src/TagLibSharp2/Aiff/AiffFile.cs b/src/TagLibSharp2/Aiff/AiffFile.cs index 6ac72bbc..51b4eeb9 100644 --- a/src/TagLibSharp2/Aiff/AiffFile.cs +++ b/src/TagLibSharp2/Aiff/AiffFile.cs @@ -104,9 +104,21 @@ internal void MarkPicturesSkipped () /// public Id3v2Tag? Id3v2Tag { get => _id3; - set => _id3 = value; + set { + _id3 = value; + _id3Gone = false; + } } + // The ID3 tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds it + // (review 2 B1) and written again once it holds a value, but the file holds no ID3 chunk, so the view goes on as a + // fresh read of that file does, its first write creating a tag. + internal Id3v2Tag? ViewId3 => _id3Gone && _id3 is { IsEmpty: true } ? null : _id3; + + // Whether the source holds no ID3 chunk for the tag held: set by a save over the source that wrote none, cleared by + // one that wrote it, and by an assignment. A save elsewhere leaves it as it was (contract suite round 3). + bool _id3Gone; + /// /// Gets the combined metadata view. /// @@ -724,12 +736,38 @@ static bool HasText (string[]? value) internal Id3v2Tag EnsureId3 () { - Id3Creation.BeforeWrite (() => [Id3v2Tag]); + Id3Creation.BeforeWrite (() => [ViewId3]); return Id3v2Tag!; } /// The ID3 tag the view creates on a first write, and drops while it stays empty. - internal TagCreation Id3Creation => _id3Creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag); + internal TagCreation Id3Creation => _id3Creation ??= new TagCreation (() => TakeGoneId3 () ?? new Id3v2Tag (), StoreCreatedId3); + + // The ID3 tag a view write creates on a file that holds none: the hidden tag the object kept, when there is one, so a + // caller who holds it still holds the file's tag (review 3 B1). A save over the source already made it a new tag + // (ResetToNew), so it is what a fresh read's view creates. + Id3v2Tag? TakeGoneId3 () + { + if (!_id3Gone || _id3 is not { IsEmpty: true } kept) + return null; + kept.ResetToNew (); + return kept; + } + + // A view write that leaves the tag it created empty removes it (TagCreation); the hidden tag the object kept is hidden + // again instead, as the file still holds no ID3 chunk. + void StoreCreatedId3 (Tag? tag) + { + if (tag is null && _id3 is { IsEmpty: true } && _id3Reused) { + _id3Gone = true; + return; + } + + _id3Reused = tag is not null && ReferenceEquals (tag, _id3) && _id3Gone; + Id3v2Tag = (Id3v2Tag?)tag; + } + + bool _id3Reused; TagCreation? _id3Creation; @@ -983,14 +1021,34 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (SaveRefusal () is { } refused) return refused; if (_skipped.Count == 0) - return SaveLoaded (path, fileSystem); + return SettleEmptyId3 (SaveLoaded (path, fileSystem), path, fileSystem); - return SaveFromSource (path, fileSystem, default); + return SettleEmptyId3 (SaveFromSource (path, fileSystem, default), path, fileSystem); } catch (Id3v2TagTooLargeException tooLarge) { return FileWriteResult.Failure (tooLarge.Message); } } + // A save writes no empty ID3 chunk. After a successful one over the source the file holds none, and the view goes on + // as a fresh read's (ViewId3); the tag itself stays attached. After a save elsewhere the object still describes its + // source, which holds the chunk (#235, review 1; contract suite round 3). + FileWriteResult SettleEmptyId3 (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (result.IsSuccess && (_id3 is { IsEmpty: true } || _id3Gone) + && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem)) { + _id3Gone = _id3 is { IsEmpty: true }; + // The tag kept is now the one a view creates on that file, so its next value is written as a fresh read's + // would be (review 3 B1). + if (_id3Gone) + _id3!.ResetToNew (); + } + + return result; + } + + async Task SettleEmptyId3 (Task save, string path, IFileSystem? fileSystem) => + SettleEmptyId3 (await save.ConfigureAwait (false), path, fileSystem); + FileWriteResult SaveLoaded (string path, IFileSystem? fileSystem) { var fs = fileSystem ?? _sourceFileSystem; @@ -1092,10 +1150,10 @@ public Task SaveToFileAsync ( if (SaveRefusal () is { } refused) return Task.FromResult (refused); if (_skipped.Count == 0) - return SaveLoadedAsync (path, fileSystem, cancellationToken); + return SettleEmptyId3 (SaveLoadedAsync (path, fileSystem, cancellationToken), path, fileSystem); // "Was not loaded" and a short source are decided before the token, matching the sync save. - return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + return Task.FromResult (SettleEmptyId3 (SaveFromSource (path, fileSystem, cancellationToken), path, fileSystem)); } catch (Id3v2TagTooLargeException tooLarge) { return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); } @@ -1321,6 +1379,33 @@ void WritePlanned (Stream output, Stream source, List chunks, long ch } } + /// + /// Saves the AIFF file back to its source path. + /// + /// + /// This convenience method saves the file back to the path it was read from, through the file system it was read + /// with unless is given, as does. + /// Requires that the file was read using or + /// . + /// + /// Optional file system abstraction. + /// The write result. + public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) + { + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + var fs = fileSystem ?? _sourceFileSystem; + return SaveToFile (SourcePath!, fs); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } + } + /// /// Saves the AIFF file back to its source path asynchronously. /// diff --git a/src/TagLibSharp2/Aiff/AiffTag.cs b/src/TagLibSharp2/Aiff/AiffTag.cs index f7d087f4..466593b0 100644 --- a/src/TagLibSharp2/Aiff/AiffTag.cs +++ b/src/TagLibSharp2/Aiff/AiffTag.cs @@ -532,7 +532,7 @@ public override bool RemoveCustomField (string name) return removed; } - Id3v2Tag? Id3 => _file.Id3v2Tag; + Id3v2Tag? Id3 => _file.ViewId3; /// /// diff --git a/src/TagLibSharp2/Core/SavedOverSource.cs b/src/TagLibSharp2/Core/SavedOverSource.cs index f51e0fe5..80e96539 100644 --- a/src/TagLibSharp2/Core/SavedOverSource.cs +++ b/src/TagLibSharp2/Core/SavedOverSource.cs @@ -53,6 +53,81 @@ public static bool Holds (string? sourcePath, IFileSystem? fileSystem, long leng } } + /// + /// Whether the file at now holds exactly what the save wrote to : + /// as long, byte for byte. That is true after a save over the source under any spelling of its path, and false after + /// a save elsewhere, which leaves the source as it was, unless the source already held those bytes, when a fresh read + /// of either file is the same. A carrier asks it before it drops a tag a save emptied and did not write: after a save + /// elsewhere the object still describes its source, which holds that tag (contract suite round 3). A source or a + /// written file that cannot be read answers false. Both files are read in chunks, and only when the save could have + /// gone to an alias of the source: a save to the same full path on the same file system wrote over the source, and + /// answers true without a read (review 3). Another process that rewrites the source between the save and the compare + /// gets whatever answer its bytes give; a wrong false only keeps the object's earlier bookkeeping, as a save elsewhere + /// does. + /// + public static bool HoldsFile (string? sourcePath, IFileSystem? sourceFileSystem, string path, IFileSystem? fileSystem) + { + if (sourcePath is null) + return false; + if (SamePath (sourcePath, sourceFileSystem, path, fileSystem)) + return true; + + byte[]? left = null; + byte[]? right = null; + try { + using var source = (sourceFileSystem ?? DefaultFileSystem.Instance).OpenRead (sourcePath); + using var written = (fileSystem ?? DefaultFileSystem.Instance).OpenRead (path); + if (source.Length != written.Length) + return false; + + left = StreamCopy.Rent (); + right = StreamCopy.Rent (); + var remaining = source.Length; + while (remaining > 0) { + var count = (int)Math.Min (left.Length, remaining); + if (!ReadAll (source, left, count) || !ReadAll (written, right, count) + || !left.AsSpan (0, count).SequenceEqual (right.AsSpan (0, count))) + return false; + remaining -= count; + } + + return true; + } catch (Exception ex) when (IsReadBackFailure (ex)) { + return false; + } finally { + if (left is not null) + StreamCopy.Return (left); + if (right is not null) + StreamCopy.Return (right); + } + } + + // The same full path, compared ordinally, on the same file system instance. A path that differs only by case, a link + // or another spelling the full path does not settle falls through to the compare. + static bool SamePath (string sourcePath, IFileSystem? sourceFileSystem, string path, IFileSystem? fileSystem) + { + if (!ReferenceEquals (sourceFileSystem ?? DefaultFileSystem.Instance, fileSystem ?? DefaultFileSystem.Instance)) + return false; + try { + return string.Equals (Path.GetFullPath (sourcePath), Path.GetFullPath (path), StringComparison.Ordinal); + } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException or System.Security.SecurityException) { + return false; + } + } + + static bool ReadAll (Stream stream, byte[] buffer, int count) + { + var done = 0; + while (done < count) { + var read = stream.Read (buffer, done, count - done); + if (read <= 0) + return false; + done += read; + } + + return true; + } + /// /// The failures a read-back after a save can meet. The save has committed by then, so none of them turns its /// success into a failure; the object keeps the offsets it had. diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index a542dd8c..309b70eb 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -107,9 +107,21 @@ public sealed partial class Id3v2Tag : Tag /// file reports 3. A frame this library does not read, or cannot parse, is written back as it was stored, flags /// included, when the tag is saved in the version it was read in, and a v2.2 one under its v2.3 ID (UnreadFrame). /// A v2.2 frame with no v2.3 ID (CRM, experimental IDs) is not written back, nor is a v2.2 LNK or a - /// v2.2 PIC that cannot be parsed. + /// v2.2 PIC that cannot be parsed. A WAV, AIFF or AVI file that keeps this tag after a save over its source + /// wrote it empty makes it a new tag, as a view creates one: version 4 from then on. /// - public int Version { get; } + public int Version { get; private set; } + + /// + /// Makes this tag the one a view creates for a file that holds no ID3v2 tag (new Id3v2Tag ()): no frame, and + /// ID3v2.4. A file whose save over its source wrote no ID3v2 tag, as this one was empty, keeps this instance for a + /// caller who holds it (review 2 B1, review 3 B1), so its next value is written as a fresh read's view would write it. + /// + internal void ResetToNew () + { + Clear (); + Version = (int)Id3v2Version.V24; + } /// public override TagTypes TagType => TagTypes.Id3v2; diff --git a/src/TagLibSharp2/Riff/AviFile.cs b/src/TagLibSharp2/Riff/AviFile.cs index dd960395..1b90ca8c 100644 --- a/src/TagLibSharp2/Riff/AviFile.cs +++ b/src/TagLibSharp2/Riff/AviFile.cs @@ -111,7 +111,24 @@ internal void MarkPicturesSkipped () /// null removes the chunk the tag was read from. A chunk this reader could not parse is kept /// while this property stays null. /// - public Id3v2Tag? Id3v2Tag { get; set; } + public Id3v2Tag? Id3v2Tag { + get => _id3v2Tag; + set { + _id3v2Tag = value; + _id3Gone = false; + } + } + + Id3v2Tag? _id3v2Tag; + + // The ID3v2 tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds + // it (review 2 B1) and written again once it holds a value, but the file holds no such chunk, so the view goes on as + // a fresh read of that file does, over the INFO list alone (review 1 N7). + Id3v2Tag? ViewId3 => _id3Gone && _id3v2Tag is { IsEmpty: true } ? null : _id3v2Tag; + + // Whether the source holds no chunk for the tag held: set by a save over the source that wrote none, cleared by one + // that wrote it, and by an assignment. A save elsewhere leaves it as it was (contract suite round 3). + bool _id3Gone; /// Gets the duration of the file. /// @@ -138,11 +155,20 @@ internal void MarkPicturesSkipped () /// Gets . public MediaFormat Format => MediaFormat.Avi; - /// - /// The INFO tag, combined with the ID3v2 tag when there is one. The INFO tag comes first. - Tag? IMediaFile.Tag => UnifiedTag; + /// Gets the file's tag view. + /// + /// The INFO tag, combined with the ID3v2 tag when there is one; the INFO tag comes first, and a set or + /// writes both. INFO holds only its own fields (title, artist, album, comment, genre, year, + /// track, copyright and custom INFO fields): on a file with no ID3v2 tag a field it cannot hold, such as a + /// MusicBrainz ID, is not stored; assign first to keep one. A save writes no empty ID3v2 tag, + /// and after a successful save over the source that emptied it this view is the INFO tag alone, as a fresh read of + /// the file finds no ID3v2 tag; keeps it, as a new ID3v2.4 tag, so a value set later through it is written. A save + /// to another path changes neither. Never null, after too, as AsfFile.Tag and MatroskaFile.Tag. + /// + public Tag Tag => ViewId3 is { } id3 ? new CombinedTag (InfoTag, id3) : InfoTag; - internal Tag UnifiedTag => Id3v2Tag is null ? InfoTag : new CombinedTag (InfoTag, Id3v2Tag); + /// + Tag? IMediaFile.Tag => Tag; IMediaProperties? IMediaFile.AudioProperties => AudioProperties; @@ -475,7 +501,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, if (!AviRewrite.TryRewrite (originalData, InfoTag, Id3v2Tag, out var rewritten, out var error)) return FileWriteResult.Failure (error); - return Source.Saved (AtomicFileWriter.Write (path, rewritten, fileSystem ?? _sourceFileSystem)); + return Saved (AtomicFileWriter.Write (path, rewritten, fileSystem ?? _sourceFileSystem), path, fileSystem); } catch (Id3v2TagTooLargeException tooLarge) { return FileWriteResult.Failure (tooLarge.Message); } @@ -495,7 +521,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (string.IsNullOrEmpty (SourcePath)) return FileWriteResult.Failure ("No source path available. File was not read from disk."); - return Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, CancellationToken.None)); + return Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, CancellationToken.None), path, fileSystem); } catch (Id3v2TagTooLargeException tooLarge) { return FileWriteResult.Failure (tooLarge.Message); } @@ -543,7 +569,7 @@ public Task SaveToFileAsync ( if (!AviRewrite.TryRewrite (originalData.Span, InfoTag, Id3v2Tag, out var rewritten, out var error)) return Task.FromResult (FileWriteResult.Failure (error)); - return Source.Saved (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem ?? _sourceFileSystem, cancellationToken)); + return Saved (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem ?? _sourceFileSystem, cancellationToken), path, fileSystem); } catch (Id3v2TagTooLargeException tooLarge) { return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); } @@ -567,7 +593,7 @@ public Task SaveToFileAsync ( if (string.IsNullOrEmpty (SourcePath)) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - return Task.FromResult (Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + return Task.FromResult (Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken), path, fileSystem)); } catch (Id3v2TagTooLargeException tooLarge) { return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); } @@ -631,6 +657,26 @@ public Task SaveToFileAsync ( } } + // A successful save describes the file it wrote (SourceLength). It writes no empty ID3v2 tag, so after one over the + // source the file holds none, and the view goes on as a fresh read's (ViewId3); the tag itself stays attached. After a + // save elsewhere the object still describes its source, which holds the tag (contract suite round 3). + FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (result.IsSuccess && (_id3v2Tag is { IsEmpty: true } || _id3Gone) + && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem)) { + _id3Gone = _id3v2Tag is { IsEmpty: true }; + // The tag kept is now a new one, as a tag assigned to the saved file would be, so its next value is written as + // that one's (review 3 B1). + if (_id3Gone) + _id3v2Tag!.ResetToNew (); + } + + return Source.Saved (result); + } + + async Task Saved (Task save, string path, IFileSystem? fileSystem) => + Saved (await save.ConfigureAwait (false), path, fileSystem); + /// Releases the tags held by this instance. public void Dispose () { diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs index 5e74ef96..38fa814c 100644 --- a/src/TagLibSharp2/Riff/WavFile.cs +++ b/src/TagLibSharp2/Riff/WavFile.cs @@ -80,7 +80,15 @@ internal void MarkPicturesSkipped () /// Every LIST INFO is merged into this tag. The first list wins, and save writes exactly one INFO list. /// Save writes that merged list at the end, not in its original position. /// - public RiffInfoTag? InfoTag { get; set; } + public RiffInfoTag? InfoTag { + get => _infoTag; + set { + _infoTag = value; + _infoGone = false; + } + } + + RiffInfoTag? _infoTag; /// /// Gets or sets the ID3v2 tag. @@ -93,7 +101,15 @@ internal void MarkPicturesSkipped () /// stays null. Assigning an , including new Id3v2Tag(), /// replaces that unparsed chunk. /// - public Id3v2Tag? Id3v2Tag { get; set; } + public Id3v2Tag? Id3v2Tag { + get => _id3v2Tag; + set { + _id3v2Tag = value; + _id3Gone = false; + } + } + + Id3v2Tag? _id3v2Tag; /// /// Gets or sets the BWF bext tag (Broadcast Wave Extension). @@ -140,22 +156,99 @@ internal void MarkPicturesSkipped () /// /// - /// The ID3v2 tag when the file has one, else the RIFF INFO tag. A file with neither has a view whose first write - /// creates an ID3v2 tag (the id3 chunk), which holds several values per field where INFO holds one and - /// declares its text encoding where INFO has none; ffprobe, ExifTool and MediaInfo read it. A write that leaves that tag empty removes it - /// again. Reading the view creates nothing, so and stay null. + /// + /// A file with both an ID3v2 tag and a RIFF INFO list has a view over both, ID3v2 first: a get returns the ID3v2 + /// value, else the INFO one, and a set or writes both, so ffprobe, ExifTool and MediaInfo, + /// which read both, show no stale copy (INFO holds one value per field and only its own fields; a field it cannot + /// hold is written to ID3v2 alone). A file with only one of them has that tag. + /// + /// + /// A file with neither has a view whose first write creates an ID3v2 tag (the id3 chunk), which holds + /// several values per field where INFO holds one and declares its text encoding where INFO has none; ffprobe, + /// ExifTool and MediaInfo read it. A write that leaves that tag empty removes it again. Reading the view creates + /// nothing, so and stay null. A save writes no empty tag. After a + /// successful save over its source this view goes on without a tag the save emptied, as a fresh read of the saved + /// file holds none; and keep it, so a value set later through them is + /// written. The kept ID3v2 tag becomes a new ID3v2.4 tag, as a view creates one, and a view write that needs an + /// ID3v2 tag uses it. A save to another path changes neither. + /// + /// Null after . /// - Tag? IMediaFile.Tag { + public Tag? Tag { get { if (_disposed) return null; - if (Id3v2Tag is null && InfoTag is not null) - return InfoTag; - return CombinedTag.SingleOrView (Id3v2Tag, () => Id3v2Tag, - _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); + var id3 = ViewId3; + var info = ViewInfo; + if (id3 is not null && info is not null) + return new CombinedTag (id3, info); + if (id3 is null && info is not null) + return info; + return CombinedTag.SingleOrView (id3, () => ViewId3, + _creation ??= new TagCreation (() => TakeGoneId3 () ?? new Id3v2Tag (), StoreCreatedId3)); + } + } + + // The tags a view shows: an emptied tag a save over the source did not write is held for a caller who holds it + // (review 2 B1) and written again once it holds a value, but the file holds no such tag, so the view goes on as a + // fresh read of that file does: without it, its first write creating an ID3v2 tag (review 1 N7). + Id3v2Tag? ViewId3 => _id3Gone && _id3v2Tag is { IsEmpty: true } ? null : _id3v2Tag; + + RiffInfoTag? ViewInfo => _infoGone && _infoTag is { IsEmpty: true } ? null : _infoTag; + + // Whether the source holds no tag of the instance held: set by a save over the source that wrote none, as the tag was + // empty; cleared by one that wrote it, and by an assignment. A save elsewhere leaves the source, and these, as they + // were (contract suite round 3, R2). + bool _id3Gone; + bool _infoGone; + + // The ID3v2 tag a view write creates on a file that holds none: the hidden tag the object kept, when there is one, so + // a caller who holds it still holds the file's tag (review 3 B1). A save over the source already made it a new tag + // (ResetToNew), so it is what a fresh read's view creates. + Id3v2Tag? TakeGoneId3 () + { + if (!_id3Gone || _id3v2Tag is not { IsEmpty: true } kept) + return null; + kept.ResetToNew (); + return kept; + } + + // A view write that leaves the tag it created empty removes it (TagCreation); the hidden tag the object kept is hidden + // again instead, as the file still holds none. + void StoreCreatedId3 (Tag? tag) + { + if (tag is null && _id3v2Tag is { IsEmpty: true } && _id3Reused) { + _id3Gone = true; + return; + } + + _id3Reused = tag is not null && ReferenceEquals (tag, _id3v2Tag) && _id3Gone; + Id3v2Tag = (Id3v2Tag?)tag; + } + + bool _id3Reused; + + FileWriteResult SettleEmptyTags (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (!result.IsSuccess + || (_id3v2Tag is not { IsEmpty: true } && _infoTag is not { IsEmpty: true } && !_id3Gone && !_infoGone) + || !SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem, path, fileSystem ?? _sourceFileSystem)) + return result; + + _id3Gone = _id3v2Tag is { IsEmpty: true }; + _infoGone = _infoTag is { IsEmpty: true }; + // The empty tag replaced any id3 chunk the read could not parse; the file written holds none. The tag kept is now + // the one a view creates on that file, so its next value is written as a fresh read's would be (review 3 B1). + if (_id3Gone) { + _keepUnparsedId3 = false; + _id3v2Tag!.ResetToNew (); } + return result; } + async Task SettleEmptyTags (Task save, string path, IFileSystem? fileSystem) => + SettleEmptyTags (await save.ConfigureAwait (false), path, fileSystem); + TagCreation? _creation; /// @@ -706,9 +799,9 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) return failure; if (_skippedChunks.Count == 0) - return SaveLoaded (path, fileSystem); + return SettleEmptyTags (SaveLoaded (path, fileSystem), path, fileSystem); - return SaveFromSource (path, fileSystem, default); + return SettleEmptyTags (SaveFromSource (path, fileSystem, default), path, fileSystem); } catch (Id3v2TagTooLargeException tooLarge) { return FileWriteResult.Failure (tooLarge.Message); } @@ -736,10 +829,10 @@ public Task SaveToFileAsync ( return Task.FromResult (failure); if (_skippedChunks.Count == 0) - return SaveLoadedAsync (path, fileSystem, cancellationToken); + return SettleEmptyTags (SaveLoadedAsync (path, fileSystem, cancellationToken), path, fileSystem); // Length and "was not loaded" are decided before the token, matching the sync save. - return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + return Task.FromResult (SettleEmptyTags (SaveFromSource (path, fileSystem, cancellationToken), path, fileSystem)); } catch (Id3v2TagTooLargeException tooLarge) { return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); } @@ -1112,6 +1205,33 @@ public WavSavePiece (string fourCC, byte[]? inline, int skippedIndex, long size) public long Size { get; } } + /// + /// Saves the WAV file back to its source path. + /// + /// + /// This convenience method saves the file back to the path it was read from, through the file system it was read + /// with unless is given, as does. + /// Requires that the file was read using or + /// . + /// + /// Optional file system abstraction. + /// The write result. + public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) + { + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + var fs = fileSystem ?? _sourceFileSystem; + return SaveToFile (SourcePath!, fs); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } + } + /// /// Saves the WAV file back to its source path asynchronously. /// diff --git a/tests/TagLibSharp2.Tests/Core/HoldsFileTests.cs b/tests/TagLibSharp2.Tests/Core/HoldsFileTests.cs new file mode 100644 index 00000000..39463bae --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/HoldsFileTests.cs @@ -0,0 +1,61 @@ +// 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.Tests.Kit; + +namespace TagLibSharp2.Tests.Core; + +/// +/// SavedOverSource.HoldsFile, which a carrier asks before it settles a tag a save emptied: a save to the source's own +/// full path on its own file system answers true without reading either file (review 3); another spelling of that +/// path is compared byte for byte; another file is not the source. +/// +[TestClass] +[TestCategory ("Unit")] +public sealed class HoldsFileTests +{ + static readonly byte[] Bytes = [1, 2, 3, 4, 5]; + + [TestMethod] + public void SamePath_SameFileSystem_IsTrueWithoutARead () + { + var files = new CountingFileSystem (); + files.AddFile ("/dir/f.wav", Bytes); + + Assert.IsTrue (SavedOverSource.HoldsFile ("/dir/f.wav", files, "/dir/f.wav", files)); + Assert.AreEqual (0L, files.BytesRead); + } + + [TestMethod] + public void AnotherSpelling_IsCompared () + { + var files = new CountingFileSystem (); + files.AddFile ("/dir/f.wav", Bytes); + files.AddFile ("/dir/sub/../g.wav", Bytes); + + Assert.IsTrue (SavedOverSource.HoldsFile ("/dir/f.wav", files, "/dir/sub/../g.wav", files), "same bytes"); + Assert.AreEqual (2L * Bytes.Length, files.BytesRead); + } + + [TestMethod] + public void AnotherFile_IsNotTheSource () + { + var files = new CountingFileSystem (); + files.AddFile ("/dir/f.wav", Bytes); + files.AddFile ("/dir/g.wav", [1, 2, 3, 4, 6]); + + Assert.IsFalse (SavedOverSource.HoldsFile ("/dir/f.wav", files, "/dir/g.wav", files)); + } + + [TestMethod] + public void SamePath_AnotherFileSystem_IsCompared () + { + var source = new CountingFileSystem (); + source.AddFile ("/dir/f.wav", Bytes); + var other = new MockFileSystem (); + other.AddFile ("/dir/f.wav", [9, 9]); + + Assert.IsFalse (SavedOverSource.HoldsFile ("/dir/f.wav", source, "/dir/f.wav", other)); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SaveElsewhere.cs b/tests/TagLibSharp2.Tests/Core/SaveElsewhere.cs new file mode 100644 index 00000000..30afb595 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SaveElsewhere.cs @@ -0,0 +1,56 @@ +// 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; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A save to another path leaves the object describing its source: read a file, edit, save to another path, edit +/// again, save to another path again; the second save writes what a fresh read of the source, given both edits, writes +/// (the contract suite's save-after-save shape, path-other entry). Both saves go through the sync and the async path save. +/// +internal static class SaveElsewhere +{ + static readonly bool[] Modes = [false, true]; + + public static void AssertSecondSaveIsFresh (byte[] source, string extension, Action first, Action second, string cell) + { + foreach (var async in Modes) { + var files = new MockFileSystem (); + var path = "/s" + extension; + var other = "/o" + extension; + files.AddFile (path, source); + using var file = (IMediaFile)MediaFile.Read (path, files).File!; + + first (file); + Save (file, other, files, async); + CollectionAssert.AreEqual (Fresh (source, extension, first), files.ReadAllBytes (other), $"{cell} (async {async}): the first save"); + + second (file); + Save (file, other, files, async); + CollectionAssert.AreEqual (Fresh (source, extension, first, second), files.ReadAllBytes (other), $"{cell} (async {async}): the second save"); + } + } + + static byte[] Fresh (byte[] source, string extension, params Action[] edits) + { + var files = new MockFileSystem (); + var path = "/s" + extension; + files.AddFile (path, source); + using var file = (IMediaFile)MediaFile.Read (path, files).File!; + foreach (var edit in edits) + edit (file); + Save (file, "/o" + extension, files, async: false); + return files.ReadAllBytes ("/o" + extension); + } + + static void Save (IMediaFile file, string path, MockFileSystem files, bool async) + { + dynamic typed = file; + FileWriteResult result = async + ? typed.SaveToFileAsync (path, (IFileSystem)files, CancellationToken.None).GetAwaiter ().GetResult () + : typed.SaveToFile (path, (IFileSystem)files); + Assert.IsTrue (result.IsSuccess, result.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SaveToSourceTests.cs b/tests/TagLibSharp2.Tests/Core/SaveToSourceTests.cs new file mode 100644 index 00000000..4e699622 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/SaveToSourceTests.cs @@ -0,0 +1,123 @@ +// 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; + +namespace TagLibSharp2.Tests.Core; + +/// +/// The documented edit, file.Tag.Title = x; file.SaveToFile ();, works on every format read from a path: each +/// format has a public Tag and a SaveToFile () that writes back to SourcePath through the file +/// system the file was read with (#235). +/// +[TestClass] +[TestCategory ("Unit")] +public class SaveToSourceTests +{ + const string Path = "/music/file"; + + // MP4's public Tag is its ilst, null until a tag exists (CHANGELOG, "Tag is no longer null"); IMediaFile.Tag is the + // view there. + static readonly string[] TagIsNotTheView = ["m4a"]; + + public static IEnumerable Formats => TaglessFixtures.All.Keys.Select (key => new object[] { key }); + + /// The public Tag is the view returns, so a write through it is saved. + [TestMethod] + [DynamicData (nameof (Formats))] + public void PublicTag_IsTheView (string format) + { + if (Array.IndexOf (TagIsNotTheView, format) >= 0) + return; + var (file, _) = ReadFromPath (format); + + dynamic typed = file; + Tag tag = typed.Tag; + tag.Title = "Through the public Tag"; + + Assert.AreEqual ("Through the public Tag", file.Tag!.Title, format); + } + + /// + /// SaveToFile () with no path saves to the source through the file system the read used, as + /// SaveToFileAsync () does, and the saved file holds the edit. + /// + [TestMethod] + [DynamicData (nameof (Formats))] + public void SaveToFile_NoPath_SavesBackToTheSourceAsTheAsyncSaveDoes (string format) + { + var (file, files) = ReadFromPath (format); + file.Tag!.Title = "Saved"; + + dynamic typed = file; + FileWriteResult saved = typed.SaveToFile (); + + Assert.IsTrue (saved.IsSuccess, $"{format}: {saved.Error}"); + var written = files.ReadAllBytes (PathOf (format)); + var again = MediaFile.ReadFromData (written, PathOf (format)); + Assert.AreEqual ("Saved", ((IMediaFile)again.File!).Tag!.Title, format); + + var (asyncFile, asyncFiles) = ReadFromPath (format); + asyncFile.Tag!.Title = "Saved"; + dynamic asyncTyped = asyncFile; + FileWriteResult asyncSaved = ((Task)asyncTyped.SaveToFileAsync ()).GetAwaiter ().GetResult (); + Assert.IsTrue (asyncSaved.IsSuccess, $"{format}: {asyncSaved.Error}"); + CollectionAssert.AreEqual (asyncFiles.ReadAllBytes (PathOf (format)), written, $"{format}: the sync and async saves differ"); + } + + /// A file system passed to SaveToFile (fileSystem) is the one it writes to. + [TestMethod] + [DynamicData (nameof (Formats))] + public void SaveToFile_NoPath_WritesToTheFileSystemGiven (string format) + { + var (file, files) = ReadFromPath (format); + file.Tag!.Title = "Elsewhere"; + var other = new MockFileSystem (); + other.AddFile (PathOf (format), files.ReadAllBytes (PathOf (format))); + + dynamic typed = file; + FileWriteResult saved = typed.SaveToFile ((IFileSystem)other); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var written = MediaFile.ReadFromData (other.ReadAllBytes (PathOf (format)), PathOf (format)); + Assert.AreEqual ("Elsewhere", ((IMediaFile)written.File!).Tag!.Title); + Assert.IsNull (((IMediaFile)MediaFile.ReadFromData (files.ReadAllBytes (PathOf (format)), PathOf (format)).File!).Tag!.Title); + } + + /// A file not read from a path has no source to save to, and a SkipPictures read refuses, as the async save does. + [TestMethod] + [DataRow ("wav", false)] + [DataRow ("aiff", false)] + [DataRow ("wav", true)] + [DataRow ("aiff", true)] + public void SaveToFile_NoPath_RefusesAsTheAsyncSaveDoes (string format, bool skipPictures) + { + var bytes = TaglessFixtures.All[format].Build (); + IMediaFile file; + if (skipPictures) { + var files = new MockFileSystem (); + files.AddFile (PathOf (format), bytes); + file = (IMediaFile)MediaFile.Read (PathOf (format), new MediaReadOptions { SkipPictures = true }, files).File!; + } else { + file = (IMediaFile)MediaFile.ReadFromData (bytes, PathOf (format)).File!; + } + + dynamic typed = file; + FileWriteResult saved = typed.SaveToFile (); + FileWriteResult asyncSaved = ((Task)typed.SaveToFileAsync ()).GetAwaiter ().GetResult (); + + Assert.IsFalse (saved.IsSuccess, format); + Assert.AreEqual (asyncSaved.Error, saved.Error, format); + } + + static string PathOf (string format) => Path + TaglessFixtures.All[format].Extension; + + static (IMediaFile File, MockFileSystem Files) ReadFromPath (string format) + { + var files = new MockFileSystem (); + files.AddFile (PathOf (format), TaglessFixtures.All[format].Build ()); + var read = MediaFile.Read (PathOf (format), files); + Assert.IsTrue (read.IsSuccess, $"{format}: {read.Error}"); + return ((IMediaFile)read.File!, files); + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 955ef0ad..c588221c 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -125,6 +125,7 @@ namespace TagLibSharp2.Aiff public void Dispose() { } public TagLibSharp2.Aiff.AiffChunk? GetChunk(string fourCC) { } public TagLibSharp2.Core.BinaryData Render() { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(TagLibSharp2.Core.IFileSystem? fileSystem = null) { } public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } public System.Threading.Tasks.Task SaveToFileAsync(TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } public System.Threading.Tasks.Task SaveToFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } @@ -3374,6 +3375,7 @@ namespace TagLibSharp2.Riff public TagLibSharp2.Core.MediaTypes MediaTypes { get; } public bool PicturesLoaded { get; } public string? SourcePath { get; } + public TagLibSharp2.Core.Tag Tag { get; } public TagLibSharp2.Core.VideoProperties? VideoProperties { get; } public void Dispose() { } public TagLibSharp2.Core.BinaryData Render(System.ReadOnlySpan originalData) { } @@ -3564,11 +3566,13 @@ namespace TagLibSharp2.Riff public bool PicturesLoaded { get; } public TagLibSharp2.Core.AudioProperties Properties { get; } public string? SourcePath { get; } + public TagLibSharp2.Core.Tag? Tag { get; } public string? Title { get; } public uint? Track { get; } public string? Year { get; } public void Dispose() { } public TagLibSharp2.Core.BinaryData Render() { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(TagLibSharp2.Core.IFileSystem? fileSystem = null) { } public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } public System.Threading.Tasks.Task SaveToFileAsync(TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } public System.Threading.Tasks.Task SaveToFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } diff --git a/tests/TagLibSharp2.Tests/Riff/RiffTagViewTests.cs b/tests/TagLibSharp2.Tests/Riff/RiffTagViewTests.cs new file mode 100644 index 00000000..817390f4 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Riff/RiffTagViewTests.cs @@ -0,0 +1,334 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Aiff; +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Riff; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Riff; + +/// +/// The public tag views of WAV, AVI and AIFF (#235) reach every store a reader shows (review 1 N6, N7): a set through +/// Tag writes the ID3v2 tag and the INFO list (or the AIFF text chunks) alike, Clear clears them all, and +/// after a save the object goes on as a fresh read of the saved file does. +/// +[TestClass] +[TestCategory ("Unit")] +public class RiffTagViewTests +{ + static readonly string[] InfoFields = ["Title", "Artist", "Album", "Comment", "Genre", "Year", "Copyright"]; + + public static IEnumerable Fields => InfoFields.Select (name => new object[] { name }); + + /// A WAV with an INFO list and an ID3v2 tag holding the same fields, as sample.wav holds them. + static byte[] WavWithBoth () + { + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal (soundBytes: 64)).File!; + wav.InfoTag = new RiffInfoTag (); + wav.Id3v2Tag = new Id3v2Tag (Id3v2Version.V23); + Tag[] tags = [wav.InfoTag, wav.Id3v2Tag]; + foreach (var tag in tags) { + foreach (var field in InfoFields) + typeof (Tag).GetProperty (field)!.SetValue (tag, field == "Year" ? "2009" : "Old " + field); + } + + var files = new MockFileSystem (); + Assert.IsTrue (wav.SaveToFile ("/w.wav", files).IsSuccess); + return files.ReadAllBytes ("/w.wav"); + } + + [TestMethod] + [DynamicData (nameof (Fields))] + public void Wav_SetThroughTag_WritesBothTags (string field) + { + var files = new MockFileSystem (); + files.AddFile ("/w.wav", WavWithBoth ()); + var wav = WavFile.ReadFromFile ("/w.wav", files).File!; + var value = field == "Year" ? "2024" : "New " + field; + + typeof (Tag).GetProperty (field)!.SetValue (wav.Tag, value); + Assert.IsTrue (wav.SaveToFile ().IsSuccess); + + var again = WavFile.Read (files.ReadAllBytes ("/w.wav")).File!; + Assert.AreEqual (value, typeof (Tag).GetProperty (field)!.GetValue (again.Id3v2Tag), $"{field}: ID3v2"); + Assert.AreEqual (value, typeof (Tag).GetProperty (field)!.GetValue (again.InfoTag), $"{field}: INFO"); + } + + [TestMethod] + public void Wav_ClearThroughTag_RemovesBothTags () + { + var files = new MockFileSystem (); + files.AddFile ("/w.wav", WavWithBoth ()); + var wav = WavFile.ReadFromFile ("/w.wav", files).File!; + + wav.Tag!.Clear (); + Assert.IsTrue (wav.SaveToFile ().IsSuccess); + + var again = WavFile.Read (files.ReadAllBytes ("/w.wav")).File!; + Assert.IsNull (again.InfoTag, "INFO"); + Assert.IsNull (again.Id3v2Tag, "ID3v2"); + } + + static readonly string[] Steps = ["clear", "title", "musicbrainz"]; + + static readonly string[] Formats = ["wav", "avi", "aiff"]; + + public static IEnumerable Sequences => + from format in Formats + from first in Steps + from second in Steps + select new object[] { format, first, second }; + + /// + /// {WAV, AVI, AIFF} x {first edit, save} x {second edit, save}: the object's second save is the fresh read's, so a + /// value set after a Clear is stored, or not, as a fresh read of the cleared file stores it (review 1 N7). + /// + [TestMethod] + [DynamicData (nameof (Sequences))] + public void SaveAfterSave_IsTheFreshReadsSave (string format, string first, string second) + { + var path = "/f." + format; + var files = new MockFileSystem (); + files.AddFile (path, Build (format)); + var file = (IMediaFile)MediaFile.Read (path, files).File!; + Apply (file, first); + Save (file, files); + var fresh = new MockFileSystem (); + fresh.AddFile (path, files.ReadAllBytes (path)); + + Apply (file, second); + Save (file, files); + var reread = (IMediaFile)MediaFile.Read (path, fresh).File!; + Apply (reread, second); + Save (reread, fresh); + + CollectionAssert.AreEqual (fresh.ReadAllBytes (path), files.ReadAllBytes (path), $"{format}: {first}, then {second}"); + } + + static readonly string[] ElsewhereFormats = ["wav", "wav-info", "avi", "aiff"]; + static readonly string[] Emptying = ["clear", "title-null"]; + static readonly string[] ElsewhereSeconds = ["title", "custom", "musicbrainz"]; + + public static IEnumerable ElsewhereSequences => + from format in ElsewhereFormats + from first in Emptying + from second in ElsewhereSeconds + select new object[] { format, first, second }; + + /// + /// {WAV with both tags, WAV with INFO only, AVI, AIFF} x {Clear, Title = null} x {second edit}, each saved to another + /// path: the object still describes its source, so the second save is a fresh read's of the source given both edits. + /// A save elsewhere does not drop the tag the edit emptied (contract suite round 3, R2). + /// + [TestMethod] + [DynamicData (nameof (ElsewhereSequences))] + public void SaveElsewhereTwice_IsTheFreshReadsSave (string format, string first, string second) + { + var extension = format == "aiff" ? ".aif" : "." + format[..3]; + SaveElsewhere.AssertSecondSaveIsFresh (Build (format), extension, file => Apply (file, first), file => Apply (file, second), + $"{format}: {first}, then {second}"); + } + + static readonly bool[] HeldFirst = [true, false]; + + public static IEnumerable HeldAndViewCases => + from format in Formats + from heldFirst in HeldFirst + select new object[] { format, heldFirst }; + + /// + /// {WAV, AVI, AIFF} x {held edit first, view edit first}: Clear through the view and a save over the source write no + /// ID3v2 tag; then a title through the view and an artist through the ID3v2 tag the caller held are both written, + /// the held tag is still the file's, and the bytes are a fresh read's of the saved file given the same edits (its + /// ID3v2 tag, or a new one assigned when it has none, standing for the held one) (review 3 B1). + /// + [TestMethod] + [DynamicData (nameof (HeldAndViewCases))] + public void ClearSave_ThenViewAndHeldEdits_AreBothWritten (string format, bool heldFirst) + { + var extension = format == "aiff" ? ".aif" : "." + format; + var path = "/f" + extension; + var files = new MockFileSystem (); + files.AddFile (path, Build (format)); + using var file = (IMediaFile)MediaFile.Read (path, files).File!; + var held = HeldId3 (file); + Assert.IsNotNull (held); + file.Tag!.Clear (); + Save (file, files); + var cleared = files.ReadAllBytes (path); + + Edit (file, held, heldFirst); + Save (file, files); + + Assert.AreSame (held, HeldId3 (file), $"{format}: the held tag is the file's"); + var written = files.ReadAllBytes (path); + var reread = new MockFileSystem (); + reread.AddFile (path, written); + using (var again = (IMediaFile)MediaFile.Read (path, reread).File!) { + Assert.AreEqual ("LATER", again.Tag!.Title, $"{format}: the view's title"); + Assert.AreEqual ("HELD", HeldId3 (again)?.Artist, $"{format}: the held tag's artist"); + } + + var fresh = new MockFileSystem (); + fresh.AddFile (path, cleared); + using var other = (IMediaFile)MediaFile.Read (path, fresh).File!; + Edit (other, null, heldFirst); + dynamic typed = other; + FileWriteResult result = typed.SaveToFile ("/o" + extension, (IFileSystem)fresh); + Assert.IsTrue (result.IsSuccess, result.Error); + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/o" + extension), written, $"{format}, held first {heldFirst}: a fresh read"); + + // The fresh read has no held tag: its ID3v2 tag stands for it, or a new one assigned when it has none. + static void Edit (IMediaFile file, Id3v2Tag? held, bool heldFirst) + { + if (heldFirst) + Held (file, held).Artist = "HELD"; + file.Tag!.Title = "LATER"; + if (!heldFirst) + Held (file, held).Artist = "HELD"; + } + + static Id3v2Tag Held (IMediaFile file, Id3v2Tag? held) + { + if (held is not null) + return held; + if (HeldId3 (file) is { } stored) + return stored; + dynamic typed = file; + typed.Id3v2Tag = new Id3v2Tag (); + return HeldId3 (file)!; + } + } + + /// + /// After a clear and a save over the source, a view write that sets and then removes a value leaves the kept ID3v2 + /// tag empty: it is hidden again, not dropped, so a later edit through the held reference is still written (review + /// 3 B1). + /// + [TestMethod] + [DataRow ("wav")] + [DataRow ("aiff")] + public void ViewWriteThatEmptiesTheKeptTag_LeavesTheHeldReferenceLive (string format) + { + var extension = format == "aiff" ? ".aif" : "." + format; + var path = "/f" + extension; + var files = new MockFileSystem (); + files.AddFile (path, Build (format)); + using var file = (IMediaFile)MediaFile.Read (path, files).File!; + var held = HeldId3 (file)!; + file.Tag!.Clear (); + Save (file, files); + + file.Tag!.Title = "X"; + file.Tag!.Title = null; + held.Artist = "HELD"; + Save (file, files); + + Assert.AreSame (held, HeldId3 (file), format); + var reread = new MockFileSystem (); + reread.AddFile (path, files.ReadAllBytes (path)); + using var again = (IMediaFile)MediaFile.Read (path, reread).File!; + Assert.AreEqual ("HELD", HeldId3 (again)?.Artist, format); + } + + static Id3v2Tag? HeldId3 (IMediaFile file) => (Id3v2Tag?)file.GetType ().GetProperty ("Id3v2Tag")!.GetValue (file); + + /// + /// An id3 chunk the reader could not parse, replaced by an empty ID3v2 tag and saved: the file holds no id3 chunk, and + /// a later save from the same object does not bring the unparsed chunk back, as a fresh read's save does not. + /// + [TestMethod] + public void Wav_UnparsedId3ReplacedByAnEmptyTag_StaysGoneAfterTheNextSave () + { + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal (soundBytes: 64)).File!; + var files = new MockFileSystem (); + Assert.IsTrue (wav.SaveToFile ("/w.wav", files).IsSuccess); + byte[] junk = [.. "id3 "u8, 6, 0, 0, 0, .. "nope!!"u8]; + var bytes = files.ReadAllBytes ("/w.wav"); + byte[] withJunk = [.. bytes, .. junk]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian (withJunk.AsSpan (4), (uint)(withJunk.Length - 8)); + files.AddFile ("/w.wav", withJunk); + var file = WavFile.ReadFromFile ("/w.wav", files).File!; + Assert.IsNull (file.Id3v2Tag, "the chunk does not parse"); + + file.Id3v2Tag = new Id3v2Tag (); + Assert.IsTrue (file.SaveToFile ().IsSuccess); + var afterFirst = files.ReadAllBytes ("/w.wav"); + Assert.IsTrue (file.SaveToFile ().IsSuccess, "a save with no edit"); + + var fresh = new MockFileSystem (); + fresh.AddFile ("/w.wav", afterFirst); + var reread = WavFile.ReadFromFile ("/w.wav", fresh).File!; + Assert.IsTrue (reread.SaveToFile ().IsSuccess); + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/w.wav"), files.ReadAllBytes ("/w.wav")); + Assert.AreEqual (-1, files.ReadAllBytes ("/w.wav").AsSpan ().IndexOf ("nope!!"u8), "the unparsed chunk came back"); + } + + /// + /// On an AVI with an INFO list and no ID3v2 tag, a field INFO cannot hold is not stored, as AviFile.Tag documents; + /// an assigned ID3v2 tag keeps it. + /// + [TestMethod] + public void Avi_FieldInfoCannotHold_IsStoredOnlyWithAnId3v2Tag () + { + var original = new AviTestBuilder { Info = { ("INAM", "Old") } }.Build (); + var avi = AviFile.Read (original).File!; + avi.Tag.MusicBrainzAlbumArtistId = "v318"; + Assert.IsNull (AviFile.Read (avi.Render (original).ToArray ()).File!.Tag.MusicBrainzAlbumArtistId); + + avi.Id3v2Tag = new Id3v2Tag (); + avi.Tag.MusicBrainzAlbumArtistId = "v318"; + Assert.AreEqual ("v318", AviFile.Read (avi.Render (original).ToArray ()).File!.Tag.MusicBrainzAlbumArtistId); + } + + internal static byte[] Build (string format) + { + if (format == "wav") + return WavWithBoth (); + if (format == "wav-info") { + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal (soundBytes: 64)).File!; + wav.InfoTag = new RiffInfoTag { Title = "Old" }; + var infoFiles = new MockFileSystem (); + Assert.IsTrue (wav.SaveToFile ("/w.wav", infoFiles).IsSuccess); + return infoFiles.ReadAllBytes ("/w.wav"); + } + if (format == "avi") { + var files = new MockFileSystem (); + files.AddFile ("/a.avi", new AviTestBuilder { Info = { ("INAM", "Old"), ("IART", "Artist") } }.Build ()); + var avi = AviFile.ReadFromFile ("/a.avi", files).File!; + avi.Id3v2Tag = new Id3v2Tag (Id3v2Version.V23) { Title = "Old", Artist = "Artist", Album = "Album" }; + Assert.IsTrue (avi.SaveToFile (files).IsSuccess); + return files.ReadAllBytes ("/a.avi"); + } + + var aiffFiles = new MockFileSystem (); + aiffFiles.AddFile ("/a.aif", TaglessFixtures.All["aiff"].Build ()); + var aiff = (AiffFile)MediaFile.Read ("/a.aif", aiffFiles).File!; + // An ID3v2.3 tag: a tag the view creates is v2.4, so a kept emptied tag shows in the bytes. + aiff.Id3v2Tag = new Id3v2Tag (Id3v2Version.V23) { Title = "Old", Artist = "Artist" }; + aiff.Title = "Old"; + Assert.IsTrue (aiff.SaveToFile (aiffFiles).IsSuccess); + return aiffFiles.ReadAllBytes ("/a.aif"); + } + + static void Apply (IMediaFile file, string step) + { + var tag = file.Tag!; + switch (step) { + case "clear": tag.Clear (); break; + case "title": tag.Title = "New title"; break; + case "title-null": tag.Title = null; break; + case "custom": tag.SetCustomField ("MYFIELD", "c1"); break; + default: tag.MusicBrainzAlbumArtistId = "v318"; break; + } + } + + static void Save (IMediaFile file, MockFileSystem files) + { + dynamic typed = file; + FileWriteResult result = typed.SaveToFile ((IFileSystem)files); + Assert.IsTrue (result.IsSuccess, result.Error); + } +} From 47583e010e024600c6cb09c6b7fee5f833a45f4f Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:33:31 -0700 Subject: [PATCH 03/12] fix: Keep an Ogg file's Tag after its Vorbis comment is removed (#236) Cause: OggVorbisFile, OggOpusFile and OggFlacFile returned the stored VorbisComment as Tag, so `VorbisComment = null` (Vorbis, Opus) or RemoveVorbisComment () (Ogg FLAC) made Tag null. FlacFile, and every other audio format since 0.7.0, keeps an empty view there. Fix: Tag is CombinedTag.SingleOrView over the comment with a TagCreation, the shape WavPack, Monkey's Audio, Musepack, DSF and DFF use: the stored comment itself when there is one, else a view that creates nothing when read, creates the comment on its first write (NewComment, the factory EnsureVorbisComment now uses too, so the vendor is the same either way), and drops it again when a write leaves it empty. Ogg FLAC writes its comment block only when present, so its Render, which every Ogg FLAC save goes through, settles the created comment first, as FlacFile's saves do; Vorbis and Opus always write a comment header (an empty one when none is stored), so a dropped comment already saves as before. Tag is null after Dispose. Tests: OggTagViewTests over {Vorbis, Opus, Ogg FLAC}: the view is empty, of type None, creates nothing when read; the first write creates and saves (Render and path save); write-then-clear and a created comment emptied through VorbisComment save as no write; Tag null after Dispose; a kept comment is the Tag. TagNeverNullTests sweeps every format in TaglessFixtures: every settable stored-tag property set to null and every Remove...Tag/Remove...Comment called, Tag is not null and takes a write; only the three Ogg formats failed before the fix. Red: 12 of 18 OggTagViewTests rows failed on main (NullReference on file.Tag), and the sweep failed for ogg, opus and oga only. --- CHANGELOG.md | 1 + src/TagLibSharp2/Ogg/OggFlacFile.cs | 17 +- src/TagLibSharp2/Ogg/OggOpusFile.cs | 14 +- src/TagLibSharp2/Ogg/OggVorbisFile.cs | 14 +- .../Core/TagNeverNullTests.cs | 55 ++++++ .../TagLibSharp2.Tests/Ogg/OggTagViewTests.cs | 173 ++++++++++++++++++ 6 files changed, 268 insertions(+), 6 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Core/TagNeverNullTests.cs create mode 100644 tests/TagLibSharp2.Tests/Ogg/OggTagViewTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 32a417cb..63dd32e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -124,6 +124,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed (`OggVorbisFile.VorbisComment = null`, `OggOpusFile.VorbisComment = null`, `OggFlacFile.RemoveVorbisComment ()`) keeps a `Tag` (#236). It was null; it is now an empty view, as on a FLAC file: reading it creates nothing, its first write creates the comment (vendor `TagLibSharp2` in Vorbis and Opus, empty in Ogg FLAC, as `EnsureVorbisComment` creates it), and a write that leaves that comment empty removes it again, so the save writes what a save with no edit writes. A file that has its comment still returns that comment as its `Tag`. `Tag` is null after `Dispose` - `Picture.DetectMimeType` no longer types any RIFF data as WebP (#234). RIFF data is `image/webp` only when its form type at offset 8 is `WEBP` (RFC 9649 §2.4); WAV, AVI and other RIFF forms, and a RIFF header cut off before its form type, fall through to the file extension, or `application/octet-stream` without one. This reaches every picture typed from its bytes: `PictureFrame.FromBytes` and `FromFile`, `FlacPicture.FromBytes` and `FromFile`, `ApePicture`, the Audible cover, and a Matroska picture given no MIME type, whose save now fails with "is not an image/ media type" instead of writing WAV or AVI bytes as an `image/webp` attachment - A Matroska save no longer grows quadratically with the pictures a file holds, and the Tags read is bounded (#247). Each picture now finds its own attachment by its content in an ordered index, the UIDs and names a save keeps are in ordered sets, and new pictures of one type are numbered in one pass, so no content a file holds, its attachments' data or UIDs included, can make a hash collide; setting the pictures back on a file with many image attachments took time quadratic in them. A read models at most 65,536 Tags and SimpleTags, as Chapters bounds its entries; the Tags past that are kept as their bytes and written back unread. A save that would write a Tag, a SimpleTag, a chapter or a chapter's value past what a read models (a new Tag or chapter in a file at the budget, or an edit that pushes the last one read, or only its title, language, times or flags, past it) now fails with a result saying so, and leaves the file and the object's edits as they were; it used to report success for a value no read could show. A chapter title edit at the budget counts too when the display was read without a language, as the save writes the default "eng". An edit that writes as many elements, such as a value replaced in place, is saved. - A second save of a Matroska file from the same object writes a clear or an undone edit (#244). Read a file, set `Title`, save it over its source, then clear `Title` and save again: the file kept the title. A save left the `Tags` element as it was when the tags matched the ones the object first read, but after a save over the source the file holds the saved tags. The same held for every tag field, and for a chapter edit undone, or a chapter or edition added and then removed. A save now compares with the `Tags` and `Chapters` elements in the bytes it rewrites, on all six save entry points. A chapter read without a `ChapterUID`, or with 0, now reads `Uid` 0 and is written as it was (a read gave it a random UID, so no two reads of the file were the same); a save that writes the chapter changed gives it a new random UID, as RFC 9559 requires one that is not 0, and the chapter keeps it once a save over the source has written it. Setting `MatroskaChapter.Uid` to 0 now means the same, no UID yet, where it threw. After a save over its source the object holds the tags and chapters it wrote, as a read of the saved file would, so a later save writes what a fresh object would; a save that fails or goes elsewhere leaves it as it was. A UID the library draws for a new chapter, edition or picture attachment is now always 8 bytes wide, so the size of a save no longer depends on the draw. A save finds the empty Tags it keeps by their content in an ordered set, in O(log n) comparisons each whatever the Tags hold, with no hash a file could make collide. diff --git a/src/TagLibSharp2/Ogg/OggFlacFile.cs b/src/TagLibSharp2/Ogg/OggFlacFile.cs index 6017b346..fb317986 100644 --- a/src/TagLibSharp2/Ogg/OggFlacFile.cs +++ b/src/TagLibSharp2/Ogg/OggFlacFile.cs @@ -190,7 +190,17 @@ internal List MetadataBlockPayloads (byte type) public string? SourcePath => _sourcePath; /// - public Tag? Tag => VorbisComment; + /// + /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write + /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after + /// Dispose. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment, + _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag)); + + TagCreation? _creation; + + static VorbisComment NewComment () => new (); /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -484,7 +494,7 @@ private static ExtractPacketResult ExtractFirstPacket (ReadOnlySpan data) /// public VorbisComment EnsureVorbisComment () { - VorbisComment ??= new VorbisComment (); + VorbisComment ??= NewComment (); return VorbisComment; } @@ -505,6 +515,9 @@ public void RemoveVorbisComment () /// public byte[] Render (ReadOnlySpan originalData) { + // A comment the tag view created and that holds nothing is not written (TagCreation). + _creation?.Settle ([VorbisComment]); + // Do not splice metadata in front of a continuation we failed to reassemble. var headerInfo = ExtractHeaderInfo (originalData); if (!headerInfo.IsSuccess) diff --git a/src/TagLibSharp2/Ogg/OggOpusFile.cs b/src/TagLibSharp2/Ogg/OggOpusFile.cs index 5e66a059..79961017 100644 --- a/src/TagLibSharp2/Ogg/OggOpusFile.cs +++ b/src/TagLibSharp2/Ogg/OggOpusFile.cs @@ -172,7 +172,17 @@ public string? Comment { } /// - public Tag? Tag => VorbisComment; + /// + /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write + /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after + /// Dispose. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment, + _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag)); + + TagCreation? _creation; + + static VorbisComment NewComment () => new ("TagLibSharp2"); /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -565,7 +575,7 @@ static bool IsOpusTags (ReadOnlySpan data) => VorbisComment EnsureVorbisComment () { - VorbisComment ??= new VorbisComment ("TagLibSharp2"); + VorbisComment ??= NewComment (); return VorbisComment; } diff --git a/src/TagLibSharp2/Ogg/OggVorbisFile.cs b/src/TagLibSharp2/Ogg/OggVorbisFile.cs index b0453c8e..fba20595 100644 --- a/src/TagLibSharp2/Ogg/OggVorbisFile.cs +++ b/src/TagLibSharp2/Ogg/OggVorbisFile.cs @@ -128,7 +128,17 @@ public string? Comment { } /// - public Tag? Tag => VorbisComment; + /// + /// The Vorbis comment. A file without one (it was removed) has a view whose first write creates one, and a write + /// that leaves that comment empty removes it again, as on a FLAC file. Reading the view creates nothing. Null after + /// Dispose. + /// + public Tag? Tag => _disposed ? null : CombinedTag.SingleOrView (VorbisComment, () => VorbisComment, + _creation ??= new TagCreation (NewComment, tag => VorbisComment = (VorbisComment?)tag)); + + TagCreation? _creation; + + static VorbisComment NewComment () => new ("TagLibSharp2"); /// IMediaProperties? IMediaFile.AudioProperties => Properties; @@ -449,7 +459,7 @@ static bool IsVorbisCommentHeader (ReadOnlySpan data) VorbisComment EnsureVorbisComment () { - VorbisComment ??= new VorbisComment ("TagLibSharp2"); + VorbisComment ??= NewComment (); return VorbisComment; } diff --git a/tests/TagLibSharp2.Tests/Core/TagNeverNullTests.cs b/tests/TagLibSharp2.Tests/Core/TagNeverNullTests.cs new file mode 100644 index 00000000..23ef903e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/TagNeverNullTests.cs @@ -0,0 +1,55 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Core; + +/// +/// An audio or video file's is not null before Dispose, whatever tags the caller removed: +/// every settable stored-tag property set to null (MP4's settable Tag included), and each Remove…Tag or Remove…Comment method called +/// (#236). The view then creates a tag on its first write. +/// +[TestClass] +[TestCategory ("Unit")] +public class TagNeverNullTests +{ + public static IEnumerable Formats => TaglessFixtures.All.Keys.Select (key => new object[] { key }); + + [TestMethod] + [DynamicData (nameof (Formats))] + public void EveryStoredTagRemoved_TagIsAViewThatTakesAWrite (string format) + { + var fixture = TaglessFixtures.All[format]; + var bytes = fixture.Build (); + var file = (IMediaFile)MediaFile.ReadFromData (bytes, "file" + fixture.Extension).File!; + + var removed = RemoveEveryStoredTag (file); + + Assert.IsNotNull (file.Tag, $"{format}: Tag is null after removing {string.Join (", ", removed)}"); + file.Tag.Title = "Written"; + Assert.AreEqual ("Written", file.Tag.Title, format); + } + + static List RemoveEveryStoredTag (IMediaFile file) + { + var removed = new List (); + foreach (var property in file.GetType ().GetProperties (BindingFlags.Public | BindingFlags.Instance)) { + if (!typeof (Tag).IsAssignableFrom (property.PropertyType) || property.SetMethod is not { IsPublic: true }) + continue; + property.SetValue (file, null); + removed.Add (property.Name); + } + + foreach (var method in file.GetType ().GetMethods (BindingFlags.Public | BindingFlags.Instance)) { + if (method.GetParameters ().Length != 0 || !method.Name.StartsWith ("Remove", StringComparison.Ordinal) + || !(method.Name.EndsWith ("Tag", StringComparison.Ordinal) || method.Name.EndsWith ("Comment", StringComparison.Ordinal))) + continue; + method.Invoke (file, null); + removed.Add (method.Name + " ()"); + } + + return removed; + } +} diff --git a/tests/TagLibSharp2.Tests/Ogg/OggTagViewTests.cs b/tests/TagLibSharp2.Tests/Ogg/OggTagViewTests.cs new file mode 100644 index 00000000..be57bcb8 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ogg/OggTagViewTests.cs @@ -0,0 +1,173 @@ +// 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.Ogg; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Ogg; + +/// +/// An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed still has a Tag, as a FLAC file does: an +/// empty view that creates nothing when read, whose first write creates the comment, and which is null only after +/// Dispose (#236). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ogg")] +public class OggTagViewTests +{ + public static IEnumerable Formats => [["ogg"], ["opus"], ["oga"]]; + + [TestMethod] + [DynamicData (nameof (Formats))] + public void RemovedComment_LeavesAnEmptyViewThatCreatesNothing (string format) + { + var (file, _) = ReadAndRemove (format); + + var tag = file.Tag; + + Assert.IsNotNull (tag, format); + Assert.IsTrue (tag.IsEmpty, format); + Assert.AreEqual (TagTypes.None, tag.TagType, format); + Assert.IsNull (tag.Title, format); + Assert.IsTrue (tag.SupportsCustomFields, $"{format}: the view answers for the Vorbis comment its first write creates"); + Assert.IsNull (Comment (file), $"{format}: reading the view created a comment"); + } + + [TestMethod] + [DynamicData (nameof (Formats))] + public void RemovedComment_FirstWriteCreatesTheCommentAndSaves (string format) + { + var (file, original) = ReadAndRemove (format); + + file.Tag!.Title = "Back"; + + Assert.AreEqual ("Back", Comment (file)?.Title, format); + var saved = SkipPicturesFixtures.Render (file, original)!; + Assert.AreEqual ("Back", ((IMediaFile)MediaFile.ReadFromData (saved, "saved." + format).File!).Tag!.Title, format); + } + + /// A write that leaves the created comment empty drops it, so the save writes what a save with no write does. + [TestMethod] + [DynamicData (nameof (Formats))] + public void RemovedComment_WriteThenClear_SavesAsNoWrite (string format) + { + var (untouched, original) = ReadAndRemove (format); + var expected = SkipPicturesFixtures.Render (untouched, original)!; + var (file, _) = ReadAndRemove (format); + + file.Tag!.Title = "Gone again"; + file.Tag!.Title = null; + + Assert.IsNull (Comment (file), format); + CollectionAssert.AreEqual (expected, SkipPicturesFixtures.Render (file, original), format); + } + + /// A comment the view created and the caller emptied through the stored-tag property is not written either. + [TestMethod] + [DynamicData (nameof (Formats))] + public void RemovedComment_CreatedCommentEmptiedThroughTheProperty_SavesAsNoWrite (string format) + { + var (untouched, original) = ReadAndRemove (format); + var expected = SkipPicturesFixtures.Render (untouched, original)!; + var (file, _) = ReadAndRemove (format); + + file.Tag!.Title = "Created"; + Comment (file)!.Title = null; + + CollectionAssert.AreEqual (expected, SkipPicturesFixtures.Render (file, original), format); + } + + /// + /// The path save, which copies the audio pages from the source: the first write through the view is saved, and a + /// created comment emptied again saves as no write. + /// + [TestMethod] + [DynamicData (nameof (Formats))] + public void RemovedComment_PathSave_WritesTheViewsEdit (string format) + { + var untouched = PathSave (format, _ => { }); + var written = PathSave (format, file => file.Tag!.Title = "On disk"); + var undone = PathSave (format, file => { + file.Tag!.Title = "Created"; + Comment (file)!.Title = null; + }); + + Assert.AreEqual ("On disk", ((IMediaFile)MediaFile.ReadFromData (written, "saved." + format).File!).Tag!.Title, format); + CollectionAssert.AreEqual (untouched, undone, format); + } + + static byte[] PathSave (string format, Action edit) + { + var files = new MockFileSystem (); + var path = "/file." + format; + files.AddFile (path, Build (format)); + var file = (IMediaFile)MediaFile.Read (path, files).File!; + Remove (file); + edit (file); + dynamic typed = file; + FileWriteResult saved = typed.SaveToFile (); + Assert.IsTrue (saved.IsSuccess, $"{format}: {saved.Error}"); + return files.ReadAllBytes (path); + } + + [TestMethod] + [DynamicData (nameof (Formats))] + public void Tag_IsNullAfterDispose (string format) + { + var (file, _) = ReadAndRemove (format); + + ((IDisposable)file).Dispose (); + + Assert.IsNull (file.Tag, format); + } + + /// A file that keeps its comment returns that comment as its tag, as before. + [TestMethod] + [DynamicData (nameof (Formats))] + public void KeptComment_IsTheTag (string format) + { + var file = (IMediaFile)MediaFile.ReadFromData (Build (format), "file." + format).File!; + + Assert.AreSame (Comment (file), file.Tag, format); + } + + static byte[] Build (string format) => format switch { + "ogg" => TestBuilders.Ogg.CreateMinimalFile (), + "opus" => TestBuilders.Opus.CreateMinimalFile (), + _ => TaglessFixtures.All["oga"].Build () + }; + + static VorbisComment? Comment (IMediaFile file) => file switch { + OggVorbisFile vorbis => vorbis.VorbisComment, + OggOpusFile opus => opus.VorbisComment, + OggFlacFile flac => flac.VorbisComment, + _ => throw new ArgumentOutOfRangeException (nameof (file)) + }; + + static (IMediaFile File, byte[] Original) ReadAndRemove (string format) + { + var original = Build (format); + var file = (IMediaFile)MediaFile.ReadFromData (original, "file." + format).File!; + Remove (file); + return (file, original); + } + + static void Remove (IMediaFile file) + { + switch (file) { + case OggVorbisFile vorbis: + vorbis.VorbisComment = null; + break; + case OggOpusFile opus: + opus.VorbisComment = null; + break; + case OggFlacFile flac: + Assert.IsNotNull (flac.VorbisComment, "the fixture has a comment to remove"); + flac.RemoveVorbisComment (); + break; + } + } +} From 3a7572f798203fdaa86857c6ebda3b193114c364 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:42:03 -0700 Subject: [PATCH 04/12] fix: Keep an APE tag's items in the order they were read (#238) Cause: ApeTag.RenderWithOptions sorted the items by rendered size, so a file that stores them in another order changed on a save with no edit (sample.ape, 8bit.wv, sample.mpc). The items lived in a Dictionary whose enumeration order is its slot order: after a removal a new item reused the freed slot, and OrderBy is stable, so items of equal size came out in slot order. A save from the object that saved before and a save from a fresh read of that save then ordered them differently (the review finding folded into this issue). Fix: OrderedMap (Core), the tag's item store: a dictionary from key to (value, place), keys compared case-insensitively for APE, places drawn from a counter that only grows. Set keeps the place of the item it replaces, else appends; Set with an alias puts a value written under its key in the alias item's place; Remove and Clear forget the place; InOrder sorts by place. Render writes InOrder with no size sort (APEv2 only recommends sorting). Parse uses Set, so a key read twice keeps the first place and the last value, as the dictionary did. The Pictures setter replaces cover items in place and removes the other "Cover Art" items (the same final set as before), SetCustomField replaces in place instead of remove-then-add, and SetTextList and SetOrRemove share one alias-aware helper. Lookups, replacements and removals stay O(1); a render is O(n log n), whatever the keys. SkipPicturesFixtures read ApeTag._items by reflection as a Dictionary; it now reads the OrderedMap, with its own picture rule. Tests: ApeTagItemOrderTests. NoEditRender_IsTheTagAsRead (three orders, with and without a header); SaveAfterSave_IsTheFreshReadsSave over {3 orders} x {13 edits} x {13 edits}: replace, remove, add, custom field, pictures, remove-then-add; Edit_PutsItemsWhereTheRuleSays; AliasItem_WrittenUnderItsKey_KeepsItsPlace; WriteBack_KeepsTheBytes (title, custom field, pictures); DuplicateKey_KeepsTheFirstPlaceAndTheLastValue; NoEditPathSave and PathSaveAfterSave for each carrier (Monkey's Audio, WavPack, Musepack, raw AAC); EditAndRender_AllocateLinearlyInTheItemCount. Grid over the corpus samples: the no-edit save of sample.ape, sample.mpc, cover-art.ape, cover-art.mpc, 128kbps.wv, 256kbps.wv and 512kbps.wv is now byte-identical; sample_v8.mpc differs only in its item count, declared 11 for 8 items, which the save writes as 8. Red: 38 of 527 rows failed on main, each carrier's no-edit and save-after-save rows among them. --- CHANGELOG.md | 1 + src/TagLibSharp2/Ape/ApeTag.cs | 111 +++---- src/TagLibSharp2/Core/OrderedMap.cs | 94 ++++++ .../Ape/ApeTagItemOrderTests.cs | 292 ++++++++++++++++++ .../Core/SkipPicturesFixtures.cs | 7 +- 5 files changed, 440 insertions(+), 65 deletions(-) create mode 100644 src/TagLibSharp2/Core/OrderedMap.cs create mode 100644 tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 63dd32e3..ab138b1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -124,6 +124,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An APE tag keeps its items in the order they were read (#238). A save sorted them by size, so a file that stores them in another order (`sample.ape`, `8bit.wv`, `sample.mpc`) changed on a save with no edit, and items of equal size were written in the order they were added, so after a removal a save from the object that saved before and a save from a fresh read of that save could order them differently. Now a save with no edit writes the items as they were; a changed value stays in its item's place, a value written under its key in place of its alias (`Album Artist` for `ALBUMARTIST`) takes the alias item's place, writing back the pictures or a custom field read moves nothing, and a new item goes after the others, in the order added. A key read twice keeps the first item's place and the last item's value, as before. This holds for Monkey's Audio, WavPack, Musepack and raw AAC. `sample_v8.mpc` declares 11 items and holds 8; its save with no edit now differs only in that count, which it writes as 8 - An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed (`OggVorbisFile.VorbisComment = null`, `OggOpusFile.VorbisComment = null`, `OggFlacFile.RemoveVorbisComment ()`) keeps a `Tag` (#236). It was null; it is now an empty view, as on a FLAC file: reading it creates nothing, its first write creates the comment (vendor `TagLibSharp2` in Vorbis and Opus, empty in Ogg FLAC, as `EnsureVorbisComment` creates it), and a write that leaves that comment empty removes it again, so the save writes what a save with no edit writes. A file that has its comment still returns that comment as its `Tag`. `Tag` is null after `Dispose` - `Picture.DetectMimeType` no longer types any RIFF data as WebP (#234). RIFF data is `image/webp` only when its form type at offset 8 is `WEBP` (RFC 9649 §2.4); WAV, AVI and other RIFF forms, and a RIFF header cut off before its form type, fall through to the file extension, or `application/octet-stream` without one. This reaches every picture typed from its bytes: `PictureFrame.FromBytes` and `FromFile`, `FlacPicture.FromBytes` and `FromFile`, `ApePicture`, the Audible cover, and a Matroska picture given no MIME type, whose save now fails with "is not an image/ media type" instead of writing WAV or AVI bytes as an `image/webp` attachment - A Matroska save no longer grows quadratically with the pictures a file holds, and the Tags read is bounded (#247). Each picture now finds its own attachment by its content in an ordered index, the UIDs and names a save keeps are in ordered sets, and new pictures of one type are numbered in one pass, so no content a file holds, its attachments' data or UIDs included, can make a hash collide; setting the pictures back on a file with many image attachments took time quadratic in them. A read models at most 65,536 Tags and SimpleTags, as Chapters bounds its entries; the Tags past that are kept as their bytes and written back unread. A save that would write a Tag, a SimpleTag, a chapter or a chapter's value past what a read models (a new Tag or chapter in a file at the budget, or an edit that pushes the last one read, or only its title, language, times or flags, past it) now fails with a result saying so, and leaves the file and the object's edits as they were; it used to report success for a value no read could show. A chapter title edit at the budget counts too when the display was read without a language, as the save writes the default "eng". An edit that writes as many elements, such as a value replaced in place, is saved. diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 03d621a0..3ffd60d8 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -81,7 +81,8 @@ public override bool Equals (object? obj) => /// public sealed class ApeTag : Tag { - private readonly Dictionary _items; + // The items in the order a save writes them: as read, a replaced item in its place, a new one last (#238). + private readonly OrderedMap _items; // Whether the tag was read with a header; null for a tag created here. The header is optional at the end of a // file (APEv2: "must have at least a footer"), so a save writes the tag back the way it was read. @@ -157,13 +158,13 @@ private static class Keys /// public ApeTag () { - _items = new Dictionary (StringComparer.OrdinalIgnoreCase); + _items = new OrderedMap (StringComparer.OrdinalIgnoreCase); } /// /// Creates an APE tag with the specified items, read with or without a header. /// - private ApeTag (Dictionary items, bool readWithHeader) + private ApeTag (OrderedMap items, bool readWithHeader) { _items = items; _readWithHeader = readWithHeader; @@ -835,13 +836,7 @@ internal static bool IsPictureItem (string key, ApeItemType type) => /// Removes every item would return, and nothing else. internal void RemovePictureItems () { - var keys = new List (); - foreach (var kvp in _items) { - if (IsPictureItem (kvp.Value)) - keys.Add (kvp.Key); - } - - foreach (var key in keys) + foreach (var key in _items.KeysWhere (static (_, item) => IsPictureItem (item))) _items.Remove (key); } @@ -859,34 +854,32 @@ public override IPicture[] Pictures { pictures.Add (ApePicture.FromBinaryData (Keys.CoverArtBack, back.BinaryValue!)); // Check for other cover art keys - foreach (var kvp in _items) { - if (IsPictureItem (kvp.Value) && - !string.Equals (kvp.Key, Keys.CoverArtFront, StringComparison.OrdinalIgnoreCase) && - !string.Equals (kvp.Key, Keys.CoverArtBack, StringComparison.OrdinalIgnoreCase)) { - pictures.Add (ApePicture.FromBinaryData (kvp.Key, kvp.Value.BinaryValue!)); + foreach (var (key, item) in _items.InOrder ()) { + if (IsPictureItem (item) && + !string.Equals (key, Keys.CoverArtFront, StringComparison.OrdinalIgnoreCase) && + !string.Equals (key, Keys.CoverArtBack, StringComparison.OrdinalIgnoreCase)) { + pictures.Add (ApePicture.FromBinaryData (key, item.BinaryValue!)); } } return [.. pictures]; } set { - // Remove existing cover art - var keysToRemove = _items.Keys - .Where (k => k.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase)) - .ToList (); - foreach (var key in keysToRemove) - _items.Remove (key); - - // Add new pictures - if (value is null || value.Length == 0) - return; - - foreach (var pic in value) { + // Every "Cover Art" item goes, text and locator items too, but a picture whose key was there takes that + // item's place, so writing back the pictures read moves nothing (#238). + var pictures = new List<(string Key, ApeTagItem Item)> (); + var kept = new HashSet (StringComparer.OrdinalIgnoreCase); + foreach (var pic in value ?? []) { var apePic = ApePicture.FromPicture (pic); var key = apePic.GetKey (); - var data = apePic.PictureData.ToArray (); - SetBinaryItem (key, apePic.Filename, data); + pictures.Add ((key, ApeTagItem.CreateBinary (key, apePic.Filename, apePic.PictureData.ToArray ()))); + kept.Add (key); } + + foreach (var key in _items.KeysWhere ((key, _) => key.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase) && !kept.Contains (key))) + _items.Remove (key); + foreach (var (key, item) in pictures) + _items.Set (key, item); } } #pragma warning restore CA1819 @@ -904,7 +897,7 @@ public override IPicture[] Pictures { /// public void SetValue (string key, string value) { - _items[key] = ApeTagItem.CreateText (key, value); + _items.Set (key, ApeTagItem.CreateText (key, value)); } /// @@ -977,24 +970,13 @@ string[] GetTextList (string key) /// void SetTextList (string key, string[]? values, string? alias = null) { - if (alias is not null) - _items.Remove (alias); - - if (values is null || values.Length == 0) { - _items.Remove (key); - return; - } - - var kept = new List (values.Length); - for (var i = 0; i < values.Length; i++) { - if (!string.IsNullOrEmpty (values[i])) - kept.Add (values[i]); + var kept = new List (values?.Length ?? 0); + foreach (var value in values ?? []) { + if (!string.IsNullOrEmpty (value)) + kept.Add (value); } - if (kept.Count == 0) - _items.Remove (key); - else - SetValue (key, string.Join ("\0", kept)); + SetOrRemove (key, kept.Count == 0 ? null : string.Join ("\0", kept), alias); } /// @@ -1010,7 +992,7 @@ void SetTextList (string key, string[]? values, string? alias = null) /// public void SetBinaryItem (string key, string filename, byte[] data) { - _items[key] = ApeTagItem.CreateBinary (key, filename, data); + _items.Set (key, ApeTagItem.CreateBinary (key, filename, data)); } /// @@ -1067,9 +1049,11 @@ public override bool SetCustomField (string name, params string[] values) if (!IsCustomFieldKey (name) || !CustomFieldValues.TryNormalize (values, out var kept)) return false; - _items.Remove (name); + // The item takes the place of the one it replaces, whatever the case of its key. if (kept.Count > 0) - _items[name] = ApeTagItem.CreateText (name, string.Join ("\0", kept)); + _items.Set (name, ApeTagItem.CreateText (name, string.Join ("\0", kept))); + else + _items.Remove (name); return true; } @@ -1087,13 +1071,19 @@ static bool IsCustomFieldKey (string name) => ApeTagItem.IsValidKey (name) && !name.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase); - private void SetOrRemove (string key, string? value, string? alias = null) + /// + /// Stores as the text item , or removes that item when it is null or + /// empty. is removed either way; a value stored when only the alias item was there takes + /// its place. + /// + void SetOrRemove (string key, string? value, string? alias = null) { - if (alias is not null) - _items.Remove (alias); - if (string.IsNullOrEmpty (value)) { + if (alias is not null) + _items.Remove (alias); _items.Remove (key); + } else if (alias is not null) { + _items.Set (key, ApeTagItem.CreateText (key, value!), alias); } else { SetValue (key, value!); } @@ -1147,9 +1137,7 @@ internal static ApeTagParseResult Parse (ReadOnlySpan data, int floor) // Do not size the dictionary from ItemCount. A count that fits the 11-byte minimum // can still allocate more than a megabyte; 0xFF payloads fail in the item parser either way. - var items = new Dictionary ( - (int)Math.Min (footer.ItemCount, 256u), - StringComparer.OrdinalIgnoreCase); + var items = new OrderedMap (StringComparer.OrdinalIgnoreCase, (int)Math.Min (footer.ItemCount, 256u)); var itemsData = data.Slice (itemsStart, itemsSize); var offset = 0; @@ -1162,7 +1150,8 @@ internal static ApeTagParseResult Parse (ReadOnlySpan data, int floor) return ApeTagParseResult.Failure (itemResult.Error!); } - items[itemResult.Item!.Key] = itemResult.Item; + // A key read again (APEv2 allows one) keeps the first item's place and takes the last item's value. + items.Set (itemResult.Item!.Key, itemResult.Item); offset += itemResult.BytesConsumed; itemsParsed++; } @@ -1234,10 +1223,10 @@ internal static bool HeaderForSave (ApeTag tag, ApeTag? readTag, bool? readHeade /// public BinaryData RenderWithOptions (bool includeHeader = false) { - // Render items (optionally sorted by size per spec recommendation) - var renderedItems = _items.Values - .Select (item => item.Render ()) - .OrderBy (data => data.Length) + // The items in the order they were read, new ones last (#238). APEv2 only recommends sorting by size, and a + // sort would change a file that stores them in another order on a save with no edit. + var renderedItems = _items.InOrder () + .Select (entry => entry.Value.Render ()) .ToList (); var itemsSize = renderedItems.Sum (data => data.Length); diff --git a/src/TagLibSharp2/Core/OrderedMap.cs b/src/TagLibSharp2/Core/OrderedMap.cs new file mode 100644 index 00000000..e3a1aa68 --- /dev/null +++ b/src/TagLibSharp2/Core/OrderedMap.cs @@ -0,0 +1,94 @@ +// 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.Diagnostics.CodeAnalysis; + +namespace TagLibSharp2.Core; + +/// +/// Values by key in the order a save writes them: the order they were read in, a replaced value in the place of the +/// value it replaces, and a new value after the others, in the order added. A tag whose format sets no order (APEv2 +/// items, #238) keeps the order it was read in, so a save from the object that saved before writes what a fresh read +/// of that save writes, and a save with no edit writes the values as they were. +/// +/// +/// A lookup, a replacement and a removal take constant time; sorts by place, so any number of +/// edits and one render take O(n log n) in the values a file holds. The places come from a counter, not from the keys, +/// so no choice of keys makes the work grow faster. +/// +/// How keys compare. +/// The number of values to allocate room for. +internal sealed class OrderedMap (IEqualityComparer comparer, int capacity = 0) +{ + readonly Dictionary _entries = new (capacity, comparer); + + // The place of the next new value. Places only grow, so a new value always goes after every value there is. + long _next; + + public int Count => _entries.Count; + + public bool ContainsKey (string key) => _entries.ContainsKey (key); + + public bool TryGetValue (string key, [MaybeNullWhen (false)] out TValue value) + { + if (_entries.TryGetValue (key, out var entry)) { + value = entry.Value; + return true; + } + + value = default; + return false; + } + + /// Stores under : in the place of the value it replaces, else last. + public void Set (string key, TValue value) => + _entries[key] = (value, _entries.TryGetValue (key, out var entry) ? entry.Place : _next++); + + /// + /// Removes and stores under : in the place of + /// the value it replaces, else in the alias's place, else last. A field read from its alias and written back under + /// its key keeps its place. + /// + public void Set (string key, TValue value, string alias) + { + if (!_entries.ContainsKey (key) && _entries.TryGetValue (alias, out var aliased)) { + _entries.Remove (alias); + _entries[key] = (value, aliased.Place); + return; + } + + _entries.Remove (alias); + Set (key, value); + } + + public bool Remove (string key) => _entries.Remove (key); + + public void Clear () => _entries.Clear (); + + /// The keys of the values selects, in place order. + public List KeysWhere (Func match) + { + var keys = new List (); + foreach (var (key, value) in InOrder ()) { + if (match (key, value)) + keys.Add (key); + } + + return keys; + } + + /// Every value with the key it is stored under, in the order a save writes them. + public List<(string Key, TValue Value)> InOrder () + { + var entries = new List<(string Key, TValue Value, long Place)> (_entries.Count); + foreach (var pair in _entries) + entries.Add ((pair.Key, pair.Value.Value, pair.Value.Place)); + + // Places are unique, so the sort needs no tie-break and is the same however the dictionary enumerates. + entries.Sort (static (a, b) => a.Place.CompareTo (b.Place)); + var ordered = new List<(string, TValue)> (entries.Count); + foreach (var (key, value, _) in entries) + ordered.Add ((key, value)); + return ordered; + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs new file mode 100644 index 00000000..dd17759e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs @@ -0,0 +1,292 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// An APE tag keeps its items in the order they were read (#238): a save with no edit writes them back as they were, +/// a changed value stays in its item's place, and a new item goes after the others, in the order the items were +/// added. So a save from the object that saved before and a save from a fresh read of that save write the same bytes. +/// APEv2 sets no item order; sorting by size is only a recommendation (https://wiki.hydrogenaud.io/index.php?title=APEv2_specification, +/// "Items ... can be sorted by size"). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public class ApeTagItemOrderTests +{ + // Each order holds items of unequal and of equal sizes: Title=A and Album=B render to the same length. + static readonly string[][] Orders = [ + ["Title=A", "Album=B", "Comment=a longer comment", "Genre=Rock"], + ["Comment=a longer comment", "Genre=Rock", "Album=B", "Title=A"], + ["Album=B", "Comment=a longer comment", "Title=A", "Genre=Rock"], + ]; + + public static IEnumerable OrderCases => Orders.Select ((order, i) => new object[] { i }); + + [TestMethod] + [DynamicData (nameof (OrderCases))] + public void NoEditRender_IsTheTagAsRead (int order) + { + foreach (var header in new[] { false, true }) { + var stored = Tag (header, Orders[order]); + + var read = ApeTag.Parse (stored).Tag!; + + CollectionAssert.AreEqual (stored, read.Render ().ToArray (), $"order {order}, header {header}"); + CollectionAssert.AreEqual (Orders[order], Keys (read.Render ().ToArray ()), $"order {order}, header {header}"); + } + } + + /// The edits a caller makes, each keeping the order rule: replace in place, remove, add at the end. + static readonly (string Name, Action Apply)[] Edits = [ + ("none", _ => { }), + ("set Title", t => t.Title = "New title"), + ("set Genre", t => t.Genre = "G"), + ("remove Album", t => t.Album = null), + ("remove Title", t => t.Title = null), + ("add Artist", t => t.Artist = "Z"), + ("add Composer", t => t.Composer = "Y"), + ("add custom", t => t.SetCustomField ("MYFIELD", "x")), + ("set custom over Comment", t => t.SetCustomField ("COMMENT", "c")), + ("remove custom Genre", t => t.RemoveCustomField ("Genre")), + ("add picture", t => t.Pictures = [new ApePicture ("image/jpeg", PictureType.FrontCover, "cover.jpg", Jpeg)]), + ("remove then add", t => { t.Album = null; t.Artist = "Z"; }), + ("set then remove", t => { t.Artist = "Z"; t.Artist = null; }), + ]; + + static readonly BinaryData Jpeg = new ([0xFF, 0xD8, 0xFF, 0xD9]); + + public static IEnumerable EditPairs => + from order in Enumerable.Range (0, Orders.Length) + from first in Enumerable.Range (0, Edits.Length) + from second in Enumerable.Range (0, Edits.Length) + select new object[] { order, first, second }; + + /// + /// {order} x {first edit} x {second edit}: the object that rendered the first edit renders the second as a fresh + /// read of the first render does. + /// + [TestMethod] + [DynamicData (nameof (EditPairs))] + public void SaveAfterSave_IsTheFreshReadsSave (int order, int first, int second) + { + var tag = ApeTag.Parse (Tag (false, Orders[order])).Tag!; + Edits[first].Apply (tag); + var saved = tag.Render ().ToArray (); + Edits[second].Apply (tag); + var again = tag.Render ().ToArray (); + + var fresh = ApeTag.Parse (saved).Tag!; + Edits[second].Apply (fresh); + + CollectionAssert.AreEqual (Keys (fresh.Render ().ToArray ()), Keys (again), $"order {order}: {Edits[first].Name}, then {Edits[second].Name}"); + CollectionAssert.AreEqual (fresh.Render ().ToArray (), again, $"order {order}: {Edits[first].Name}, then {Edits[second].Name}"); + } + + /// Where each edit puts the items: a value set stays in its place, and new items follow the others in the order added. + [TestMethod] + [DataRow ("set Title", new[] { "Comment", "Genre", "Album", "Title" })] + [DataRow ("remove Album", new[] { "Comment", "Genre", "Title" })] + [DataRow ("add Artist", new[] { "Comment", "Genre", "Album", "Title", "Artist" })] + [DataRow ("remove then add", new[] { "Comment", "Genre", "Title", "Artist" })] + [DataRow ("set custom over Comment", new[] { "COMMENT", "Genre", "Album", "Title" })] + [DataRow ("add picture", new[] { "Comment", "Genre", "Album", "Title", "Cover Art (Front)" })] + public void Edit_PutsItemsWhereTheRuleSays (string edit, string[] expected) + { + var tag = ApeTag.Parse (Tag (false, Orders[1])).Tag!; + + Edits.Single (e => e.Name == edit).Apply (tag); + + CollectionAssert.AreEqual (expected, Keys (tag.Render ().ToArray ()).Select (k => k[..k.IndexOf ('=')]).ToArray (), edit); + } + + /// + /// A field read from its alias item (ALBUMARTIST) and written under its key ("Album Artist") takes the alias item's + /// place; a key already there keeps its own place and the alias goes. + /// + [TestMethod] + [DataRow ("AlbumArtist", new[] { "Title", "ALBUMARTIST", "Genre" }, new[] { "Title", "Album Artist", "Genre" })] + [DataRow ("AlbumArtists", new[] { "Title", "ALBUMARTIST", "Genre" }, new[] { "Title", "Album Artist", "Genre" })] + [DataRow ("AlbumArtist", new[] { "Album Artist", "ALBUMARTIST", "Genre" }, new[] { "Album Artist", "Genre" })] + [DataRow ("AlbumArtist", new[] { "ALBUMARTIST", "Genre", "Album Artist" }, new[] { "Genre", "Album Artist" })] + public void AliasItem_WrittenUnderItsKey_KeepsItsPlace (string property, string[] stored, string[] expected) + { + var tag = ApeTag.Parse (Tag (false, [.. stored.Select (key => key + "=v " + key)])).Tag!; + + if (property == "AlbumArtists") + tag.AlbumArtists = ["New"]; + else + tag.AlbumArtist = "New"; + + CollectionAssert.AreEqual (expected, Keys (tag.Render ().ToArray ()).Select (k => k[..k.IndexOf ('=')]).ToArray (), property); + Assert.AreEqual ("New", tag.AlbumArtist, property); + } + + /// Writing back what was read moves nothing: values, custom fields and pictures. + [TestMethod] + public void WriteBack_KeepsTheBytes () + { + byte[] picture = [.. "cover.jpg"u8, 0, .. Jpeg.ToArray ()]; + var stored = Tag (true, [ + ("Title", 0, "A"u8.ToArray ()), + ("Cover Art (Front)", 2, picture), + ("MYFIELD", 0, "x\0y"u8.ToArray ()), + ("Album", 0, "B"u8.ToArray ())]); + var tag = ApeTag.Parse (stored).Tag!; + + tag.Title = tag.Title; + tag.SetCustomField ("MYFIELD", [.. tag.GetCustomField ("MYFIELD")]); + tag.Pictures = tag.Pictures; + + CollectionAssert.AreEqual (stored, tag.Render ().ToArray ()); + } + + /// A key read twice (APEv2 allows one) keeps the place of its first item and the value of its last, as before. + [TestMethod] + public void DuplicateKey_KeepsTheFirstPlaceAndTheLastValue () + { + var tag = ApeTag.Parse (Tag (false, ["Title=first", "Album=B", "TITLE=last"])).Tag!; + + CollectionAssert.AreEqual ((string[])["TITLE=last", "Album=B"], Keys (tag.Render ().ToArray ())); + } + + /// A no-edit path save of each carrier writes the tag in the order it was read. + [TestMethod] + [DataRow (".ape")] + [DataRow (".wv")] + [DataRow (".mpc")] + [DataRow (".aac")] + public void NoEditPathSave_OfEachCarrier_IsByteIdentical (string extension) + { + var bytes = Carrier (extension, Tag (true, Orders[1])); + var files = new MockFileSystem (); + files.AddFile ("/f" + extension, bytes); + var file = (IMediaFile)MediaFile.Read ("/f" + extension, files).File!; + + dynamic typed = file; + FileWriteResult saved = typed.SaveToFile (); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + CollectionAssert.AreEqual (bytes, files.ReadAllBytes ("/f" + extension), extension); + } + + /// + /// Each carrier's path save after a save over its source writes what a fresh read of that file writes, given the + /// same edit: remove an item and save, then add one of the same size and save. + /// + [TestMethod] + [DataRow (".ape")] + [DataRow (".wv")] + [DataRow (".mpc")] + [DataRow (".aac")] + public void PathSaveAfterSave_OfEachCarrier_IsTheFreshReadsSave (string extension) + { + var bytes = Carrier (extension, Tag (false, Orders[0])); + var same = new MockFileSystem (); + same.AddFile ("/f" + extension, bytes); + var file = (IMediaFile)MediaFile.Read ("/f" + extension, same).File!; + dynamic typed = file; + file.Tag!.Title = null; + Assert.IsTrue (((FileWriteResult)typed.SaveToFile ()).IsSuccess); + var fresh = new MockFileSystem (); + fresh.AddFile ("/f" + extension, same.ReadAllBytes ("/f" + extension)); + + file.Tag!.SetCustomField ("ZZZZZ", "Z"); + Assert.IsTrue (((FileWriteResult)typed.SaveToFile ()).IsSuccess); + var reread = (IMediaFile)MediaFile.Read ("/f" + extension, fresh).File!; + reread.Tag!.SetCustomField ("ZZZZZ", "Z"); + Assert.IsTrue (((FileWriteResult)((dynamic)reread).SaveToFile ()).IsSuccess); + + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f" + extension), same.ReadAllBytes ("/f" + extension), extension); + } + + /// Reading n items, removing half, adding one and rendering allocates linearly in n. + [TestMethod] + public void EditAndRender_AllocateLinearlyInTheItemCount () + { + Bounds.AssertLinearAllocation ( + n => Tag (false, [.. Enumerable.Range (0, n).Select (i => $"K{i:D6}=v")]), + bytes => { + var tag = ApeTag.Parse (bytes).Tag!; + var n = tag.ItemCount; + for (var i = 0; i < n; i += 2) + tag.RemoveCustomField ($"K{i:D6}"); + tag.SetCustomField ("NEW", "x"); + _ = tag.Render (); + }, + 2000); + } + + static byte[] Carrier (string extension, byte[] tag) => extension switch { + ".ape" => [.. TestBuilders.MonkeysAudio.CreateMinimal (), .. tag], + ".wv" => [.. TestBuilders.WavPack.CreateMinimal (), .. tag], + ".aac" => [.. TagLibSharp2.Tests.Aac.AacTestBuilder.Adts (8), .. tag], + _ => [.. TestBuilders.Musepack.CreateMinimal (), .. tag], + }; + + /// An APEv2 tag holding text items "Key=value", in this order, with or without a header. + static byte[] Tag (bool header, string[] items) => + Tag (header, [.. items.Select (item => (item[..item.IndexOf ('=')], 0u, Encoding.UTF8.GetBytes (item[(item.IndexOf ('=') + 1)..])))]); + + /// An APEv2 tag holding these items (key, item flags, value), in this order, with or without a header. + static byte[] Tag (bool header, (string Key, uint Flags, byte[] Value)[] items) + { + var body = new List (); + foreach (var (key, itemFlags, value) in items) { + var field = new byte[8]; + BinaryPrimitives.WriteInt32LittleEndian (field, value.Length); + BinaryPrimitives.WriteUInt32LittleEndian (field.AsSpan (4), itemFlags); + body.AddRange (field); + body.AddRange (Encoding.ASCII.GetBytes (key)); + body.Add (0); + body.AddRange (value); + } + + var tagSize = (uint)(body.Count + 32); + var result = new List (); + if (header) + result.AddRange (Frame (tagSize, (uint)items.Length, isHeader: true)); + result.AddRange (body); + result.AddRange (Frame (tagSize, (uint)items.Length, isHeader: false)); + return [.. result]; + + byte[] Frame (uint size, uint count, bool isHeader) + { + var frame = new byte[32]; + "APETAGEX"u8.CopyTo (frame); + BinaryPrimitives.WriteUInt32LittleEndian (frame.AsSpan (8), 2000); + BinaryPrimitives.WriteUInt32LittleEndian (frame.AsSpan (12), size); + BinaryPrimitives.WriteUInt32LittleEndian (frame.AsSpan (16), count); + var flags = (header ? 0x80000000u : 0) | (isHeader ? 0x20000000u : 0); + BinaryPrimitives.WriteUInt32LittleEndian (frame.AsSpan (20), flags); + return frame; + } + } + + /// The items of a rendered tag as "Key=value", in the order they are stored. + static string[] Keys (byte[] tag) + { + var start = tag.AsSpan (0, 8).SequenceEqual ("APETAGEX"u8) ? 32 : 0; + var end = tag.Length - 32; + var rows = new List (); + for (var pos = start; pos < end;) { + var size = BinaryPrimitives.ReadInt32LittleEndian (tag.AsSpan (pos)); + var keyEnd = Array.IndexOf (tag, (byte)0, pos + 8); + var key = Encoding.ASCII.GetString (tag, pos + 8, keyEnd - pos - 8); + var flags = BinaryPrimitives.ReadUInt32LittleEndian (tag.AsSpan (pos + 4)); + var value = (flags & 6) == 2 ? "" : Encoding.UTF8.GetString (tag, keyEnd + 1, size); + rows.Add (key + "=" + value); + pos = keyEnd + 1 + size; + } + + return [.. rows]; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs index d158530b..59c5e95d 100644 --- a/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs +++ b/tests/TagLibSharp2.Tests/Core/SkipPicturesFixtures.cs @@ -304,13 +304,12 @@ static void Clear (Tag? tag) // Every binary item whose key starts with "Cover Art" (APEv2 item types and the cover keys, // https://wiki.hydrogenaud.io/index.php?title=APE_Tag_Item). ApeTag has no public item list, so the test reads - // its dictionary. + // its item list. static List ApePictureKeys (ApeTag tag) { - var items = (System.Collections.Generic.Dictionary)typeof (ApeTag) + var items = (OrderedMap)typeof (ApeTag) .GetField ("_items", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue (tag)!; - return items.Where (item => item.Value.ItemType == ApeItemType.Binary && item.Key.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase)) - .Select (item => item.Key).ToList (); + return items.KeysWhere ((key, item) => item.ItemType == ApeItemType.Binary && key.StartsWith ("Cover Art", StringComparison.OrdinalIgnoreCase)); } static PictureFrame Picture () => new ("image/jpeg", PictureType.FrontCover, "Front", new BinaryData (s_cover)); From 01f85e52a6a0ae8f259f622b118afef692e9addc Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:45:51 -0700 Subject: [PATCH 05/12] fix: Save a non-ASCII AVI INFO change next to a guessed field under a CSET (#220) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cause: when a changed value did not fit the code page an AVI INFO list's CSET declares, the list became UTF-8 under a CSET of 65001, and RiffInfoTag.TryRenderAvi refused the save if an unchanged value's code page was a guess: a CSET of 932, 1251 or another code page the library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252, 0x80-0x9F under code page 0). So a value the reader returned could not always be saved; copying a title read from a guessed field into another field failed. Fix, by kind of guess (review 1's recommendation, for Stephen's review): - A CSET of a code page this library does not decode (932, 1251, any other): the save drops the CSET, keeps every unchanged value's bytes and writes the changes by the no-CSET read rule (Windows-1252 when that reads back as the value, else UTF-8), as a list with no CSET is written. The library reads such a list by that rule already (InfoText.Decode under InfoCharacterSet.Other equals it under None), so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes the code page. - A byte CSET 1252 or 0 leaves undefined: the list becomes UTF-8 under a CSET of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. The guessed byte has no defined meaning to keep, and dropping a 1252 or 0 CSET would change the meaning of exactly decoded text that is also valid UTF-8 ("é"). A list whose own CSET is 65001 keeps its guessed bytes, as before. A changed value is never refused: TryRenderAvi is RenderAvi (out InfoCsetWrite: keep, 65001 or drop), both AviRewrite call sites (span rewrite and stream plan) lose their refusal branch and remove the CSET chunks for a drop, and InfoText.GuessReason and Escape, used only by the refusal message, are gone. AviFile.InfoTag remarks and the [Unreleased] Added line describing the refusal are updated. Trade-off: dropping the CSET loses the declaration. ExifTool then reads the list as Latin-1, so a UTF-8 change shows as mojibake there (ffprobe shows it right); before the save ExifTool and ffprobe showed the untouched Shift-JIS field as undecoded bytes, and they still do. The first version of this commit rewrote the guessed field as the UTF-8 of its Windows-1252 misreading under CSET 65001, which every reader then showed as mojibake and which lost the original bytes. Tests: AviInfoTextTests. The CSET matrix {none, 0, 28591, 932, 1252, 65001} x {ASCII, UTF-8, legacy} x {ASCII, non-ASCII change}, through a mapped field and through the custom-field API, expects a save in every cell: under 932 a non-ASCII change keeps the unchanged bytes and drops the CSET; under 1252 and 0 the guessed value becomes UTF-8 under 65001. Save_GuessedValueNextToAChangeItsCodePageCannotHold_ReadsBackAsItRead over {1252 undefined byte, CSET 0 C1 byte, 932 Shift-JIS, 1251, 1251 holding UTF-8, undefined code page 4242} x {Render, span save, path save, async path save}, and Save_GuessedTextCopiedToAnotherField_ReadsBackTheSame (the issue's case, the Shift-JIS bytes kept) on each entry point. They replace the two refusal tests, which pinned the old behaviour on purpose. Black box (CSET 932, IART Shift-JIS, title set to non-ASCII): the save succeeds, ffmpeg decodes the file, the IART bytes are 93fa967b82cc89cc00 before and after, exiftool reports no CodePage after (932 before), and ffprobe shows the new title. Red: 36 of 141 rows failed on main with the refusal; after the switch, 26 of 141 failed against the first version. Left as it is (review 2 nit): once the CSET is dropped, a later non-ASCII change goes by the no-CSET rule, so Title = "Zoë" is written as the Windows-1252 byte EB and ffprobe shows a replacement character. That is the existing no-CSET behaviour, and the same object and a fresh read agree. --- CHANGELOG.md | 3 +- src/TagLibSharp2/Riff/AviFile.cs | 20 ++- src/TagLibSharp2/Riff/AviRewrite.cs | 35 ++-- src/TagLibSharp2/Riff/InfoText.cs | 62 ++------ src/TagLibSharp2/Riff/RiffInfoTag.cs | 99 ++++++------ .../Riff/AviInfoTextTests.cs | 149 ++++++++++++------ 6 files changed, 197 insertions(+), 171 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab138b1d..aa1d0da6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,7 +78,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Tags: every `LIST INFO` in the first RIFF form (`InfoTag`) and an ID3v2 tag in an `ID32` chunk (`Id3v2Tag`). The unified `Tag` puts INFO first. - Saving keeps the `movi` sample bytes. New tags reuse the tag and `JUNK` space between `hdrl` and `movi`, so nothing moves; when they do not fit, the data moves and the RIFF size, absolute `idx1` offsets, `indx` super index entries, and each standard index's base offset (or, when the base stays put, each entry whose data moved) are shifted. A save is refused, without writing, when an index cannot be verified first. A changed tag chunk cut off by the end of the file is turned into `JUNK`, so a removed value does not return. An unchanged save writes the original bytes. - 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). + - 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, and untouched text whose code page is a guess because of a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) as the UTF-8 of the text read (#220). With no `CSET`, or a `CSET` of a code page not decoded here (for example Shift-JIS or cp1251), untouched text that is not UTF-8 keeps its bytes, the changes are written by the read rule, and such a `CSET` is dropped. 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). - A path save copies `movi` in 64 KB pieces and patches `idx1` and OpenDML indexes from the source, so it no longer loads the file. `Render` and `SaveToFile(path, span)` still build one buffer. `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). - Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 §B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. A JPEG stores the comment and the title, and a GIF the comment; only their copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. @@ -124,6 +124,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An AVI INFO list with a declared `CSET` saves a change its code page cannot hold next to a value whose code page is a guess (#220). The save was refused, naming the guessed field: a `CSET` of 932, 1251 or another code page this library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252; 0x80-0x9F under code page 0). Copying a title read from such a field into another field failed. Under a code page this library does not decode, the save now drops the `CSET` and keeps every unchanged field's bytes, writing the change by the no-`CSET` read rule: this library already reads such a list by that rule, so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes them. Under 1252 or code page 0 the list becomes UTF-8 under a `CSET` of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. Both hold on every save entry point. Without the `CSET`, ExifTool reads a UTF-8 change as Latin-1 - An APE tag keeps its items in the order they were read (#238). A save sorted them by size, so a file that stores them in another order (`sample.ape`, `8bit.wv`, `sample.mpc`) changed on a save with no edit, and items of equal size were written in the order they were added, so after a removal a save from the object that saved before and a save from a fresh read of that save could order them differently. Now a save with no edit writes the items as they were; a changed value stays in its item's place, a value written under its key in place of its alias (`Album Artist` for `ALBUMARTIST`) takes the alias item's place, writing back the pictures or a custom field read moves nothing, and a new item goes after the others, in the order added. A key read twice keeps the first item's place and the last item's value, as before. This holds for Monkey's Audio, WavPack, Musepack and raw AAC. `sample_v8.mpc` declares 11 items and holds 8; its save with no edit now differs only in that count, which it writes as 8 - An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed (`OggVorbisFile.VorbisComment = null`, `OggOpusFile.VorbisComment = null`, `OggFlacFile.RemoveVorbisComment ()`) keeps a `Tag` (#236). It was null; it is now an empty view, as on a FLAC file: reading it creates nothing, its first write creates the comment (vendor `TagLibSharp2` in Vorbis and Opus, empty in Ogg FLAC, as `EnsureVorbisComment` creates it), and a write that leaves that comment empty removes it again, so the save writes what a save with no edit writes. A file that has its comment still returns that comment as its `Tag`. `Tag` is null after `Dispose` - `Picture.DetectMimeType` no longer types any RIFF data as WebP (#234). RIFF data is `image/webp` only when its form type at offset 8 is `WEBP` (RFC 9649 §2.4); WAV, AVI and other RIFF forms, and a RIFF header cut off before its form type, fall through to the file extension, or `application/octet-stream` without one. This reaches every picture typed from its bytes: `PictureFrame.FromBytes` and `FromFile`, `FlacPicture.FromBytes` and `FromFile`, `ApePicture`, the Audible cover, and a Matroska picture given no MIME type, whose save now fails with "is not an image/ media type" instead of writing WAV or AVI bytes as an `image/webp` attachment diff --git a/src/TagLibSharp2/Riff/AviFile.cs b/src/TagLibSharp2/Riff/AviFile.cs index 1b90ca8c..a2a7b83f 100644 --- a/src/TagLibSharp2/Riff/AviFile.cs +++ b/src/TagLibSharp2/Riff/AviFile.cs @@ -91,14 +91,18 @@ internal void MarkPicturesSkipped () /// /// On save, a value that was not changed 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 all fit it; with no CSET, - /// or one this library does not encode, only ASCII fits. Otherwise the list becomes UTF-8 with a CSET - /// of code page 65001 in front of it: unchanged UTF-8 and ASCII values keep their bytes, and unchanged - /// text in a declared code page this library decodes exactly (1252, 28591, 0) is written as UTF-8 of - /// the same text; the new CSET keeps the old one's country, language and dialect codes. The save is - /// refused, with an error naming the field and the reason, rather than changing an unchanged value's - /// text when its code page is a guess (no CSET and not UTF-8), is not decoded here (932 or 1251, say), - /// or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90 or 0x9D - /// in 1252; 0x80-0x9F under code page 0). mediainfo ignores CSET. + /// or one this library does not encode, only ASCII fits. When one does not fit (#220): + /// with no CSET and an unchanged value that is not UTF-8, or with a CSET of a code page this library does not decode + /// (932 or 1251, say), every unchanged value keeps its bytes and the changes are written by the read rule + /// (Windows-1252 when that reads back as the value, else UTF-8), and such a CSET is dropped: this library already + /// reads that list by the no-CSET rule, so every value reads back as it read, and a reader that decodes the code page + /// itself still has the original bytes. Otherwise (no CSET and only ASCII or UTF-8, or a code page this library + /// decodes: 1252, 28591, 0) the list becomes UTF-8 with a CSET of code page 65001 in front of it: + /// unchanged UTF-8 and ASCII values keep their bytes, and every other unchanged value is written as the UTF-8 of the + /// text this reader returned for it (the same text when decoded exactly; the text read when a byte the code page + /// leaves undefined, 0x81, 0x8D, 0x8F, 0x90 or 0x9D in 1252 or 0x80-0x9F under code page 0, made it a guess). The + /// new CSET keeps the old one's country, language and dialect codes. A changed value is never refused. mediainfo + /// ignores CSET. /// /// public RiffInfoTag InfoTag { get; } diff --git a/src/TagLibSharp2/Riff/AviRewrite.cs b/src/TagLibSharp2/Riff/AviRewrite.cs index 1acd5f71..bd78d9e5 100644 --- a/src/TagLibSharp2/Riff/AviRewrite.cs +++ b/src/TagLibSharp2/Riff/AviRewrite.cs @@ -94,18 +94,21 @@ public static bool TryRewrite ( var list = BinaryData.Empty; byte[]? characterSet = null; + var dropCharacterSet = false; if (infoChanged && !info.IsEmpty) { - if (!info.TryRenderAvi (out list, out var declareUtf8, out var refused)) { - error = refused!; - return false; - } + list = info.RenderAvi (out var cset); // The CSET goes right before the list; exiftool honours only a CSET it meets first. - characterSet = declareUtf8 ? AviChunks.Utf8CharacterSetChunk (original) : AviChunks.FirstCharacterSetChunk (original); + characterSet = cset switch { + InfoCsetWrite.Utf8 => AviChunks.Utf8CharacterSetChunk (original), + InfoCsetWrite.Drop => null, + _ => AviChunks.FirstCharacterSetChunk (original), + }; + dropCharacterSet = cset == InfoCsetWrite.Drop; } var blob = Blob (list, characterSet, id3, id3Changed, id3Present ? AviChunks.Name (id3Chunk.Id) : "ID32"); - var plan = Plan (original, movi, hasHeaders ? hdrl.Offset : -1, new Changes (infoChanged, characterSet is not null, id3Changed), blob.Length); + var plan = Plan (original, movi, hasHeaders ? hdrl.Offset : -1, new Changes (infoChanged, characterSet is not null || dropCharacterSet, id3Changed), blob.Length); if (blob.Length == 0 || plan.Target is not null) { output = owned ?? original.ToArray (); if (plan.Target is { } target) { @@ -216,7 +219,8 @@ static bool IsChangedTag (AviTopChunk chunk, Changes changes) => /// /// What the save rewrites. A CSET is rewritten only when a new list is written with one in front: - /// the file's own CSET again, or a 65001 CSET for a list that became UTF-8. A cleared list leaves it. + /// the file's own CSET again, or a 65001 CSET for a list that became UTF-8. It is removed when the list drops a CSET + /// of a code page this library does not decode (#220). A cleared list leaves it. /// readonly struct Changes (bool info, bool characterSet, bool id3) { @@ -690,19 +694,20 @@ internal static bool TryPlanStream ( var list = BinaryData.Empty; byte[]? characterSet = null; + var dropCharacterSet = false; if (infoChanged && !info.IsEmpty) { - if (!info.TryRenderAvi (out list, out var declareUtf8, out var refused)) { - error = refused!; - return false; - } + list = info.RenderAvi (out var cset); - characterSet = declareUtf8 - ? Utf8CharacterSet (FirstChunk (source, ref walk, static item => item.IsCharacterSet, length, chunk)) - : ReadWholeChunk (source, ref walk, static item => item.IsCharacterSet, chunk); + characterSet = cset switch { + InfoCsetWrite.Utf8 => Utf8CharacterSet (FirstChunk (source, ref walk, static item => item.IsCharacterSet, length, chunk)), + InfoCsetWrite.Drop => null, + _ => ReadWholeChunk (source, ref walk, static item => item.IsCharacterSet, chunk), + }; + dropCharacterSet = cset == InfoCsetWrite.Drop; } var blob = Blob (list, characterSet, id3, id3Changed, id3Present ? AviChunks.Name (id3Chunk.Id) : "ID32"); - var save = Plan (ref walk, movi.Value.Offset, hdrl is { } headers ? headers.Offset : -1, new Changes (infoChanged, characterSet is not null, id3Changed), blob.Length); + var save = Plan (ref walk, movi.Value.Offset, hdrl is { } headers ? headers.Offset : -1, new Changes (infoChanged, characterSet is not null || dropCharacterSet, id3Changed), blob.Length); if (blob.Length == 0 || save.Target is not null) { plan = new StreamPlan { InPlace = true, diff --git a/src/TagLibSharp2/Riff/InfoText.cs b/src/TagLibSharp2/Riff/InfoText.cs index 13f40c08..a889376b 100644 --- a/src/TagLibSharp2/Riff/InfoText.cs +++ b/src/TagLibSharp2/Riff/InfoText.cs @@ -30,6 +30,22 @@ internal enum InfoCharacterSet Other } +/// What an AVI save does with the file's CSET chunk when it writes a new INFO list. +internal enum InfoCsetWrite +{ + /// The file's CSET goes in front of the list again (or there is none). + Keep, + + /// A CSET of code page 65001 goes in front of the list, which became UTF-8. + Utf8, + + /// + /// The file's CSET goes: it names a code page this library does not decode, and the list keeps every unchanged + /// value's bytes and writes the changes by the no-CSET read rule (#220). + /// + Drop +} + /// How surely a stored INFO value's text is known. internal enum InfoTextKind { @@ -241,50 +257,4 @@ static int Windows1252Byte (char c) var index = Array.IndexOf (Windows1252High, c); return index < 0 || IsUnassigned1252 ((byte)(0x80 + index)) ? -1 : 0x80 + index; } - - /// - /// Why an unchanged value of kind cannot be rewritten as UTF-8, - /// for the refusal message. is the CSET's wCodePage, or -1 for none. - /// - public static string GuessReason (ReadOnlySpan field, InfoCharacterSet characterSet, int codePage) - { - var end = field.IndexOf ((byte)0); - if (end >= 0) - field = field.Slice (0, end); - switch (characterSet) { - case InfoCharacterSet.Latin1Default: - foreach (var b in field) { - if (IsC1 (b)) - return $"holds byte 0x{b:X2}, which the CSET's code page 0 (ISO 8859/1 without columns 8 and 9) leaves undefined"; - } - - break; - case InfoCharacterSet.Windows1252: - foreach (var b in field) { - if (IsUnassigned1252 (b)) - return $"holds byte 0x{b:X2}, which code page 1252 leaves undefined"; - } - - break; - case InfoCharacterSet.Other: - return $"is in code page {codePage}, which this library does not decode"; - } - - // A list with no CSET is never refused (RiffInfoTag.TryRenderAvi writes it by the read rule). - return $"is not valid in the declared code page {codePage}"; - } - - /// The value with control characters (C0, DEL, C1) written as \uXXXX, for a message. - public static string Escape (string value) - { - var builder = new System.Text.StringBuilder (value.Length); - foreach (var c in value) { - if (c < '\u0020' || c is >= '\u007F' and <= '\u009F') - builder.Append ("\\u").Append (((int)c).ToString ("X4", System.Globalization.CultureInfo.InvariantCulture)); - else - builder.Append (c); - } - - return builder.ToString (); - } } diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs index 21b125f1..144a5ae0 100644 --- a/src/TagLibSharp2/Riff/RiffInfoTag.cs +++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs @@ -63,16 +63,18 @@ public RiffInfoTag () /// /// Values are decoded as describes. /// - /// Invariant on save: a value the caller did not change keeps its meaning under the file's CSET. - /// Changed values are encoded in the file's declared code page when they all fit it (with no CSET, + /// Invariant on save: every value reads back as this reader returned it, and any value it can return can be + /// saved (#220). Changed values are encoded in the file's declared code page when they all fit it (with no CSET, /// or one this library does not encode, only ASCII fits); unchanged values then keep their exact - /// bytes and the CSET is kept as it is. When a changed value does not fit, the list becomes UTF-8 - /// under a CSET of code page 65001: ASCII and UTF-8 values keep their bytes, and a value decoded - /// exactly in its declared code page () is written as UTF-8 of the - /// same text. A value whose code page is a guess () cannot be - /// rewritten. With no CSET, where each field is read on its own (UTF-8, else Windows-1252), the list then - /// keeps every unchanged value's bytes and writes the changed values by that rule, with no CSET, as WAV INFO - /// does; under a CSET refuses instead. + /// bytes and the CSET is kept as it is. When a changed value does not fit: + /// with no CSET and an unchanged value that is not UTF-8, or a CSET of a code page this library does not decode + /// (932, 1251, ...), where each field is read on its own (UTF-8, else Windows-1252), the list keeps every unchanged + /// value's bytes and writes the changed values by that rule, as WAV INFO does, and such a CSET is dropped; otherwise + /// (no CSET and only ASCII or UTF-8, or a code page this library decodes: 1252, 28591, 0) the list becomes UTF-8 + /// under a CSET of code page 65001: ASCII and UTF-8 values keep their bytes, and every other + /// value is written as the UTF-8 of the text this reader returned for it, the same text when it was decoded exactly + /// (), the text read when a byte the code page leaves undefined made it a guess + /// (). /// /// internal RiffInfoTag (InfoCharacterSet characterSet, int codePage = -1) @@ -458,66 +460,53 @@ bool IsUnchanged (string id, string value, out (string Value, byte[] Bytes, Info /// /// Renders the list in AVI text mode, keeping the invariant on . - /// is true when the list became UTF-8 and needs a CSET of code page - /// 65001 in place of the file's own CSET. Returns false, with , when a changed - /// value does not fit the file's declared code page and an unchanged value's code page is a guess. + /// says what the save does with the file's CSET chunk. /// - internal bool TryRenderAvi (out BinaryData list, out bool declareUtf8, out string? error) + internal BinaryData RenderAvi (out InfoCsetWrite cset) { - list = BinaryData.Empty; - declareUtf8 = false; - error = null; + cset = InfoCsetWrite.Keep; if (!_avi) throw new InvalidOperationException ("Not an AVI text mode tag."); - var target = _characterSet; + var needsUtf8 = false; + var hasGuess = false; foreach (var kvp in _fields) { - if (!IsUnchanged (kvp.Key, kvp.Value, out _) && !InfoText.CanEncode (kvp.Value, _characterSet)) { - // Only a file not already in UTF-8 gets here: UTF-8 encodes every value. - target = InfoCharacterSet.Utf8; - declareUtf8 = true; - break; - } + if (!IsUnchanged (kvp.Key, kvp.Value, out var stored)) + needsUtf8 |= !InfoText.CanEncode (kvp.Value, _characterSet); + else + hasGuess |= stored.Kind == InfoTextKind.Guess; } - if (declareUtf8) { - foreach (var kvp in _fields) { - if (IsUnchanged (kvp.Key, kvp.Value, out var stored) && stored.Kind == InfoTextKind.Guess) { - // With no CSET each field is read on its own (UTF-8, else Windows-1252). The legacy bytes stay, and - // the changed values are written by that rule, with no CSET to misdeclare the legacy ones: every - // value this reader returns is stored and reads back the same. - if (_characterSet == InfoCharacterSet.None) { - declareUtf8 = false; - list = RenderFields (InfoCharacterSet.None, keepStored: true); - return true; - } - - var reason = InfoText.GuessReason (stored.Bytes, _characterSet, _codePage); - error = $"Cannot save the INFO list: a changed value needs UTF-8, and {kvp.Key} ('{InfoText.Escape (kvp.Value)}') " - + $"{reason}, so it cannot be rewritten as UTF-8 without guessing its text. Set or remove that field too."; - return false; - } - } + // Only a file not already in UTF-8 needs it: UTF-8 encodes every value. + if (!needsUtf8) + return RenderFields (_characterSet, keepStored: true); + + // With no CSET each field is read on its own (UTF-8, else Windows-1252). The legacy bytes stay, and the changed + // values are written by that rule, with no CSET to misdeclare the legacy ones: every value this reader returns is + // stored and reads back the same. + if (_characterSet == InfoCharacterSet.None && hasGuess) + return RenderFields (InfoCharacterSet.None, keepStored: true); + + // A code page this library does not decode (932, 1251, ...) is read by that same rule already, so dropping its + // CSET changes nothing this library reads, and every unchanged value keeps its bytes (#220): a reader that + // decodes the code page itself still has the original bytes, where a rewrite would leave the UTF-8 of their + // misreading. + if (_characterSet == InfoCharacterSet.Other) { + cset = InfoCsetWrite.Drop; + return RenderFields (InfoCharacterSet.None, keepStored: true); } - list = RenderFields (target, keepStored: true); - return true; + cset = InfoCsetWrite.Utf8; + return RenderFields (InfoCharacterSet.Utf8, keepStored: true); } /// - /// - /// In AVI text mode this is the list writes. When that save would be - /// refused, unchanged values keep their bytes and changed values are UTF-8; no CSET describes that list. - /// + /// In AVI text mode this is the list writes. public override BinaryData Render () { if (_fields.Count == 0) return BinaryData.Empty; - if (!_avi) - return RenderFields (InfoCharacterSet.None, keepStored: true); - if (TryRenderAvi (out var list, out _, out _)) - return list; - return RenderFields (InfoCharacterSet.Utf8, keepStored: true); + return _avi ? RenderAvi (out _) : RenderFields (InfoCharacterSet.None, keepStored: true); } BinaryData RenderFields (InfoCharacterSet target, bool keepStored) @@ -531,10 +520,10 @@ BinaryData RenderFields (InfoCharacterSet target, bool keepStored) if (string.IsNullOrEmpty (kvp.Key) || kvp.Key.Length != 4) continue; - // An unchanged value keeps its bytes, except an exactly decoded legacy value in a list that - // became UTF-8: that one is written as UTF-8 of the same text. + // An unchanged value keeps its bytes, except a legacy value (decoded exactly, or a guess) in a list that + // became UTF-8: that one is written as the UTF-8 of the text read (#220). var bytes = keepStored && IsUnchanged (kvp.Key, kvp.Value, out var stored) - && !(stored.Kind == InfoTextKind.Exact && target == InfoCharacterSet.Utf8) + && !(stored.Kind is InfoTextKind.Exact or InfoTextKind.Guess && target == InfoCharacterSet.Utf8 && _characterSet != InfoCharacterSet.Utf8) ? stored.Bytes : _avi && target != InfoCharacterSet.None ? InfoText.Encode (kvp.Value, target) : InfoText.EncodeByReadRule (kvp.Value); encodedFields.Add ((kvp.Key, bytes)); diff --git a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs index 70da0b85..08d25d3a 100644 --- a/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs +++ b/tests/TagLibSharp2.Tests/Riff/AviInfoTextTests.cs @@ -12,7 +12,11 @@ namespace TagLibSharp2.Tests.Riff; /// /// AVI INFO text and the CSET chunk (MPIDS 1.0, "CSET (Character Set) Chunk": no CSET, or code page 0, /// means ISO 8859/1). Invariant: a value the caller did not change keeps its exact bytes, and so its -/// meaning under the file's CSET; a save that cannot keep that refuses. +/// meaning under the file's CSET. When a change does not fit a code page this library does not decode (932, 1251), the +/// CSET is dropped and every unchanged field keeps its bytes: the library reads such a list by the no-CSET rule already. +/// When a change does not fit a code page it decodes (1252, 0, 28591), the list becomes UTF-8 and an unchanged value is +/// written as the UTF-8 of the text the reader returned. Every value reads back as it read, and any value the reader +/// can return can be saved (#220). /// [TestClass] [TestCategory ("Unit")] @@ -28,12 +32,15 @@ public class AviInfoTextTests /// /// {CSET none, 0, 28591, 932, 1252, 65001} x {unchanged ASCII, UTF-8, legacy} x {changed ASCII, non-ASCII}. - /// Each cell either keeps the unchanged field's bytes and text, or refuses the save. With no CSET a legacy value - /// next to a non-ASCII change keeps its bytes and the change is written by the read rule, with no CSET. + /// Each cell saves, and the unchanged field keeps its bytes, or, when the list becomes UTF-8 and its text is not + /// ASCII or UTF-8, is written as the UTF-8 of the text it read (exact or a guess, #220); it reads back the same + /// either way. With no CSET a legacy value next to a non-ASCII change keeps its bytes and the change is written by + /// the read rule, with no CSET; under CSET 932, which this library does not decode, the CSET is dropped and the + /// same holds. /// [TestMethod] [DynamicData (nameof (Matrix))] - public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, string unchangedKind, string changedKind) + public void Save_UnchangedField_KeepsItsBytesOrItsText (int codePage, string unchangedKind, string changedKind) { var unchanged = UnchangedBytes (codePage, unchangedKind); var builder = new AviTestBuilder { CharacterSet = codePage < 0 ? null : (ushort?)codePage }; @@ -50,22 +57,20 @@ public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, str var nativeUtf8 = codePage == 65001; var kind = Kind (codePage, unchanged); - var byReadRule = changedKind == "nonascii" && codePage < 0 && kind == "guess"; + var dropsCset = changedKind == "nonascii" && codePage == 932; + var byReadRule = changedKind == "nonascii" && ((codePage < 0 && kind == "guess") || dropsCset); var becameUtf8 = changedKind == "nonascii" && !nativeUtf8 && !byReadRule; - var expectRefusal = becameUtf8 && kind == "guess"; var reencoded = becameUtf8 && kind == "exact"; + var guessed = becameUtf8 && kind == "guess"; var cell = $"CSET {codePage}, unchanged {unchangedKind}, changed {changedKind}"; - if (expectRefusal) { - Assert.IsFalse (result.IsSuccess, cell); - StringAssert.Contains (result.Error, "IART", cell); - Assert.IsFalse (fs.FileExists ("/out.avi"), cell); - return; - } Assert.IsTrue (result.IsSuccess, $"{cell}: {result.Error}"); var saved = fs.ReadAllBytes ("/out.avi"); var again = AviFile.Read (saved).File!.InfoTag; - if (reencoded) { + if (guessed) { + // The text the reader returned, as UTF-8: a guess is not checked against .NET's decoder, only kept. + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (artist + "\0"), AviTestBuilder.InfoField (saved, "IART"), cell); + } else if (reencoded) { // The round trip: the original decoded with its declared code page by .NET's own decoder // equals the UTF-8 the save wrote, and the value read back. var declared = Oracle (codePage).GetString (unchanged, 0, Array.IndexOf (unchanged, (byte)0)); @@ -82,7 +87,7 @@ public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, str if (becameUtf8) { Assert.AreEqual ((ushort)65001, CodePage (saved), cell); Assert.AreEqual (1, names.Count (n => n == "CSET"), cell); - } else if (codePage < 0) { + } else if (codePage < 0 || dropsCset) { CollectionAssert.DoesNotContain (names, "CSET", cell); } else { Assert.AreEqual ((ushort)codePage, CodePage (saved), cell); @@ -95,11 +100,11 @@ public void Save_UnchangedField_KeepsItsBytesOrTheSaveRefuses (int codePage, str /// /// The same matrix with the change made through the custom-field API: SetCustomField adds a field the /// file did not hold, or RemoveCustomField drops one it did. Each cell keeps the unchanged field's bytes, or - /// re-encodes it as UTF-8 when the list must become UTF-8, or refuses, exactly as a mapped field change does. + /// re-encodes it as UTF-8 of the text it read when the list must become UTF-8, exactly as a mapped field change does. /// [TestMethod] [DynamicData (nameof (Matrix))] - public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int codePage, string unchangedKind, string changedKind) + public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheirText (int codePage, string unchangedKind, string changedKind) { var unchanged = UnchangedBytes (codePage, unchangedKind); var builder = new AviTestBuilder { CharacterSet = codePage < 0 ? null : (ushort?)codePage }; @@ -117,19 +122,17 @@ public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int code var result = file.SaveToFile ("/out.avi", original, fs); var kind = Kind (codePage, unchanged); - var byReadRule = changedKind == "nonascii" && codePage < 0 && kind == "guess"; + var dropsCset = changedKind == "nonascii" && codePage == 932; + var byReadRule = changedKind == "nonascii" && ((codePage < 0 && kind == "guess") || dropsCset); var becameUtf8 = changedKind == "nonascii" && codePage != 65001 && !byReadRule; var cell = $"CSET {codePage}, unchanged {unchangedKind}, custom field {changedKind}"; - if (becameUtf8 && kind == "guess") { - Assert.IsFalse (result.IsSuccess, cell); - StringAssert.Contains (result.Error, "IART", cell); - return; - } Assert.IsTrue (result.IsSuccess, $"{cell}: {result.Error}"); var saved = fs.ReadAllBytes ("/out.avi"); var again = AviFile.Read (saved).File!.InfoTag; - if (becameUtf8 && kind == "exact") { + if (becameUtf8 && kind == "guess") { + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (artist + "\0"), AviTestBuilder.InfoField (saved, "IART"), cell); + } else if (becameUtf8 && kind == "exact") { var declared = Oracle (codePage).GetString (unchanged, 0, Array.IndexOf (unchanged, (byte)0)); CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (declared + "\0"), AviTestBuilder.InfoField (saved, "IART"), cell); } else { @@ -143,7 +146,7 @@ public void Save_CustomFieldChange_KeepsUnchangedBytesOrTheSaveRefuses (int code Assert.IsNull (AviTestBuilder.InfoField (saved, "IOLD"), cell); if (becameUtf8) Assert.AreEqual ((ushort)65001, CodePage (saved), cell); - else if (codePage >= 0) + else if (codePage >= 0 && !dropsCset) Assert.AreEqual ((ushort)codePage, CodePage (saved), $"{cell}: the declared code page is kept"); else CollectionAssert.DoesNotContain (AviSaveTests.Names (saved), "CSET", cell); @@ -190,7 +193,8 @@ public static IEnumerable Matrix () /// /// How surely the unchanged value is known: ASCII and UTF-8 keep their bytes in a UTF-8 list; text in a - /// declared code page decoded exactly is rewritten as UTF-8; text whose code page is a guess refuses. + /// declared code page decoded exactly is rewritten as the same text in UTF-8; text whose code page is a guess is + /// rewritten as the UTF-8 of the text the reader returned. /// static string Kind (int codePage, byte[] bytes) { @@ -273,41 +277,94 @@ public void Save_NonAsciiChangeUnderADecodableCset_RewritesUntouchedTextAsTheSam Assert.AreEqual (ChangedNonAscii, again.Title); } + /// + /// A guessed value next to a change the declared code page cannot hold (#220). Under a code page this library does + /// not decode (932, 1251, or an undefined one), the CSET is dropped and the guessed value keeps its bytes: the + /// library reads such a list by the no-CSET rule already, so it reads back as it read, and the change is written by + /// that rule. Under a byte the declared code page leaves undefined (0x81 in Windows-1252, 0x80-0x9F under CSET 0's + /// ISO 8859/1), the list becomes UTF-8 under a CSET of 65001 and the guessed value is written as the UTF-8 of the + /// text the reader returned. Each save entry point does the same. + /// [TestMethod] - [DataRow (1252, new byte[] { 0x41, 0x81, 0x42, 0x00 }, "holds byte 0x81, which code page 1252 leaves undefined")] - [DataRow (0, new byte[] { 0x41, 0x96, 0x42, 0x00 }, "holds byte 0x96, which the CSET's code page 0")] - public void Save_UndefinedByteInTheDeclaredCodePage_Refuses (int codePage, byte[] legacy, string reason) + [DynamicData (nameof (GuessedNextToAChange))] + public void Save_GuessedValueNextToAChangeItsCodePageCannotHold_ReadsBackAsItRead (int codePage, byte[] legacy, string entry) { - // 0x81 is unassigned in Windows-1252, and columns 8 and 9 are undefined in CSET 0's ISO 8859/1. var builder = new AviTestBuilder { CharacterSet = (ushort)codePage }; + builder.Info.Add (("INAM", "Old")); builder.InfoBytes.Add (("IART", legacy)); var original = builder.Build (); - var file = AviFile.Read (original).File!; - file.InfoTag.Title = ChangedNonAscii; - var saved = file.SaveToFile ("/x.avi", original, new MockFileSystem ()); + var saved = Save (original, entry, tag => tag.Title = ChangedNonAscii, out var artist); - Assert.IsFalse (saved.IsSuccess); - StringAssert.Contains (saved.Error, "IART"); - StringAssert.Contains (saved.Error, reason); - StringAssert.Contains (saved.Error, codePage == 1252 ? "'A\\u0081B'" : "'A\\u0096B'", "Control characters are shown escaped."); + var cell = $"CSET {codePage}, {entry}"; + var undecoded = codePage is not (1252 or 0); + if (undecoded) { + CollectionAssert.AreEqual (legacy, AviTestBuilder.InfoField (saved, "IART"), $"{cell}: the bytes are kept"); + CollectionAssert.DoesNotContain (AviSaveTests.Names (saved), "CSET", $"{cell}: the CSET is dropped"); + } else { + CollectionAssert.AreEqual (Encoding.UTF8.GetBytes (artist + "\0"), AviTestBuilder.InfoField (saved, "IART"), cell); + Assert.AreEqual ((ushort)65001, CodePage (saved), cell); + } + + var again = AviFile.Read (saved).File!.InfoTag; + Assert.AreEqual (artist, again.Artist, cell); + Assert.AreEqual (ChangedNonAscii, again.Title, cell); } + public static IEnumerable GuessedNextToAChange => + from cell in new (int CodePage, byte[] Legacy)[] { + (1252, [0x41, 0x81, 0x42, 0x00]), + (0, [0x41, 0x96, 0x42, 0x00]), + (932, ShiftJisSong), + (1251, Windows1251Alice), + (1251, [.. Encoding.UTF8.GetBytes ("Björk"), 0]), + (4242, Windows1252Halo), + } + from entry in SaveEntries + select new object[] { cell.CodePage, cell.Legacy, entry }; + + static readonly string[] SaveEntries = ["render", "span", "path", "async-path"]; + + /// + /// The issue's case: a value read from a guessed field copied into another field, under a CSET this library does + /// not decode. The save writes both as the text read. + /// [TestMethod] - [DataRow (932, "is in code page 932, which this library does not decode")] - [DataRow (1251, "is in code page 1251, which this library does not decode")] - public void Save_RefusalNamesItsReason (int codePage, string reason) + [DataRow ("render")] + [DataRow ("span")] + [DataRow ("path")] + [DataRow ("async-path")] + public void Save_GuessedTextCopiedToAnotherField_ReadsBackTheSame (string entry) { - var builder = new AviTestBuilder { CharacterSet = codePage < 0 ? null : (ushort?)codePage }; - builder.InfoBytes.Add (("IART", Windows1251Alice)); + var builder = new AviTestBuilder { CharacterSet = 932 }; + builder.Info.Add (("INAM", "Old")); + builder.InfoBytes.Add (("IART", ShiftJisSong)); var original = builder.Build (); - var file = AviFile.Read (original).File!; - file.InfoTag.Title = ChangedNonAscii; - var saved = file.SaveToFile ("/x.avi", original, new MockFileSystem ()); + var saved = Save (original, entry, tag => tag.Title = tag.Artist, out var artist); - Assert.IsFalse (saved.IsSuccess); - StringAssert.Contains (saved.Error, reason); + var again = AviFile.Read (saved).File!.InfoTag; + Assert.AreEqual (artist, again.Title, entry); + Assert.AreEqual (artist, again.Artist, entry); + CollectionAssert.AreEqual (ShiftJisSong, AviTestBuilder.InfoField (saved, "IART"), $"{entry}: the untouched field keeps its Shift-JIS bytes"); + } + + /// Reads , edits its INFO tag, and saves it through . + static byte[] Save (byte[] original, string entry, Action edit, out string? artist) + { + var files = new MockFileSystem (); + files.AddFile ("/in.avi", original); + var file = entry is "path" or "async-path" ? AviFile.ReadFromFile ("/in.avi", files).File! : AviFile.Read (original).File!; + artist = file.InfoTag.Artist; + edit (file.InfoTag); + var result = entry switch { + "render" => FileWriteResult.Success (0), + "span" => file.SaveToFile ("/out.avi", original, files), + "path" => file.SaveToFile ("/out.avi", files), + _ => file.SaveToFileAsync ("/out.avi", files).GetAwaiter ().GetResult (), + }; + Assert.IsTrue (result.IsSuccess, $"{entry}: {result.Error}"); + return entry == "render" ? file.Render (original).ToArray () : files.ReadAllBytes ("/out.avi"); } [TestMethod] From 60b2e42a15d9fc3a99957193666155a96b6cd542 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:49:43 -0700 Subject: [PATCH 06/12] fix: Keep a RIFF INFO list's fields in the order they were read (#251) Cause: RiffInfoTag kept its fields in a Dictionary, which enumerates in slot order: a field added after a removal reused the freed slot, so it was written in the removed field's place. Read a WAV with INFO [IART, INAM, ISFT], clear Title, save over the source, set Album, save: the object wrote [IART, IPRD, ISFT], and a fresh read of the first save given the same edit wrote [IART, ISFT, IPRD]. The twin of #238's equal-size finding; WAV and AVI share RiffInfoTag. Fix: the fields live in the OrderedMap #238 added: a changed value keeps its field's place, a new field goes last, a removal forgets the place. Parse uses Set, so a field read twice keeps the first place and the last value, as before. FieldIds, SameFieldsAs, RenderAvi and RenderFields walk the fields in place order. Sweep of the other tag stores that could write in a hash enumeration order: see the #251 report; none of them is RIFF code, so nothing else changes here. Tests: RiffInfoFieldOrderTests. SaveAfterSave_IsTheFreshReadsSave over {WAV, AVI} x {9 edits} x {9 edits} (set, remove, add, custom field add and remove, remove-then-add), path saves over the source against a fresh read of the saved file; Edit_PutsFieldsWhereTheRuleSays; DuplicateField_KeepsTheFirstPlaceAndTheLastValue (a mutant that moved a re-read field to the end survived until it was added). Red: 18 of 166 rows failed on main (the remove-then-add cells). --- CHANGELOG.md | 1 + src/TagLibSharp2/Riff/RiffInfoTag.cs | 37 +++-- .../Riff/RiffInfoFieldOrderTests.cs | 137 ++++++++++++++++++ 3 files changed, 156 insertions(+), 19 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Riff/RiffInfoFieldOrderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index aa1d0da6..5f4ab2a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -124,6 +124,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- A WAV or AVI INFO list keeps its fields in the order they were read (#251). A field added after a removal took the removed field's place, so after a save over the source a save from the same object and a save from a fresh read of that file, given the same edit, wrote the fields in different orders. A changed value now stays in its field's place and a new field goes after the others, in the order added, as for APE items (#238) - An AVI INFO list with a declared `CSET` saves a change its code page cannot hold next to a value whose code page is a guess (#220). The save was refused, naming the guessed field: a `CSET` of 932, 1251 or another code page this library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252; 0x80-0x9F under code page 0). Copying a title read from such a field into another field failed. Under a code page this library does not decode, the save now drops the `CSET` and keeps every unchanged field's bytes, writing the change by the no-`CSET` read rule: this library already reads such a list by that rule, so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes them. Under 1252 or code page 0 the list becomes UTF-8 under a `CSET` of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. Both hold on every save entry point. Without the `CSET`, ExifTool reads a UTF-8 change as Latin-1 - An APE tag keeps its items in the order they were read (#238). A save sorted them by size, so a file that stores them in another order (`sample.ape`, `8bit.wv`, `sample.mpc`) changed on a save with no edit, and items of equal size were written in the order they were added, so after a removal a save from the object that saved before and a save from a fresh read of that save could order them differently. Now a save with no edit writes the items as they were; a changed value stays in its item's place, a value written under its key in place of its alias (`Album Artist` for `ALBUMARTIST`) takes the alias item's place, writing back the pictures or a custom field read moves nothing, and a new item goes after the others, in the order added. A key read twice keeps the first item's place and the last item's value, as before. This holds for Monkey's Audio, WavPack, Musepack and raw AAC. `sample_v8.mpc` declares 11 items and holds 8; its save with no edit now differs only in that count, which it writes as 8 - An Ogg Vorbis, Opus or FLAC file whose Vorbis comment was removed (`OggVorbisFile.VorbisComment = null`, `OggOpusFile.VorbisComment = null`, `OggFlacFile.RemoveVorbisComment ()`) keeps a `Tag` (#236). It was null; it is now an empty view, as on a FLAC file: reading it creates nothing, its first write creates the comment (vendor `TagLibSharp2` in Vorbis and Opus, empty in Ogg FLAC, as `EnsureVorbisComment` creates it), and a write that leaves that comment empty removes it again, so the save writes what a save with no edit writes. A file that has its comment still returns that comment as its `Tag`. `Tag` is null after `Dispose` diff --git a/src/TagLibSharp2/Riff/RiffInfoTag.cs b/src/TagLibSharp2/Riff/RiffInfoTag.cs index 144a5ae0..b974c182 100644 --- a/src/TagLibSharp2/Riff/RiffInfoTag.cs +++ b/src/TagLibSharp2/Riff/RiffInfoTag.cs @@ -29,7 +29,8 @@ namespace TagLibSharp2.Riff; /// public class RiffInfoTag : Tag { - readonly Dictionary _fields = new (StringComparer.OrdinalIgnoreCase); + // The fields in the order a save writes them: as read, a changed value in its field's place, a new field last. + readonly OrderedMap _fields = new (StringComparer.OrdinalIgnoreCase); /// /// The stored bytes of each field read from a file, and how surely their text is known (whether they are UTF-8, @@ -273,9 +274,7 @@ public void SetField (string fourCC, string? value) _fields.Remove (fourCC); _stored.Remove (fourCC); } else { -#pragma warning disable CS8601 // Possible null reference assignment - checked above - _fields[fourCC] = value; -#pragma warning restore CS8601 + _fields.Set (fourCC, value!); } } @@ -335,7 +334,7 @@ static bool IsFourCC (string name) /// /// Gets all field identifiers present in this tag. /// - public IEnumerable FieldIds => _fields.Keys; + public IEnumerable FieldIds => _fields.InOrder ().Select (entry => entry.Key); /// /// Gets whether this tag has any fields. @@ -420,7 +419,8 @@ public override void Clear () if (value.Length > 0) tag._stored[fieldId] = (value, bytes, kind); - tag._fields[fieldId] = value; + // A field read again keeps the first one's place and takes the last one's value. + tag._fields.Set (fieldId, value); // Field size does not include the pad. Advance in long; a size near int.MaxValue must not throw. var next = (long)offset + fieldSize + (fieldSize & 1); @@ -444,11 +444,10 @@ internal bool SameFieldsAs (RiffInfoTag? other) if (other._fields.Count != _fields.Count) return false; - using var mine = _fields.GetEnumerator (); - using var theirs = other._fields.GetEnumerator (); - while (mine.MoveNext () && theirs.MoveNext ()) { - if (!string.Equals (mine.Current.Key, theirs.Current.Key, StringComparison.OrdinalIgnoreCase) - || mine.Current.Value != theirs.Current.Value) + var mine = _fields.InOrder (); + var theirs = other._fields.InOrder (); + for (var i = 0; i < mine.Count; i++) { + if (!string.Equals (mine[i].Key, theirs[i].Key, StringComparison.OrdinalIgnoreCase) || mine[i].Value != theirs[i].Value) return false; } @@ -470,9 +469,9 @@ internal BinaryData RenderAvi (out InfoCsetWrite cset) var needsUtf8 = false; var hasGuess = false; - foreach (var kvp in _fields) { - if (!IsUnchanged (kvp.Key, kvp.Value, out var stored)) - needsUtf8 |= !InfoText.CanEncode (kvp.Value, _characterSet); + foreach (var (id, value) in _fields.InOrder ()) { + if (!IsUnchanged (id, value, out var stored)) + needsUtf8 |= !InfoText.CanEncode (value, _characterSet); else hasGuess |= stored.Kind == InfoTextKind.Guess; } @@ -516,17 +515,17 @@ BinaryData RenderFields (InfoCharacterSet target, bool keepStored) var encodedFields = new List<(string Id, byte[] Bytes)> (_fields.Count); var fieldsSize = 4; // "INFO" type - foreach (var kvp in _fields) { - if (string.IsNullOrEmpty (kvp.Key) || kvp.Key.Length != 4) + foreach (var (id, value) in _fields.InOrder ()) { + if (string.IsNullOrEmpty (id) || id.Length != 4) continue; // An unchanged value keeps its bytes, except a legacy value (decoded exactly, or a guess) in a list that // became UTF-8: that one is written as the UTF-8 of the text read (#220). - var bytes = keepStored && IsUnchanged (kvp.Key, kvp.Value, out var stored) + var bytes = keepStored && IsUnchanged (id, value, out var stored) && !(stored.Kind is InfoTextKind.Exact or InfoTextKind.Guess && target == InfoCharacterSet.Utf8 && _characterSet != InfoCharacterSet.Utf8) ? stored.Bytes - : _avi && target != InfoCharacterSet.None ? InfoText.Encode (kvp.Value, target) : InfoText.EncodeByReadRule (kvp.Value); - encodedFields.Add ((kvp.Key, bytes)); + : _avi && target != InfoCharacterSet.None ? InfoText.Encode (value, target) : InfoText.EncodeByReadRule (value); + encodedFields.Add ((id, bytes)); fieldsSize += 8 + bytes.Length + (bytes.Length & 1); } diff --git a/tests/TagLibSharp2.Tests/Riff/RiffInfoFieldOrderTests.cs b/tests/TagLibSharp2.Tests/Riff/RiffInfoFieldOrderTests.cs new file mode 100644 index 00000000..61da5fdb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Riff/RiffInfoFieldOrderTests.cs @@ -0,0 +1,137 @@ +// 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.Riff; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Riff; + +/// +/// A RIFF INFO list keeps its fields in the order they were read, in WAV and in AVI: a changed value stays in its +/// field's place, and a new field goes after the others, in the order added. A field added after a removal used to +/// take the removed field's place, so a save from the object that saved before and a save from a fresh read of that +/// save wrote the fields in different orders. +/// +[TestClass] +[TestCategory ("Unit")] +public class RiffInfoFieldOrderTests +{ + static readonly (string Id, string Value)[] Stored = [("IART", "Artist"), ("INAM", "Title"), ("ISFT", "Lavf")]; + + static readonly (string Name, Action Apply)[] Edits = [ + ("none", _ => { }), + ("set INAM", t => t.Title = "New title"), + ("remove INAM", t => t.Title = null), + ("remove IART", t => t.Artist = null), + ("add IPRD", t => t.Album = "Album"), + ("add ICMT", t => t.Comment = "Comment"), + ("add custom", t => t.SetCustomField ("IXYZ", "x")), + ("remove custom ISFT", t => t.RemoveCustomField ("ISFT")), + ("remove then add", t => { t.Title = null; t.Album = "Album"; }), + ]; + + static readonly string[] Formats = ["wav", "avi"]; + + public static IEnumerable EditPairs => + from format in Formats + from first in Enumerable.Range (0, Edits.Length) + from second in Enumerable.Range (0, Edits.Length) + select new object[] { format, first, second }; + + /// + /// {WAV, AVI} x {first edit} x {second edit}: the object that saved the first edit over its source saves the second + /// as a fresh read of that file does. + /// + [TestMethod] + [DynamicData (nameof (EditPairs))] + public void SaveAfterSave_IsTheFreshReadsSave (string format, int first, int second) + { + var files = new MockFileSystem (); + var path = "/f." + format; + files.AddFile (path, Build (format)); + var file = Read (format, path, files); + Edits[first].Apply (InfoTag (file)); + Save (file, files); + var fresh = new MockFileSystem (); + fresh.AddFile (path, files.ReadAllBytes (path)); + + Edits[second].Apply (InfoTag (file)); + Save (file, files); + var reread = Read (format, path, fresh); + Edits[second].Apply (InfoTag (reread)); + Save (reread, fresh); + + var cell = $"{format}: {Edits[first].Name}, then {Edits[second].Name}"; + CollectionAssert.AreEqual (FieldIds (fresh.ReadAllBytes (path), format), FieldIds (files.ReadAllBytes (path), format), cell); + CollectionAssert.AreEqual (fresh.ReadAllBytes (path), files.ReadAllBytes (path), cell); + } + + /// Where each edit puts the fields: a value set stays in its place, and new fields follow the others in the order added. + [TestMethod] + [DataRow ("wav", "set INAM", new[] { "IART", "INAM", "ISFT" })] + [DataRow ("wav", "remove then add", new[] { "IART", "ISFT", "IPRD" })] + [DataRow ("avi", "set INAM", new[] { "IART", "INAM", "ISFT" })] + [DataRow ("avi", "remove then add", new[] { "IART", "ISFT", "IPRD" })] + public void Edit_PutsFieldsWhereTheRuleSays (string format, string edit, string[] expected) + { + var files = new MockFileSystem (); + var path = "/f." + format; + files.AddFile (path, Build (format)); + var file = Read (format, path, files); + + Edits.Single (e => e.Name == edit).Apply (InfoTag (file)); + + CollectionAssert.AreEqual (expected, InfoTag (file).FieldIds.ToArray (), edit); + Save (file, files); + CollectionAssert.AreEqual (expected, FieldIds (files.ReadAllBytes (path), format), edit); + } + + /// A field read twice keeps the place of the first and the value of the last, as before. + [TestMethod] + public void DuplicateField_KeepsTheFirstPlaceAndTheLastValue () + { + byte[] list = [.. "INFO"u8, .. "INAM"u8, 2, 0, 0, 0, .. "a\0"u8, .. "IART"u8, 2, 0, 0, 0, .. "b\0"u8, .. "INAM"u8, 2, 0, 0, 0, .. "c\0"u8]; + + var tag = RiffInfoTag.Parse (new BinaryData (list))!; + + CollectionAssert.AreEqual ((string[])["INAM", "IART"], tag.FieldIds.ToArray ()); + Assert.AreEqual ("c", tag.Title); + } + + static byte[] Build (string format) + { + if (format == "avi") { + var builder = new AviTestBuilder (); + foreach (var (id, value) in Stored) + builder.Info.Add ((id, value)); + return builder.Build (); + } + + var wav = WavFile.Read (TestBuilders.Wav.CreateMinimal (soundBytes: 64)).File!; + wav.InfoTag = new RiffInfoTag (); + foreach (var (id, value) in Stored) + wav.InfoTag.SetField (id, value); + var files = new MockFileSystem (); + Assert.IsTrue (wav.SaveToFile ("/build.wav", files).IsSuccess); + return files.ReadAllBytes ("/build.wav"); + } + + static IMediaFile Read (string format, string path, MockFileSystem files) => + format == "avi" ? AviFile.ReadFromFile (path, files).File! : WavFile.ReadFromFile (path, files).File!; + + static RiffInfoTag InfoTag (IMediaFile file) => file is AviFile avi ? avi.InfoTag : ((WavFile)file).InfoTag!; + + static void Save (IMediaFile file, MockFileSystem files) + { + var result = file is AviFile avi ? avi.SaveToFile (files) : ((WavFile)file).SaveToFile (files); + Assert.IsTrue (result.IsSuccess, result.Error); + } + + /// The field IDs of the file's INFO list, in the order they are stored. + static string[] FieldIds (byte[] file, string format) + { + var info = format == "avi" ? AviFile.Read (file).File!.InfoTag : WavFile.Read (file).File!.InfoTag; + return info is null ? [] : [.. info.FieldIds]; + } +} From 09fd27ad86d28a23641a1351505e140ca1967804 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 08:07:12 -0700 Subject: [PATCH 07/12] fix: Expose an ASF file's File Properties Object (#250) Cause: AsfFile parsed the File Properties Object to build its audio properties and dropped it, so AsfFileProperties.IsBroadcast, added in ID, size, creation date, packet counts, durations, flags and bit rate could be reached only by calling AsfFileProperties.Parse on the bytes. Fix: AsfFile.FileProperties (AsfFileProperties?), read-only, set from the object the header parse already holds; null when the header has none. Shape and name follow the existing sub-structure properties (Mp4File.VideoProperties, nullable when absent; the type is AsfFileProperties, so the member is FileProperties). Every read entry point (span, stream, path, async path, ReadFromData and the SkipPictures reads) goes through the one header parse, so all fill it. A save copies the object unchanged, so after a save over the source the object's value is the saved file's. XML docs; the public API snapshot gains this one member. Tests: AsfFilePropertiesExposedTests. Read_ExposesTheFilePropertiesObject over {broadcast, not} x {span, stream, path, async path, data, skip-stream, skip-path, skip-data}: the object is there, IsBroadcast and the fields read, and Properties.Duration is its Duration; Read_HeaderWithoutFileProperties_IsNull on every entry point; SaveOverSource_KeepsTheFilePropertiesOfTheSavedFile (sync and async, the header grows) against a fresh read. Red: the tests did not compile on main ("AsfFile does not contain a definition for 'FileProperties'"). --- CHANGELOG.md | 1 + src/TagLibSharp2/Asf/AsfFile.cs | 16 ++- .../Asf/AsfFilePropertiesExposedTests.cs | 115 ++++++++++++++++++ .../TagLibSharp2.PublicApi.verified.txt | 1 + 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesExposedTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f4ab2a2..07abd514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `AsfFile.FileProperties` (`AsfFileProperties?`) exposes the File Properties Object the header holds, or null when it has none (#250). `AsfFileProperties.IsBroadcast` (#249), which tells why a file still being written reads a duration of 0, could only be reached by parsing the file again; the file ID, size, creation date, packet counts, durations, flags and bit rate can now be read too. Every read entry point fills it, `SkipPictures` reads included. A header with more than one (the specification allows one) gives the last - `WavFile.SaveToFile ()` and `AiffFile.SaveToFile ()` save back to `SourcePath` through the file system the file was read with (or the one given), as every other format does, so `file.Tag.Title = x; file.SaveToFile ();` works on WAV and AIFF (#235). They refuse as `SaveToFileAsync ()` does: a file not read from a path, or read with `SkipPictures`. `WavFile.Tag` and `AviFile.Tag` are public; each was only the explicit `IMediaFile.Tag`, so `wav.Tag` and `avi.Tag` did not compile on a `WavFile` or `AviFile` variable. On a WAV file with both an ID3v2 tag and an INFO list, `Tag` is now a view over both, ID3v2 first, so a set or `Clear` reaches both and ffprobe, ExifTool and MediaInfo show no stale copy (it was the ID3v2 tag alone, and the INFO list kept the old values). `AviFile.Tag` is the INFO tag, combined with the ID3v2 tag when there is one, and is never null, after `Dispose` too; on an AVI with no ID3v2 tag a field INFO cannot hold, such as a MusicBrainz ID, is not stored. After a successful save over its source a WAV, AVI or AIFF file's view goes on without a tag the save emptied and did not write, as a fresh read of the saved file has none, so the next value set through `Tag` goes where that read's would; the emptied tag stays the file's, so a value set later through a reference to it is written; a kept ID3v2 tag becomes a new ID3v2.4 tag, as a view creates one, and the view's next write that needs an ID3v2 tag uses it. After a save to another path the object still describes its source - `Mp4File.VideoProperties` (`VideoProperties?`) gives the width, height, codec, duration and rotation of the first video track, or null without one. Width and height are the sample entry's coded size, as ffprobe and MediaInfo report it: the track matrix is not applied and the pixel aspect ratio is ignored. An `mp4v` track's codec comes from its `esds` object type (MPEG-4, MPEG-1 Video, MPEG-2 Video, JPEG, PNG, JPEG 2000) - `VideoProperties.Rotation`: the clockwise rotation, 0 to 359 degrees, that the file asks a player to apply. MP4 and QuickTime read it from the track header matrix (0 when the matrix mirrors or skews the picture); Matroska reads `ProjectionPoseRoll` for a rectangular projection with no yaw or pitch. Other formats report 0 diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs index 3765a44e..6f9cb95f 100644 --- a/src/TagLibSharp2/Asf/AsfFile.cs +++ b/src/TagLibSharp2/Asf/AsfFile.cs @@ -42,6 +42,17 @@ internal void MarkPicturesSkipped () /// public AudioProperties Properties { get; } + /// + /// Gets the File Properties Object the header holds, or null when it has none (ASF Specification 01.20.03, File + /// Properties Object). + /// + /// + /// takes its duration from this object, so + /// tells why a file still being written reads a duration of 0. A save copies the object unchanged, so after a save + /// over the source this is still the saved file's. + /// + public AsfFileProperties? FileProperties { get; } + /// /// Gets the source file path if the file was read from disk. /// @@ -67,10 +78,11 @@ internal void MarkPicturesSkipped () /// public MediaFormat Format => MediaFormat.Asf; - AsfFile (AsfTag tag, AudioProperties audioProperties) + AsfFile (AsfTag tag, AudioProperties audioProperties, AsfFileProperties? fileProperties) { Tag = tag; Properties = audioProperties; + FileProperties = fileProperties; } // ═══════════════════════════════════════════════════════════════ @@ -194,7 +206,7 @@ static AsfFileReadResult Parse (ReadOnlySpan data) // Create audio properties var audioProps = CreateAudioProperties (fileProps, streamProps); - var file = new AsfFile (tag, audioProps); + var file = new AsfFile (tag, audioProps, fileProps); file._originalData = data.ToArray (); return AsfFileReadResult.Success (file); } diff --git a/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesExposedTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesExposedTests.cs new file mode 100644 index 00000000..05d371ed --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfFilePropertiesExposedTests.cs @@ -0,0 +1,115 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// An exposes the File Properties Object it read (#250), so a caller can see why a broadcast file +/// reads a duration of 0 () without parsing the file again. It is null when +/// the header has none, the same on every read entry point, and still the file's after a save over the source. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfFilePropertiesExposedTests +{ + // The Flags field of the File Properties Object CreateMinimalWma writes: the 30-byte Header Object, the object's + // 24-byte header, then File ID (16), File Size, Creation Date, Data Packets Count, Play Duration, Send Duration and + // Preroll (8 each) (ASF Specification 01.20.03, File Properties Object). + const int FlagsOffset = 30 + 24 + 16 + (6 * 8); + + static readonly string[] Entries = ["span", "stream", "path", "async-path", "data", "skip-stream", "skip-path", "skip-data"]; + + static readonly bool[] Broadcasts = [false, true]; + + public static IEnumerable Cases => + from broadcast in Broadcasts + from entry in Entries + select new object[] { broadcast, entry }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void Read_ExposesTheFilePropertiesObject (bool broadcast, string entry) + { + var bytes = AsfTestBuilder.CreateMinimalWma (title: "T", durationMs: 2500, bitrate: 96000); + BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (FlagsOffset), broadcast ? 0x03u : 0x02u); + + var file = ReadOn (entry, bytes); + + var cell = $"broadcast {broadcast}, {entry}"; + Assert.IsNotNull (file.FileProperties, cell); + Assert.AreEqual (broadcast, file.FileProperties.IsBroadcast, cell); + Assert.IsTrue (file.FileProperties.IsSeekable, cell); + Assert.AreEqual (25_000_000UL, file.FileProperties.PlayDurationNs, cell); + Assert.AreEqual (96000u, file.FileProperties.MaxBitrate, cell); + Assert.AreEqual (file.FileProperties.Duration, file.Properties.Duration, $"{cell}: the duration comes from this object"); + Assert.AreEqual (broadcast ? TimeSpan.Zero : TimeSpan.FromMilliseconds (2500), file.Properties.Duration, cell); + } + + /// A header without a File Properties Object reads, with no file properties. + [TestMethod] + public void Read_HeaderWithoutFileProperties_IsNull () + { + var header = AsfTestBuilder.CreateHeaderObject (AsfTestBuilder.CreateAudioStreamPropertiesObject (44100, 2, 16)); + byte[] bytes = [.. header, .. AsfTestBuilder.CreateDataObject (0)]; + + foreach (var entry in Entries) { + var file = ReadOn (entry, bytes); + Assert.IsNull (file.FileProperties, entry); + } + } + + /// + /// After a save over the source that grows the header, the object's file properties are a fresh read's of the + /// saved file, on the sync and async path saves. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void SaveOverSource_KeepsTheFilePropertiesOfTheSavedFile (bool async) + { + var bytes = AsfTestBuilder.CreateMinimalWma (title: "T", durationMs: 2500); + BinaryPrimitives.WriteUInt32LittleEndian (bytes.AsSpan (FlagsOffset), 0x03u); + var files = new MockFileSystem (); + files.AddFile ("/f.wma", bytes); + var file = AsfFile.ReadFromFile ("/f.wma", files).File!; + + file.Tag.Title = new string ('L', 4000); + var saved = async ? file.SaveToFileAsync (files).GetAwaiter ().GetResult () : file.SaveToFile (files); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var fresh = AsfFile.Read (files.ReadAllBytes ("/f.wma")).File!; + Assert.IsNotNull (file.FileProperties); + Assert.IsNotNull (fresh.FileProperties); + Assert.IsTrue (file.FileProperties.IsBroadcast); + Assert.AreEqual (Describe (fresh.FileProperties), Describe (file.FileProperties)); + } + + static string Describe (AsfFileProperties p) => + $"{p.FileId}/{p.FileSize}/{p.CreationDateFiletime}/{p.DataPacketsCount}/{p.PlayDurationNs}/{p.SendDurationNs}/" + + $"{p.PrerollMs}/{p.Flags}/{p.MinPacketSize}/{p.MaxPacketSize}/{p.MaxBitrate}"; + + static AsfFile ReadOn (string entry, byte[] bytes) + { + var files = new MockFileSystem (); + files.AddFile ("/f.wma", bytes); + var skip = new MediaReadOptions { SkipPictures = true }; + var read = entry switch { + "span" => AsfFile.Read (bytes).File, + "stream" => (AsfFile?)MediaFile.Read (new MemoryStream (bytes, writable: false), "f.wma").File, + "path" => AsfFile.ReadFromFile ("/f.wma", files).File, + "async-path" => AsfFile.ReadFromFileAsync ("/f.wma", files).GetAwaiter ().GetResult ().File, + "data" => (AsfFile?)MediaFile.ReadFromData (bytes, "f.wma").File, + "skip-stream" => (AsfFile?)MediaFile.Read (new MemoryStream (bytes, writable: false), skip, "f.wma").File, + "skip-path" => (AsfFile?)MediaFile.Read ("/f.wma", skip, files).File, + _ => (AsfFile?)MediaFile.ReadFromData (bytes, skip, "f.wma").File, + }; + Assert.IsNotNull (read, entry); + return read; + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index c588221c..7fbec544 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -511,6 +511,7 @@ namespace TagLibSharp2.Asf { public string? Album { get; set; } public string? Artist { get; set; } + public TagLibSharp2.Asf.AsfFileProperties? FileProperties { get; } public TagLibSharp2.Core.MediaFormat Format { get; } public bool PicturesLoaded { get; } public TagLibSharp2.Core.AudioProperties Properties { get; } From 8926c6abce3a563f9b137e75403d30bd42c73d43 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 08:31:03 -0700 Subject: [PATCH 08/12] fix: Keep an MP4 ilst's items in the order they were read (#252) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cause: Mp4Tag kept its standard atoms in a Dictionary, which enumerates in slot order, so an atom added after a removal took the removed atom's slot; an iTunes ilst render wrote the standard atoms in that order, then the freeform fields, the cover art and the kept atoms, so a save grouped the items by kind. A save with no edit reordered sample.m4a, bgo_676934.m4a, bgo_701689.m4a, sample_replaygain.m4a and "01 Horrible Theme.m4a", and after a save over the source the same object wrote new atoms in another order than a fresh read of the saved file (ffmpeg m4a: clear Title and Genre, save, set Composer, Year, Conductor, save: ©day first from the object, last from a fresh read). The object's memory of the file also went stale after such a save, in a keys meta and in a moov/meta beside udta/meta: slots, key indexes, the movie meta a field lived in, the places of fields read from the second meta, and the placement after a Clear (review 1 B2, N2). Fix: every ilst item takes a place from one Places counter, in read order. Standard atoms and freeform fields live in OrderedMaps sharing it (OrderedMap gains an optional shared Places, Placed () and TryGetValue with the place), the cover art keeps a place while it has pictures, and each kept atom records its place (a field's earlier value kept by KeepCurrentValue takes the field's place). The iTunes render writes all items in place order; the keyed render appends fields without a slot in place order. Freeform fields are now replaced in place (they moved to the end). After a save over the source, on every save entry point, the object goes on as a fresh read of the saved file does: Mp4File.Adopt parses the moov the save wrote, the tag the object holds takes that read's state (Mp4Tag.AdoptStateOf, every field), or a new tag's when the save wrote no ilst, and the placement follows. That tag keeps its identity whether the file read it, the caller assigned it or a view created it, so a reference to it stays live and a later edit through it is written (review 2 B1: a first version replaced an assigned tag by the one read back, and set Tag to null when no ilst was written, so "strip, save, retag, save" lost the retag). Whether the save went over the source is decided by #179's rule (SavedOverSource.Holds: the file at SourcePath holds the written moov at its offset and the written length), so a path with a "." segment or an explicitly passed default file system counts (review 1 N1); the other formats already decide it by content. That read-back costs one source length read, which Mp4SaveStreamsAudioTests and Mp4ChapterSaveStreamsTests now expect, as the MP3 tests do. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read (BothMetas_ClearedThenSetFieldStaysInMovieMeta keeps passing). KeepCurrentValue finds the field it keeps by its id instead of walking and sorting every field, so a read where a second meta overrides n fields is linear in n in every order (review 1 B1: 16,000 overridden freeform fields took 8.5 s and 17.7 GB). Tests: Mp4IlstItemOrderTests. SaveAfterSave_IsTheFreshReadsSave over {iTunes ilst with interleaved standard, cover, freeform and unknown atoms; mdta meta; mdta moov/meta beside an iTunes udta/meta} x {12 edits} x {12 edits}; RandomSequence_EverySaveIsTheFreshReadsSave (four layouts, a keyed moov/meta alone included, 60 seeds each, three saves of one to three edits from 21, Clear and an assigned tag among them, through a random one of the six saves); RemoveSaveSetAgain_OnEverySaveEntryPoint; SaveOverTheSource_UnderAnySpelling_IsTheFreshReadsSave (real files: a "." segment, an explicit default file system); RemoveSavedElsewhere_SetAgain_GoesBackWhereItWasRead; SaveOverTheSource_KeepsTheReadTagLive; AdoptStateOf_TakesEveryField (every instance field, by reflection, so a field added later is caught); ClearOrAssign_PicturesSetAfterATitleGoAfterIt (pins both _picturesPlace resets); Read_SecondMetaOverridingEveryField_AllocatesLinearly (both orders); NoEditSave_KeepsTheItemsInTheirOrder; Edit_PutsItemsWhereTheRuleSays; EditAndRender_AllocateLinearlyInTheItemCount. Offline, the review's exhaustive two-step matrix (every pair of steps of zero to two edits from 19, 145,161 sequences per layout, the six saves in rotation): 0 differences in the iTunes, keys and two-meta layouts (head of round 1: 0, 436 and 9,330). Grid: every MP4 sample's no-edit save is byte-identical now (5 were not). Black box: the ffmpeg scenario writes the same bytes from both objects; qt-artwork.mov Clear, save, set, save is the fresh read's; a title edit of sample.m4a shows in ffprobe, exiftool and MediaInfo, and ffmpeg decodes it. Red: 72 of 454 rows failed on main; of the round-2 tests, 22 failed at the round-1 head (random sequences, both scaling rows, the four spellings). HeldTagTests' MP4 rows (#258) and Mp4_AssignedTag_TakesALaterEdit pin the kept identity. --- CHANGELOG.md | 1 + src/TagLibSharp2/Core/OrderedMap.cs | 54 +- src/TagLibSharp2/Mp4/Mp4File.cs | 78 ++- src/TagLibSharp2/Mp4/Mp4Tag.cs | 232 +++++--- .../Mp4/Mp4ChapterSaveStreamsTests.cs | 3 +- .../Mp4/Mp4IlstItemOrderTests.cs | 496 ++++++++++++++++++ .../Mp4/Mp4SaveStreamsAudioTests.cs | 3 +- 7 files changed, 770 insertions(+), 97 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Mp4/Mp4IlstItemOrderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 07abd514..afc400f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An MP4 ilst keeps its items in the order they were read, and a save after a save over the source writes what a fresh read of the saved file writes (#252). Standard atoms, freeform (`----`) fields, cover art and atoms the tag does not map share one order: a set field stays in its item's place and a new field goes after the others, in the order added. A save grouped them by kind and wrote the standard atoms in the order of a dictionary that reused a removed atom's slot, so a save with no edit reordered `sample.m4a`, `bgo_676934.m4a`, `bgo_701689.m4a`, `sample_replaygain.m4a` and `01 Horrible Theme.m4a` (it is now byte-identical). After a save over the source the object's tag takes the state a fresh read of the saved file has (its items, places, keys and key indexes, slots and metas), so the next save writes what that read's save writes in an iTunes `ilst`, a QuickTime `keys` meta, and a `moov/meta` beside `udta/meta` alike; the tag the object holds keeps its identity, whether the file read it, the caller assigned it or a view created it, and takes a new tag's state when the save wrote no `ilst`, so a reference to it stays live and a later edit through it is written. A save over the source is recognised as #179 recognises it, by what the file at `SourcePath` holds, under any spelling of the path or file system. A read where a second meta overrides n fields is linear in n again; it walked every field for each one. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read - A WAV or AVI INFO list keeps its fields in the order they were read (#251). A field added after a removal took the removed field's place, so after a save over the source a save from the same object and a save from a fresh read of that file, given the same edit, wrote the fields in different orders. A changed value now stays in its field's place and a new field goes after the others, in the order added, as for APE items (#238) - An AVI INFO list with a declared `CSET` saves a change its code page cannot hold next to a value whose code page is a guess (#220). The save was refused, naming the guessed field: a `CSET` of 932, 1251 or another code page this library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252; 0x80-0x9F under code page 0). Copying a title read from such a field into another field failed. Under a code page this library does not decode, the save now drops the `CSET` and keeps every unchanged field's bytes, writing the change by the no-`CSET` read rule: this library already reads such a list by that rule, so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes them. Under 1252 or code page 0 the list becomes UTF-8 under a `CSET` of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. Both hold on every save entry point. Without the `CSET`, ExifTool reads a UTF-8 change as Latin-1 - An APE tag keeps its items in the order they were read (#238). A save sorted them by size, so a file that stores them in another order (`sample.ape`, `8bit.wv`, `sample.mpc`) changed on a save with no edit, and items of equal size were written in the order they were added, so after a removal a save from the object that saved before and a save from a fresh read of that save could order them differently. Now a save with no edit writes the items as they were; a changed value stays in its item's place, a value written under its key in place of its alias (`Album Artist` for `ALBUMARTIST`) takes the alias item's place, writing back the pictures or a custom field read moves nothing, and a new item goes after the others, in the order added. A key read twice keeps the first item's place and the last item's value, as before. This holds for Monkey's Audio, WavPack, Musepack and raw AAC. `sample_v8.mpc` declares 11 items and holds 8; its save with no edit now differs only in that count, which it writes as 8 diff --git a/src/TagLibSharp2/Core/OrderedMap.cs b/src/TagLibSharp2/Core/OrderedMap.cs index e3a1aa68..54d2c38e 100644 --- a/src/TagLibSharp2/Core/OrderedMap.cs +++ b/src/TagLibSharp2/Core/OrderedMap.cs @@ -12,18 +12,22 @@ namespace TagLibSharp2.Core; /// of that save writes, and a save with no edit writes the values as they were. /// /// -/// A lookup, a replacement and a removal take constant time; sorts by place, so any number of -/// edits and one render take O(n log n) in the values a file holds. The places come from a counter, not from the keys, -/// so no choice of keys makes the work grow faster. +/// A lookup, a replacement and a removal take a dictionary operation; sorts by place, so any +/// number of edits and one render take O(n log n) in the values a file holds. The order comes from a counter, not from +/// the keys, so no choice of keys changes it. The dictionary underneath hashes the keys as any string dictionary does. /// /// How keys compare. /// The number of values to allocate room for. -internal sealed class OrderedMap (IEqualityComparer comparer, int capacity = 0) +/// +/// Where new places come from. Maps that share one write their values in one order between them (an MP4 ilst's +/// atoms and freeform fields, #252); a map given none has its own. +/// +internal sealed class OrderedMap (IEqualityComparer comparer, int capacity = 0, Places? places = null) { readonly Dictionary _entries = new (capacity, comparer); - // The place of the next new value. Places only grow, so a new value always goes after every value there is. - long _next; + // Places only grow, so a new value always goes after every value there is. + readonly Places _places = places ?? new Places (); public int Count => _entries.Count; @@ -40,9 +44,22 @@ public bool TryGetValue (string key, [MaybeNullWhen (false)] out TValue value) return false; } + /// The value under and its place, when there is one. + public bool TryGetValue (string key, [MaybeNullWhen (false)] out TValue value, out long place) + { + if (_entries.TryGetValue (key, out var entry)) { + (value, place) = entry; + return true; + } + + value = default; + place = -1; + return false; + } + /// Stores under : in the place of the value it replaces, else last. public void Set (string key, TValue value) => - _entries[key] = (value, _entries.TryGetValue (key, out var entry) ? entry.Place : _next++); + _entries[key] = (value, _entries.TryGetValue (key, out var entry) ? entry.Place : _places.Next ()); /// /// Removes and stores under : in the place of @@ -79,6 +96,16 @@ public List KeysWhere (Func match) /// Every value with the key it is stored under, in the order a save writes them. public List<(string Key, TValue Value)> InOrder () + { + var entries = Placed (); + var ordered = new List<(string, TValue)> (entries.Count); + foreach (var (key, value, _) in entries) + ordered.Add ((key, value)); + return ordered; + } + + /// Every value with its key and its place, in place order, to merge with another map's values. + public List<(string Key, TValue Value, long Place)> Placed () { var entries = new List<(string Key, TValue Value, long Place)> (_entries.Count); foreach (var pair in _entries) @@ -86,9 +113,14 @@ public List KeysWhere (Func match) // Places are unique, so the sort needs no tie-break and is the same however the dictionary enumerates. entries.Sort (static (a, b) => a.Place.CompareTo (b.Place)); - var ordered = new List<(string, TValue)> (entries.Count); - foreach (var (key, value, _) in entries) - ordered.Add ((key, value)); - return ordered; + return entries; } } + +/// The places gives new values; shared, they order several maps as one. +internal sealed class Places +{ + long _next; + + public long Next () => _next++; +} diff --git a/src/TagLibSharp2/Mp4/Mp4File.cs b/src/TagLibSharp2/Mp4/Mp4File.cs index fb6536b0..1250552b 100644 --- a/src/TagLibSharp2/Mp4/Mp4File.cs +++ b/src/TagLibSharp2/Mp4/Mp4File.cs @@ -78,7 +78,7 @@ internal void MarkPicturesSkipped () // The tag as read. A different tag assigned to Tag replaces the mapped fields on save, in // every meta, and the items the tag does not map stay; null removes all metadata, as Clear. - readonly Mp4Tag? _readTag; + Mp4Tag? _readTag; /// /// Gets the audio properties (duration, bitrate, sample rate, etc.). @@ -101,7 +101,7 @@ internal void MarkPicturesSkipped () public string FileType { get; private set; } = string.Empty; // Where the tag was read from. A save writes it back there. - Mp4MetaPlacement MetaPlacement { get; init; } + Mp4MetaPlacement MetaPlacement { get; set; } /// /// Gets the audio duration from audio properties. @@ -2981,7 +2981,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, return FileWriteResult.Failure (error ?? "Failed to render MP4 file"); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.Write (path, rendered.Span, fileSystem); + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), fileSystem, rendered); } /// @@ -3007,7 +3007,64 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure (error ?? "Failed to render MP4 file")); fileSystem ??= _sourceFileSystem; - return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken); + return AdoptAsync (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), fileSystem, rendered); + } + + // A save of the whole file in memory: its moov is found where the render put it. + FileWriteResult Adopt (FileWriteResult result, IFileSystem? fileSystem, BinaryData written) + { + if (!result.IsSuccess || FindTopLevel (written.Span, "moov") is not { } moov) + return result; + return Adopt (result, fileSystem, written.Length, moov.Offset, written.Memory.Slice ((int)moov.Offset, (int)moov.Length)); + } + + async Task AdoptAsync (Task save, IFileSystem? fileSystem, BinaryData written) => + Adopt (await save.ConfigureAwait (false), fileSystem, written); + + /// + /// After a save over the source the object goes on as a fresh read of the saved file does (#252): its tag takes the + /// state of the tag read back from the moov the save wrote, and the tag's placement with it, so a later save writes + /// what that read's save writes. Whether the save went over the source is decided as the other formats decide it + /// (#179, ): the file at holds the bytes written, however the + /// path was spelled and through whichever file system. A save elsewhere leaves the source as it was, and the object + /// still describes it. The tag the object holds keeps its identity, whether the file read it, the caller assigned it + /// or a view created it, so a reference to it stays live and a later edit through it is written (review 2 B1): it + /// takes the state of the tag read back, or of a new tag when the save wrote no ilst, as a fresh read's view + /// creates one. + /// + FileWriteResult Adopt (FileWriteResult result, IFileSystem? fileSystem, long length, long moovOffset, ReadOnlyMemory moov) + { + if (!result.IsSuccess || !SavedOverSource.Holds (SourcePath, fileSystem, length, new WrittenBytes (moovOffset, moov))) + return result; + + var parsed = Mp4Box.Parse (moov.Span); + if (!parsed.IsSuccess || parsed.Box is null) + return result; + + var (readBack, placement) = ExtractMetadata (parsed.Box); + MetaPlacement = placement; + _creation = null; + if (Tag is not null) + Tag.AdoptStateOf (readBack ?? new Mp4Tag ()); + else + Tag = readBack; + _readTag = Tag; + return result; + } + + // The offset and length of the first top-level box of type type in a whole file, or null. + static (long Offset, long Length)? FindTopLevel (ReadOnlySpan file, string type) + { + long offset = 0; + while (offset + Mp4Box.HeaderSize <= file.Length) { + if (!TryMeasure (file[(int)offset..], out var found, out var size, out _) || size <= 0 || size > file.Length - offset) + return null; + if (found == type) + return (offset, size); + offset += size; + } + + return null; } /// @@ -3190,26 +3247,35 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, if (cancellationToken.IsCancellationRequested) return FileWriteResult.Failure ("Failed to re-read source file: Operation was cancelled"); + long length = 0; + long moovAt = 0; var written = PathSave.Replace (destinationPath, opened, output => { for (var i = 0; i < boxes.Count; i++) { if (i == droppedIndex) continue; if (i == moovIndex) { + moovAt = length; StreamCopy.Write (output, moovBytes, copyBuffer); + length += moovBytes.Length; if (chapterBytes.Length > 0) StreamCopy.Write (output, chapterBytes, copyBuffer); + length += chapterBytes.Length; } else if (patched[i] is { } block) { StreamCopy.Write (output, block, copyBuffer); + length += block.Length; } else { CopyFileRange (stream, output, boxes[i].Start, boxes[i].Length, copyBuffer); + length += boxes[i].Length; } } - if (tailStart >= 0) + if (tailStart >= 0) { CopyFileRange (stream, output, tailStart, fileLength - tailStart, copyBuffer); + length += fileLength - tailStart; + } }); source = null; - return written; + return Adopt (written, fileSystem, length, moovAt, moovBytes); } finally { source?.Dispose (); if (chunk is not null) diff --git a/src/TagLibSharp2/Mp4/Mp4Tag.cs b/src/TagLibSharp2/Mp4/Mp4Tag.cs index 60b77aa0..238b7d49 100644 --- a/src/TagLibSharp2/Mp4/Mp4Tag.cs +++ b/src/TagLibSharp2/Mp4/Mp4Tag.cs @@ -49,48 +49,63 @@ public enum Mp4ContentRating /// public sealed class Mp4Tag : Tag { - readonly Dictionary> _atoms = new (); - readonly List _pictures = new (); + // The tag's state. None of it is readonly: after a save over the source the file takes the state a fresh read of the + // saved file has (AdoptStateOf), so a later save writes what that read's save writes (#252). - // mean and name stay separate so a colon in either field is not a delimiter. - // The list keeps render order; the index finds a field without scanning, so a file - // with many freeform atoms reads in linear time. - readonly LinkedList _freeform = new (); - readonly Dictionary<(string Mean, string Name), LinkedListNode> _freeformByKey = new (); + // Every ilst item the tag writes takes a place from one counter, in the order it was read, so a save writes the + // items in that order: a set field stays in its item's place, a new one goes after the others (#252). The standard + // atoms, the freeform fields, the cover art and the kept atoms share it. + Places _places = new (); + OrderedMap> _atoms; + List _pictures = new (); + long _picturesPlace = -1; + + // Keyed by FreeformId, so a colon in the mean or the name is not a delimiter. The map finds a field without + // scanning, so a file with many freeform atoms reads in linear time. + OrderedMap _freeform; // ilst children that are not rebuilt from parsed fields, such as "orch". // Indexed by 4-byte type so one edit does not scan every child. - readonly List _preservedAtoms = new (); - readonly Dictionary> _preservedByType = new (); + List _preservedAtoms = new (); + Dictionary> _preservedByType = new (); // Preserved freeform boxes that carry a mean and a name, so a set drops its twin directly. - readonly Dictionary<(string Mean, string Name), List> _preservedFreeformByKey = new (); + Dictionary<(string Mean, string Name), List> _preservedFreeformByKey = new (); // Set when the ilst belongs to a QuickTime meta whose handler is "mdta". Items are then typed // by key index, so a field remembers the key it was read from and a new field gets a key. Mp4QuickTimeKeys? _keys; bool _cleared; - readonly Dictionary _keyIndexByField = new (StringComparer.Ordinal); + Dictionary _keyIndexByField = new (StringComparer.Ordinal); // Items a field was read from when they are kept byte for byte: every item of an "mdta" meta // that names a field (keyed, iTunes-typed, or with a value the reader rejects), and the items // of a second meta (moov/meta beside udta/meta). While a field's value comes from them, an // unedited save writes them back as they were; setting the field drops all of them. - readonly Dictionary> _sources = new (StringComparer.Ordinal); - readonly HashSet _valueFromSources = new (StringComparer.Ordinal); - readonly Dictionary _valueRank = new (StringComparer.Ordinal); - readonly Dictionary _slotByField = new (StringComparer.Ordinal); + Dictionary> _sources = new (StringComparer.Ordinal); + HashSet _valueFromSources = new (StringComparer.Ordinal); + Dictionary _valueRank = new (StringComparer.Ordinal); + Dictionary _slotByField = new (StringComparer.Ordinal); // Items of a second meta (moov/meta beside udta/meta), in file order. Null marks one a set // dropped. A field whose value came from it is written back there when set: QTFF gives // metadata precedence over user data that declares the same information. - readonly List _movieItems = new (); - readonly HashSet _movieFields = new (StringComparer.Ordinal); - readonly Dictionary _movieSlotByField = new (StringComparer.Ordinal); - readonly Dictionary _movieKeyIndexByField = new (StringComparer.Ordinal); + List _movieItems = new (); + HashSet _movieFields = new (StringComparer.Ordinal); + Dictionary _movieSlotByField = new (StringComparer.Ordinal); + Dictionary _movieKeyIndexByField = new (StringComparer.Ordinal); Mp4QuickTimeKeys? _movieKeys; bool _hasMovieMeta; + /// + /// Creates an empty tag. + /// + public Mp4Tag () + { + _atoms = new OrderedMap> (StringComparer.Ordinal, 0, _places); + _freeform = new OrderedMap (StringComparer.Ordinal, 0, _places); + } + /// public override TagTypes TagType => TagTypes.Apple; @@ -759,10 +774,16 @@ public override IPicture[] Pictures { _pictures.Add (new Mp4Picture (pic.MimeType, pic.PictureType, pic.Description, pic.PictureData)); } } + + PicturesChanged (); } } #pragma warning restore CA1819 + // The cover art keeps its place while the tag has pictures; pictures set on a tag with none go last. + void PicturesChanged () => + _picturesPlace = _pictures.Count == 0 ? -1 : _picturesPlace >= 0 ? _picturesPlace : _places.Next (); + string? GetGnreName () { var code = GetInteger (Mp4AtomMapping.GenreId3); @@ -913,22 +934,17 @@ internal void SetFreeform (string mean, string name, string? value) internal void SetFreeformAtoms (string mean, string name, List dataAtoms) { - var key = (mean, name); - if (_freeformByKey.TryGetValue (key, out var existing)) { - _freeform.Remove (existing); - _freeformByKey.Remove (key); - } - DropPreservedFreeform (mean, name); DropFreeformTwins (mean, name); + var id = FreeformId (mean, name); if (dataAtoms is null || dataAtoms.Count == 0) - return; - - _freeformByKey.Add (key, _freeform.AddLast (new FreeformField (mean, name, dataAtoms))); + _freeform.Remove (id); + else + _freeform.Set (id, new FreeformField (mean, name, dataAtoms)); } FreeformField? FindFreeform (string mean, string name) => - _freeformByKey.TryGetValue ((mean, name), out var node) ? node.Value : null; + _freeform.TryGetValue (FreeformId (mean, name), out var field) ? field : null; void RemoveAtom (string atomId) { @@ -936,6 +952,36 @@ void RemoveAtom (string atomId) DropPreserved (atomId); } + /// + /// Takes the state of , a tag read from the file a save just wrote over the source, so this + /// object goes on as a fresh read of that file does (#252): the same items in the same places, the same keys and key + /// indexes, the same sources and slots, and the same metas. Every field of the tag is state, and every one is taken. + /// + internal void AdoptStateOf (Mp4Tag other) + { + _places = other._places; + _atoms = other._atoms; + _pictures = other._pictures; + _picturesPlace = other._picturesPlace; + _freeform = other._freeform; + _preservedAtoms = other._preservedAtoms; + _preservedByType = other._preservedByType; + _preservedFreeformByKey = other._preservedFreeformByKey; + _keys = other._keys; + _cleared = other._cleared; + _keyIndexByField = other._keyIndexByField; + _sources = other._sources; + _valueFromSources = other._valueFromSources; + _valueRank = other._valueRank; + _slotByField = other._slotByField; + _movieItems = other._movieItems; + _movieFields = other._movieFields; + _movieSlotByField = other._movieSlotByField; + _movieKeyIndexByField = other._movieKeyIndexByField; + _movieKeys = other._movieKeys; + _hasMovieMeta = other._hasMovieMeta; + } + /// public override bool SupportsCustomFields => true; @@ -1019,8 +1065,8 @@ public override void Clear () _cleared = true; _atoms.Clear (); _pictures.Clear (); + _picturesPlace = -1; _freeform.Clear (); - _freeformByKey.Clear (); _preservedAtoms.Clear (); _preservedByType.Clear (); _preservedFreeformByKey.Clear (); @@ -1050,8 +1096,8 @@ internal void ClearMappedFields () _atoms.Clear (); _pictures.Clear (); + _picturesPlace = -1; _freeform.Clear (); - _freeformByKey.Clear (); for (var i = 0; i < _preservedAtoms.Count; i++) { if (_preservedAtoms[i] is { } kept && IsMappedType (kept.Box.Span)) _preservedAtoms[i] = null; @@ -1126,20 +1172,31 @@ public override BinaryData Render () if (_keys is not null) return RenderKeyed (_keys); - using var builder = new BinaryDataBuilder (); - - // A field whose value still comes from kept items is not written here. A field set after it - // was read from a second meta is written both there and here, so every reader shows it. + // Every item in its place (#252). A field whose value still comes from kept items is not written here. A field + // set after it was read from a second meta is written both there and here, so every reader shows it. + var items = new List<(long Place, BinaryData Box)> (); foreach (var field in ValuedFields ()) { if (!_valueFromSources.Contains (field.Id)) - builder.Add (field.Itunes ()); + items.Add ((field.Place, field.Itunes ())); } foreach (var preserved in _preservedAtoms) { if (preserved is not null) - builder.Add (preserved.Box); + items.Add ((preserved.Place, preserved.Box)); } + // A kept item that holds a field's earlier value shares that field's place; the field is not written then. + var order = new int[items.Count]; + for (var i = 0; i < order.Length; i++) + order[i] = i; + Array.Sort (order, (x, y) => { + var byPlace = items[x].Place.CompareTo (items[y].Place); + return byPlace != 0 ? byPlace : x.CompareTo (y); + }); + + using var builder = new BinaryDataBuilder (); + foreach (var i in order) + builder.Add (items[i].Box); return builder.ToBinaryData (); } @@ -1201,7 +1258,7 @@ internal void AddSourceAtom (string atomId, List? value, BinaryData if (!AddSource (atomId, box, keyIndex, movie) || value is null || value.Count == 0 || !TakesValue (atomId, _atoms.ContainsKey (atomId), rank)) return; - _atoms[atomId] = value; + _atoms.Set (atomId, value); TookValue (atomId, rank, movie); } @@ -1211,12 +1268,7 @@ internal void AddSourceFreeform (string mean, string name, List? va if (!AddSource (id, box, keyIndex, movie) || value is null || value.Count == 0 || !TakesValue (id, FindFreeform (mean, name) is not null, rank)) return; - if (_freeformByKey.TryGetValue ((mean, name), out var existing)) { - _freeform.Remove (existing); - _freeformByKey.Remove ((mean, name)); - } - - _freeformByKey.Add ((mean, name), _freeform.AddLast (new FreeformField (mean, name, value))); + _freeform.Set (id, new FreeformField (mean, name, value)); TookValue (id, rank, movie); } @@ -1228,6 +1280,7 @@ internal void AddSourcePictures (Mp4Picture[]? value, BinaryData box, uint keyIn _pictures.Clear (); _pictures.AddRange (value); + PicturesChanged (); TookValue (id, rank, movie); } @@ -1292,21 +1345,20 @@ void TookValue (string fieldId, Mp4SourceRank rank, bool movie) void KeepCurrentValue (string fieldId) { - foreach (var field in ValuedFields ()) { - if (field.Id != fieldId) - continue; - - var index = PreserveIlstAtom (field.Itunes (), field.Field.Mean, field.Field.Name); - if (!_slotByField.ContainsKey (fieldId)) - _slotByField[fieldId] = index; - if (!_sources.TryGetValue (fieldId, out var list)) { - list = new List<(bool, int)> (); - _sources[fieldId] = list; - } - - list.Add ((false, index)); + // Found by its id: a read where a second meta overrides n fields stays linear in n (#252). + if (FindValuedField (fieldId) is not { } field) return; + + // The kept value stays where the field was. + var index = PreserveIlstAtom (field.Itunes (), field.Field.Mean, field.Field.Name, field.Place); + if (!_slotByField.ContainsKey (fieldId)) + _slotByField[fieldId] = index; + if (!_sources.TryGetValue (fieldId, out var list)) { + list = new List<(bool, int)> (); + _sources[fieldId] = list; } + + list.Add ((false, index)); } // A set or a removal replaces every item the field was read from. @@ -1333,28 +1385,48 @@ void DropSources (string fieldId) internal BinaryData RenderMovieIlst () => RenderOrdered (_movieItems, _movieKeys, _movieSlotByField, _movieKeyIndexByField, movie: true); - // Every field that has a value, with its iTunes form and its keyed form. - IEnumerable<(string Id, Mp4KeyedField Field, List Atoms, Func Itunes)> ValuedFields () + // Every field that has a value, with its place, its iTunes form and its keyed form, in place order (#252). + List ValuedFields () { - foreach (var kvp in _atoms) { - var (atomId, atoms) = (kvp.Key, kvp.Value); - yield return (atomId, Mp4KeyedField.Atom (atomId), atoms, () => Rendered (b => RenderStandardAtom (b, atomId, atoms))); - } + var fields = new List (_atoms.Count + _freeform.Count + 1); + foreach (var (atomId, atoms, place) in _atoms.Placed ()) + fields.Add (AtomField (atomId, atoms, place)); + foreach (var (id, f, place) in _freeform.Placed ()) + fields.Add (FreeformValuedField (id, f, place)); + if (PicturesField () is { } pictures) + fields.Add (pictures); + fields.Sort (static (a, b) => a.Place.CompareTo (b.Place)); + return fields; + } + + // The field with the id fieldId, or null when it has no value: a lookup, not a walk. + ValuedField? FindValuedField (string fieldId) + { + if (fieldId == Mp4AtomMapping.CoverArt) + return PicturesField (); + if (_freeform.TryGetValue (fieldId, out var f, out var place)) + return FreeformValuedField (fieldId, f, place); + return _atoms.TryGetValue (fieldId, out var atoms, out place) ? AtomField (fieldId, atoms, place) : null; + } - foreach (var field in _freeform) { - var f = field; - yield return (FreeformId (f.Mean, f.Name), Mp4KeyedField.Freeform (f.Mean, f.Name), f.Atoms, - () => Rendered (b => RenderFreeformAtom (b, f.Mean, f.Name, f.Atoms))); - } + static ValuedField AtomField (string atomId, List atoms, long place) => + new (atomId, Mp4KeyedField.Atom (atomId), atoms, place, () => Rendered (b => RenderStandardAtom (b, atomId, atoms))); - if (_pictures.Count > 0) { - var covers = new List (_pictures.Count); - foreach (var picture in _pictures) - covers.Add (new Mp4DataAtom (picture.RenderTypeIndicator, picture.PictureData, picture.RenderLocale)); - yield return (Mp4AtomMapping.CoverArt, Mp4KeyedField.Artwork (), covers, () => Rendered (RenderPictures)); - } + static ValuedField FreeformValuedField (string id, FreeformField f, long place) => + new (id, Mp4KeyedField.Freeform (f.Mean, f.Name), f.Atoms, place, () => Rendered (b => RenderFreeformAtom (b, f.Mean, f.Name, f.Atoms))); + + ValuedField? PicturesField () + { + if (_pictures.Count == 0) + return null; + var covers = new List (_pictures.Count); + foreach (var picture in _pictures) + covers.Add (new Mp4DataAtom (picture.RenderTypeIndicator, picture.PictureData, picture.RenderLocale)); + return new ValuedField (Mp4AtomMapping.CoverArt, Mp4KeyedField.Artwork (), covers, _picturesPlace, () => Rendered (RenderPictures)); } + readonly record struct ValuedField (string Id, Mp4KeyedField Field, List Atoms, long Place, Func Itunes); + static BinaryData Rendered (Action render) { using var builder = new BinaryDataBuilder (); @@ -1577,17 +1649,17 @@ internal void SetAtoms (string atomId, List dataAtoms) } DropPreserved (atomId); - _atoms[atomId] = dataAtoms; + _atoms.Set (atomId, dataAtoms); } - internal int PreserveIlstAtom (BinaryData box, string? mean = null, string? name = null) + internal int PreserveIlstAtom (BinaryData box, string? mean = null, string? name = null, long? place = null) { if (box.IsEmpty) return -1; var typeKey = TypeKey (box.Span); var index = _preservedAtoms.Count; - _preservedAtoms.Add (new PreservedBox (box)); + _preservedAtoms.Add (new PreservedBox (box, place ?? _places.Next ())); if (!_preservedByType.TryGetValue (typeKey, out var indexes)) { indexes = new List (); _preservedByType.Add (typeKey, indexes); @@ -1674,13 +1746,17 @@ public FreeformField (string mean, string name, List atoms) public List Atoms { get; } } + // A kept ilst item and its place among the items a save writes (#252). sealed class PreservedBox { - public PreservedBox (BinaryData box) + public PreservedBox (BinaryData box, long place) { Box = box; + Place = place; } public BinaryData Box { get; } + + public long Place { get; } } } diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterSaveStreamsTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterSaveStreamsTests.cs index cfbda950..53281519 100644 --- a/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterSaveStreamsTests.cs +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4ChapterSaveStreamsTests.cs @@ -96,7 +96,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179, #252). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4IlstItemOrderTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4IlstItemOrderTests.cs new file mode 100644 index 00000000..9f8b311f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4IlstItemOrderTests.cs @@ -0,0 +1,496 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// An MP4 ilst keeps its items in the order they were read (#252): a save with no edit writes them as they were, a +/// changed field stays in its item's place, and a new field goes after the others, in the order added. Standard atoms, +/// freeform (----) atoms, cover art and atoms the tag does not map share one order. So a save from the object +/// that saved before and a save from a fresh read of that save write the same bytes. QTFF sets no order for ilst items. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +public class Mp4IlstItemOrderTests +{ + const int Utf8 = 1; + static readonly byte[] Jpeg = [0xFF, 0xD8, 0xFF, 0xD9]; + + // An iTunes ilst whose kinds interleave: a standard atom, cover art, a freeform atom, an atom the tag does not map + // ("orch"), and more standard atoms. + static byte[] Itunes () => TestBuilders.Mp4.CreateWithIlstAtoms ( + TestBuilders.Mp4.CreateIlstChild ("©nam", Utf8, "Title"u8.ToArray ()), + TestBuilders.Mp4.CreateCovrAtom (Jpeg, 13), + TestBuilders.Mp4.CreateIlstChild ("©ART", Utf8, "Artist"u8.ToArray ()), + TestBuilders.Mp4.CreateFreeformAtom ("com.apple.iTunes", "MOOD", "Calm"), + TestBuilders.Mp4.CreateIlstChild ("orch", Utf8, "kept"u8.ToArray ()), + TestBuilders.Mp4.CreateIlstChild ("©alb", Utf8, "Album"u8.ToArray ()), + TestBuilders.Mp4.CreateIlstChild ("©gen", Utf8, "Genre"u8.ToArray ()), + TestBuilders.Mp4.CreateIlstChild ("©cmt", Utf8, "Comment"u8.ToArray ())); + + // A QuickTime "mdta" meta, as ffmpeg writes it with -movflags use_metadata_tags. + static byte[] Mdta () => TestBuilders.Mp4.CreateWithMdtaIlst ( + ["title", "artist", "album", "genre", "comment"], + TestBuilders.Mp4.CreateMdtaItem (1, "Title"), + TestBuilders.Mp4.CreateMdtaItem (2, "Artist"), + TestBuilders.Mp4.CreateMdtaItem (3, "Album"), + TestBuilders.Mp4.CreateMdtaItem (4, "Genre"), + TestBuilders.Mp4.CreateMdtaItem (5, "Comment")); + + // A QuickTime moov/meta with keys beside an iTunes udta/meta, as Apple software leaves an ffmpeg file: both metas + // are written, so both keep their order. + static byte[] BothMetas () => TestBuilders.Mp4.CreateWithKeyedMeta ("mdta", + TestBuilders.Mp4.KeysPayload ("com.apple.quicktime.title", "com.apple.quicktime.artist", "com.apple.quicktime.genre"), + [TestBuilders.Mp4.CreateMdtaItem (1, "Movie title"), TestBuilders.Mp4.CreateMdtaItem (2, "Artist"), TestBuilders.Mp4.CreateMdtaItem (3, "Genre")], + inMovie: true, + udtaExtra: TestBuilders.Mp4.CreateBox ("meta", [ + 0, 0, 0, 0, + .. TestBuilders.Mp4.CreateBox ("hdlr", [0, 0, 0, 0, 0, 0, 0, 0, .. "mdirappl"u8, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + .. TestBuilders.Mp4.CreateBox ("ilst", [ + .. TestBuilders.Mp4.CreateIlstChild ("©nam", Utf8, "Title"u8.ToArray ()), + .. TestBuilders.Mp4.CreateIlstChild ("©alb", Utf8, "Album"u8.ToArray ()), + .. TestBuilders.Mp4.CreateIlstChild ("©cmt", Utf8, "Comment"u8.ToArray ())])])); + + static readonly string[] Layouts = ["itunes", "mdta", "both"]; + + static byte[] Build (string layout) => layout switch { + "itunes" => Itunes (), + "mdta" => Mdta (), + _ => BothMetas () + }; + + static readonly (string Name, Action Apply)[] Edits = [ + ("none", _ => { }), + ("set Title", t => t.Title = "New title"), + ("remove Title", t => t.Title = null), + ("remove Genre", t => t.Genre = null), + ("add Composer", t => t.Composer = "Composer"), + ("add Year", t => t.Year = "2001"), + ("add custom", t => t.SetCustomField ("NEWFIELD", "x")), + ("set custom MOOD", t => t.SetCustomField ("MOOD", "Loud")), + ("remove custom MOOD", t => t.RemoveCustomField ("MOOD")), + ("set pictures", t => t.Pictures = [new Mp4Picture ("image/png", PictureType.FrontCover, "", new BinaryData ([0x89, 0x50, 0x4E, 0x47]))]), + ("remove pictures", t => t.Pictures = []), + ("remove two, add three", t => { t.Title = null; t.Genre = null; t.Composer = "C"; t.Year = "2001"; t.Conductor = "D"; }), + ]; + + public static IEnumerable EditPairs => + from layout in Layouts + from first in Enumerable.Range (0, Edits.Length) + from second in Enumerable.Range (0, Edits.Length) + select new object[] { layout, first, second }; + + /// + /// {iTunes ilst, mdta meta, mdta moov/meta beside an iTunes udta/meta} x {first edit} x {second edit}: the object that saved the first edit over its source + /// saves the second as a fresh read of that file does. + /// + [TestMethod] + [DynamicData (nameof (EditPairs))] + public void SaveAfterSave_IsTheFreshReadsSave (string layout, int first, int second) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Build (layout)); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + Edits[first].Apply (((IMediaFile)file).Tag!); + Save (file, files); + var fresh = new MockFileSystem (); + fresh.AddFile ("/f.m4a", files.ReadAllBytes ("/f.m4a")); + + Edits[second].Apply (((IMediaFile)file).Tag!); + Save (file, files); + var reread = Mp4File.ReadFromFile ("/f.m4a", fresh).File!; + Edits[second].Apply (((IMediaFile)reread).Tag!); + Save (reread, fresh); + + var cell = $"{layout}: {Edits[first].Name}, then {Edits[second].Name}"; + CollectionAssert.AreEqual (Items (fresh.ReadAllBytes ("/f.m4a")), Items (files.ReadAllBytes ("/f.m4a")), cell); + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f.m4a"), files.ReadAllBytes ("/f.m4a"), cell); + } + + static readonly string[] SaveEntries = ["path", "async-path", "span", "async-span"]; + + public static IEnumerable EntryCases => + from layout in Layouts + from entry in SaveEntries + select new object[] { layout, entry }; + + /// + /// The removal saved over the source, then the field set again, on every save entry point: the object forgets the + /// removed field once the file no longer holds it, as a fresh read does. A save to another path does not. + /// + [TestMethod] + [DynamicData (nameof (EntryCases))] + public void RemoveSaveSetAgain_OnEverySaveEntryPoint_IsTheFreshReadsSave (string layout, string entry) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Build (layout)); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + ((IMediaFile)file).Tag!.Title = null; + SaveOn (entry, file, files, "/f.m4a"); + var fresh = new MockFileSystem (); + fresh.AddFile ("/f.m4a", files.ReadAllBytes ("/f.m4a")); + + ((IMediaFile)file).Tag!.Title = "Again"; + SaveOn (entry, file, files, "/f.m4a"); + var reread = Mp4File.ReadFromFile ("/f.m4a", fresh).File!; + ((IMediaFile)reread).Tag!.Title = "Again"; + SaveOn (entry, reread, fresh, "/f.m4a"); + + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f.m4a"), files.ReadAllBytes ("/f.m4a"), $"{layout}, {entry}"); + } + + /// A clear saved to another path leaves the source as it was, so the object still sets the field where it was read. + [TestMethod] + [DataRow ("mdta")] + [DataRow ("both")] + public void RemoveSavedElsewhere_SetAgain_GoesBackWhereItWasRead (string layout) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Build (layout)); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + ((IMediaFile)file).Tag!.Title = null; + SaveOn ("path", file, files, "/other.m4a"); + + ((IMediaFile)file).Tag!.Title = "Again"; + SaveOn ("path", file, files, "/other.m4a"); + + var unsaved = Mp4File.ReadFromFile ("/f.m4a", files).File!; + ((IMediaFile)unsaved).Tag!.Title = null; + ((IMediaFile)unsaved).Tag!.Title = "Again"; + SaveOn ("path", unsaved, files, "/expected.m4a"); + CollectionAssert.AreEqual (files.ReadAllBytes ("/expected.m4a"), files.ReadAllBytes ("/other.m4a"), layout); + } + + static void SaveOn (string entry, Mp4File file, MockFileSystem files, string path) + { + var source = files.ReadAllBytes (file.SourcePath!); + var result = entry switch { + "path" => file.SaveToFile (path, files), + "async-path" => file.SaveToFileAsync (path, files).GetAwaiter ().GetResult (), + "span" => file.SaveToFile (path, source, files), + _ => file.SaveToFileAsync (path, source, files).GetAwaiter ().GetResult (), + }; + Assert.IsTrue (result.IsSuccess, $"{entry}: {result.Error}"); + } + + /// A save with no edit writes the ilst as it was read, every kind in its place. + [TestMethod] + [DataRow ("itunes")] + [DataRow ("mdta")] + [DataRow ("both")] + public void NoEditSave_KeepsTheItemsInTheirOrder (string layout) + { + var original = Build (layout); + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", original); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + ((IMediaFile)file).Tag!.Title = ((IMediaFile)file).Tag!.Title; + + Save (file, files); + + CollectionAssert.AreEqual (Items (original), Items (files.ReadAllBytes ("/f.m4a")), layout); + } + + /// Where each edit puts the items of the iTunes ilst: a set field stays in its place, a new one goes last. + [TestMethod] + [DataRow ("set Title", new[] { "©nam", "covr", "©ART", "----:MOOD", "orch", "©alb", "©gen", "©cmt" })] + [DataRow ("set custom MOOD", new[] { "©nam", "covr", "©ART", "----:MOOD", "orch", "©alb", "©gen", "©cmt" })] + [DataRow ("set pictures", new[] { "©nam", "covr", "©ART", "----:MOOD", "orch", "©alb", "©gen", "©cmt" })] + [DataRow ("remove two, add three", new[] { "covr", "©ART", "----:MOOD", "orch", "©alb", "©cmt", "©wrt", "©day", "----:CONDUCTOR" })] + public void Edit_PutsItemsWhereTheRuleSays (string edit, string[] expected) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Itunes ()); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + + Edits.Single (e => e.Name == edit).Apply (((IMediaFile)file).Tag!); + Save (file, files); + + CollectionAssert.AreEqual (expected, Items (files.ReadAllBytes ("/f.m4a")), edit); + } + + /// Reading n items, removing half, adding one and rendering allocates linearly in n. + [TestMethod] + public void EditAndRender_AllocateLinearlyInTheItemCount () + { + Kit.Bounds.AssertLinearAllocation ( + n => TestBuilders.Mp4.CreateWithIlstAtoms ([.. Enumerable.Range (0, n).Select (i => TestBuilders.Mp4.CreateFreeformAtom ("com.apple.iTunes", $"K{i:D6}", "v"))]), + bytes => { + var tag = Mp4File.Read (bytes).File!.Tag!; + for (var i = 0; i < 2000; i += 2) + tag.RemoveCustomField ($"K{i:D6}"); + tag.SetCustomField ("NEW", "x"); + _ = tag.Render (); + }, + 2000); + } + + /// + /// A read where a second meta overrides n freeform fields of the first allocates linearly in n (#252, review 1 B1): + /// the field each override keeps is found by its id, not by a walk over every field. In both orders. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Read_SecondMetaOverridingEveryField_AllocatesLinearly (bool reverse) + { + Kit.Bounds.AssertLinearAllocation ( + n => OverriddenFreeform (n, reverse), + bytes => _ = Mp4File.Read (bytes).File!.Tag!.Title, + 500); + } + + // udta/meta (iTunes) with n freeform fields, and a keyed moov/meta holding a freeform atom for each of them. + static byte[] OverriddenFreeform (int n, bool reverse) + { + var names = Enumerable.Range (0, n).Select (i => $"F{i:D6}").ToArray (); + var movie = (reverse ? Enumerable.Reverse (names) : names).Select (name => TestBuilders.Mp4.CreateFreeformAtom ("com.apple.iTunes", name, "movie")).ToArray (); + return TestBuilders.Mp4.CreateWithKeyedMeta ("mdta", TestBuilders.Mp4.KeysPayload ("com.apple.quicktime.title"), movie, + inMovie: true, + udtaExtra: TestBuilders.Mp4.CreateBox ("meta", [ + 0, 0, 0, 0, + .. TestBuilders.Mp4.CreateBox ("hdlr", [0, 0, 0, 0, 0, 0, 0, 0, .. "mdirappl"u8, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + .. TestBuilders.Mp4.CreateBox ("ilst", [.. names.SelectMany (name => TestBuilders.Mp4.CreateFreeformAtom ("com.apple.iTunes", name, "udta"))])])); + } + + static readonly string[] RandomEdits = [ + "title=null", "title=T2", "genre=null", "genre=G2", "artist=null", "artist=A2", "cmt=null", "cmt=C2", + "composer=A", "composer=B", "composer=null", "year=2001", "year=null", "custom=X", "custom=null", + "pic", "pics", "nopic", "clear", "noop", "assign"]; + + static readonly string[] RandomLayouts = ["itunes", "mdta", "both", "movie"]; + + public static IEnumerable RandomCases => + from layout in RandomLayouts + from seed in Enumerable.Range (0, 60) + select new object[] { layout, seed }; + + /// + /// Random sequences of up to three saves over the source, each after one to three edits, through a random one of the + /// six save entry points, against a fresh read of the file before each step (review 1 B2; the reviewer's exhaustive + /// two-step matrix runs offline). Every save of the object writes what the fresh read's save writes. + /// + [TestMethod] + [DynamicData (nameof (RandomCases))] + public void RandomSequence_EverySaveIsTheFreshReadsSave (string layout, int seed) + { + var rng = new Random (seed * 7919 + layout.Length); + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", layout == "movie" ? MovieMeta () : Build (layout)); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + var log = new List (); + for (var step = 0; step < 3; step++) { + var fresh = new MockFileSystem (); + fresh.AddFile ("/f.m4a", files.ReadAllBytes ("/f.m4a")); + var reread = Mp4File.ReadFromFile ("/f.m4a", fresh).File!; + var edits = Enumerable.Range (0, 1 + rng.Next (3)).Select (_ => RandomEdits[rng.Next (RandomEdits.Length)]).ToArray (); + var entry = SaveEntries[rng.Next (SaveEntries.Length)]; + log.Add ($"[{string.Join (",", edits)}] {entry}"); + foreach (var edit in edits) { + ApplyRandom (file, edit); + ApplyRandom (reread, edit); + } + + SaveOn (entry, file, files, "/f.m4a"); + SaveOn ("path", reread, fresh, "/f.m4a"); + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f.m4a"), files.ReadAllBytes ("/f.m4a"), $"{layout} seed {seed}: {string.Join (" SAVE ", log)}"); + } + } + + static readonly BinaryData Png = new ([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D]); + + static void ApplyRandom (Mp4File file, string edit) + { + var tag = ((IMediaFile)file).Tag!; + switch (edit) { + case "noop": break; + case "clear": tag.Clear (); break; + case "pic": tag.Pictures = [new Mp4Picture ("image/png", PictureType.FrontCover, "", Png)]; break; + case "pics": tag.Pictures = [new Mp4Picture ("image/png", PictureType.BackCover, "", Png), new Mp4Picture ("image/jpeg", PictureType.FrontCover, "", new BinaryData (Jpeg))]; break; + case "nopic": tag.Pictures = []; break; + case "custom=X": tag.SetCustomField ("CUSTOM", "X"); break; + case "custom=null": tag.RemoveCustomField ("CUSTOM"); break; + // A tag assigned in place of the one read (its mapped fields replace the file's). + case "assign": file.Tag = new Mp4Tag { Title = "Assigned", Comment = "C" }; break; + default: + var value = edit[(edit.IndexOf ('=') + 1)..] is "null" ? null : edit[(edit.IndexOf ('=') + 1)..]; + switch (edit[..edit.IndexOf ('=')]) { + case "title": tag.Title = value; break; + case "genre": tag.Genre = value; break; + case "artist": tag.Artist = value; break; + case "cmt": tag.Comment = value; break; + case "composer": tag.Composer = value; break; + default: tag.Year = value; break; + } + + break; + } + } + + // A keyed meta in moov/meta and no udta/meta, as QuickTime writes it (qt-artwork.mov, review 1 N2). + static byte[] MovieMeta () => TestBuilders.Mp4.CreateWithKeyedMeta ("mdta", + TestBuilders.Mp4.KeysPayload ("com.apple.quicktime.title", "com.apple.quicktime.artist"), + [TestBuilders.Mp4.CreateMdtaItem (1, "Movie title"), TestBuilders.Mp4.CreateMdtaItem (2, "Artist")], + inMovie: true, udtaExtra: null); + + /// + /// A save over the source is recognised by what the source holds, not by the path string or the file system object + /// (review 1 N1, #179's rule): the path spelled with a "." segment, and the default file system passed explicitly + /// after a read with none. Then a removed field set again writes what a fresh read writes. + /// + [TestMethod] + [DataRow ("mdta", "dot")] + [DataRow ("mdta", "default-fs")] + [DataRow ("both", "dot")] + [DataRow ("both", "default-fs")] + public void SaveOverTheSource_UnderAnySpelling_IsTheFreshReadsSave (string layout, string spelling) + { + var dir = Path.Combine (Path.GetTempPath (), "tls2-adopt-" + Guid.NewGuid ().ToString ("N")); + Directory.CreateDirectory (dir); + try { + var path = Path.Combine (dir, "a.m4a"); + File.WriteAllBytes (path, Build (layout)); + var file = Mp4File.ReadFromFile (path).File!; + ((IMediaFile)file).Tag!.Artist = null; + var first = spelling == "dot" + ? file.SaveToFile (Path.Combine (dir, ".", "a.m4a")) + : file.SaveToFile (path, DefaultFileSystem.Instance); + Assert.IsTrue (first.IsSuccess, first.Error); + var freshPath = Path.Combine (dir, "b.m4a"); + File.Copy (path, freshPath); + + ((IMediaFile)file).Tag!.Artist = "Again"; + Assert.IsTrue (file.SaveToFile ().IsSuccess); + var fresh = Mp4File.ReadFromFile (freshPath).File!; + ((IMediaFile)fresh).Tag!.Artist = "Again"; + Assert.IsTrue (fresh.SaveToFile ().IsSuccess); + + CollectionAssert.AreEqual (File.ReadAllBytes (freshPath), File.ReadAllBytes (path), $"{layout}, {spelling}"); + } finally { + Directory.Delete (dir, recursive: true); + } + } + + /// + /// Clear and an assigned tag start the cover art's place again (review 1 N5): pictures set after them go after the + /// fields set before them, as in the order given. + /// + [TestMethod] + [DataRow ("clear")] + [DataRow ("assign")] + public void ClearOrAssign_PicturesSetAfterATitleGoAfterIt (string how) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Itunes ()); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + var picture = new Mp4Picture ("image/png", PictureType.FrontCover, "", Png); + if (how == "clear") { + file.Tag!.Clear (); + file.Tag.Title = "First"; + file.Tag.Pictures = [picture]; + } else { + var assigned = new Mp4Tag { Title = "First" }; + assigned.Pictures = [picture]; + file.Tag = assigned; + } + + Save (file, files); + + var items = Items (files.ReadAllBytes ("/f.m4a")); + Assert.IsLessThan (Array.IndexOf (items, "covr"), Array.IndexOf (items, "©nam"), $"{how}: {string.Join (",", items)}"); + } + + /// + /// The tag the file read keeps its identity across a save over the source, so a reference taken before the save + /// still edits the file (the state is adopted into it, not swapped for a new object). + /// + [TestMethod] + [DataRow ("itunes")] + [DataRow ("both")] + public void SaveOverTheSource_KeepsTheReadTagLive (string layout) + { + var files = new MockFileSystem (); + files.AddFile ("/f.m4a", Build (layout)); + var file = Mp4File.ReadFromFile ("/f.m4a", files).File!; + var tag = file.Tag!; + tag.Title = "One"; + Save (file, files); + + tag.Title = "Two"; + Save (file, files); + + Assert.AreSame (tag, file.Tag, layout); + Assert.AreEqual ("Two", Mp4File.Read (files.ReadAllBytes ("/f.m4a")).File!.Tag!.Title, layout); + } + + /// + /// AdoptStateOf takes every field of the tag read back (review 1 B2): a state field added later and not adopted + /// would leave the object describing the file before the save. + /// + [TestMethod] + public void AdoptStateOf_TakesEveryField () + { + var target = Mp4File.Read (Mdta ()).File!.Tag!; + var source = Mp4File.Read (BothMetas ()).File!.Tag!; + + target.AdoptStateOf (source); + + foreach (var field in typeof (Mp4Tag).GetFields (System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)) { + var mine = field.GetValue (target); + var theirs = field.GetValue (source); + Assert.IsTrue (field.FieldType.IsValueType ? Equals (mine, theirs) : ReferenceEquals (mine, theirs), field.Name); + } + } + + static void Save (Mp4File file, MockFileSystem files) + { + var result = file.SaveToFile (files); + Assert.IsTrue (result.IsSuccess, result.Error); + } + + /// The children of the file's moov/udta/meta/ilst, as their type, and "----:name" for a freeform atom. + static string[] Items (byte[] file) + { + var ilst = Find (file, 0, file.Length, ["moov", "udta", "meta", "ilst"]); + var items = new List (); + for (var pos = ilst.Start; pos + 8 <= ilst.End;) { + var size = (int)BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (pos)); + var type = Encoding.Latin1.GetString (file, pos + 4, 4); + if (type == "----") { + var name = Find (file, pos + 8, pos + size, ["name"]); + type += ":" + Encoding.UTF8.GetString (file, name.Start + 4, name.End - name.Start - 4); + } else if (type[0] == '\0') { + type = "key" + BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (pos + 4)); + } + + items.Add (type); + pos += size; + } + + return [.. items]; + } + + static (int Start, int End) Find (byte[] file, int start, int end, string[] path) + { + for (var pos = start; pos + 8 <= end;) { + var size = (int)BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (pos)); + var type = Encoding.Latin1.GetString (file, pos + 4, 4); + if (type == path[0]) { + // udta/meta is a full atom (version and flags before its children); moov/meta is not. + var content = pos + 8 + (type == "meta" && Encoding.Latin1.GetString (file, pos + 16, 4) == "hdlr" ? 4 : 0); + return path.Length == 1 ? (content, pos + size) : Find (file, content, pos + size, path[1..]); + } + + pos += size; + } + + throw new AssertFailedException ("no " + string.Join ("/", path)); + } +} diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4SaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4SaveStreamsAudioTests.cs index a486f279..1fa22a00 100644 --- a/tests/TagLibSharp2.Tests/Mp4/Mp4SaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4SaveStreamsAudioTests.cs @@ -78,7 +78,8 @@ static void AssertSaved ( long allocated) { Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (#179, #252). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); From d035cb96088bf12184ddbcba4faabd6151da1c36 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 08:36:02 -0700 Subject: [PATCH 09/12] fix: Keep an ASF file's File Size true after a save that changes its length (#253) Cause: an ASF save rebuilds the header and copies the File Properties Object unchanged, so a save that grew or shrank the header left File Size, "the size, in bytes, of the entire file" (ASF Specification 01.20.03, File Properties Object), at the old length: an ffmpeg WMA of 10,332 bytes given a 4,000-character title read 10,332 at 18,314. AsfFile.FileProperties (#250) then kept the old value too. Fix: the header rebuild (RenderRebuiltHeader, shared by Render, the span saves and the path save that copies from the source) writes the File Size into every File Properties Object of the rebuilt header that holds a whole one (AsfFileProperties.SavedFileSize). The value comes from the object, not from the bytes the payload is copied from: a save whose length differs from the file the object describes (the one it read, or after a save the one it wrote) writes the length it writes; a save that keeps that length writes the object's File Size, so a save with no edit leaves the field as it was, even where another tagger left it stale (both WMA files in the TagLib# test set declare a size smaller than the file). While the Broadcast Flag is set the specification calls the field invalid, and the bytes stay as they are. The specification allows one File Properties Object; in a header with more the File Size goes into the last, the one the read takes and FileProperties gives, and the others stay as stored, so a save with no edit is byte for byte (review 2; a first version wrote it into each, review 1 N4). After a successful save over the source (SavedOverSource.Holds on the length and the header written) the object describes the file it wrote: its length, and FileProperties as that save wrote it (WithFileSize). A save to another path, or one from an object read from bytes, leaves the source described, as a fresh read of it given the same edits describes it (contract suite round 3, R3: a save elsewhere then made the next one write another File Size than a fresh read); until a save over the source the length described is the one the read saw (SourceLength.First), whichever bytes a span save copies. A failed save changes neither. A first version patched only the first File Properties Object and decided from the copied bytes, so an object read from bytes with a stale File Size wrote the stale value back after a grow and a revert. Sweep: the rest of the header holds nothing a length change moves. The Header Object's size and object count are written fresh, nothing records where the Data Object starts, and Data Packets Count and the Play and Send Durations describe the packets, which are copied. Index entries count packets from the Data Object, not file offsets (from the specification as read, not re-checked). Siblings, by a growing title save of an ffmpeg file: the WAV and AVI RIFF size, the AIFF FORM size and the Matroska Segment size all equal the written length. Tests: AsfFileSizeTests. Save_FileSizeIsTheLengthWritten over {grow, shrink, no edit} x {span, async span, path, async path, no-path, async no-path, path and async path after a stream read}: File Size is the written length, a no-edit save is byte for byte, and FileProperties matches a fresh read; SaveAfterSave_IsTheFreshReadsSave; Save_FileSizeThatWasNotTheLength (broadcast, 0, larger, smaller; with and without a length change); GrowThenRevert_FromBytesWithAStaleFileSize_IsTheFreshReadsSave (path, span, and span from the bytes the first save wrote; its oracle is now the contract suite's, a fresh read of the bytes read given both edits, where review 1 N4 took the file the first save wrote); AsfSaveElsewhereTests over {titled, bare} x every ordered pair of {Title = null, custom field, title, Clear}, saved twice to another path; TwoFilePropertiesObjects_TheLastHoldsTheLengthWritten (a no-edit save is byte for byte); ShortFilePropertiesObject_IsNotWrittenInto (pins the whole-object check); FailedSave_LeavesTheFileProperties (pins IsSuccess). AsfHeaderObjectsSaveTests' CountShortOrLong_SaveCarriesEveryObject compared the File Properties Object byte for byte; it now expects its File Size to be the written length. Black box: sample.wma given a long title reads File Size = length in exiftool, ffprobe and MediaInfo read it, and ffmpeg decodes it. A no-edit save of the two corpus WMAs moved the description objects to the end of the header (a pre-existing bug, commit does not claim it. Red: 37 of 92 rows (AsfFileSizeTests and AsfHeaderObjectsSaveTests) failed on main; of the round-2 tests, 3 failed at the round-1 head. Of AsfSaveElsewhereTests, 6 of 32 rows failed at the round-2 head (the File Size, offset 70). AsfSaveStreamsAudioTests now count two source length reads: the save reads the source back. Inverted on purpose: review 1 N4's oracle took an object read from bytes and saved to a path as describing the file it wrote; under the contract suite's C2 that is a save elsewhere, so the object still describes the bytes it read, and the test now says so. Left as they are (review 2 nit): a path-read object with a stale File Size that grows, saves elsewhere, reverts and saves over the source writes the true length, not the stale value, because the File Size is computed from the length written whenever it differs from the described file's; it is the true value. --- CHANGELOG.md | 1 + src/TagLibSharp2/Asf/AsfFile.cs | 94 +++++-- src/TagLibSharp2/Asf/AsfFileProperties.cs | 23 ++ src/TagLibSharp2/Core/SourceLength.cs | 6 + .../Asf/AsfFileSizeTests.cs | 262 ++++++++++++++++++ .../Asf/AsfHeaderObjectsSaveTests.cs | 5 +- .../Asf/AsfSaveElsewhereTests.cs | 46 +++ .../Asf/AsfSaveStreamsAudioTests.cs | 6 +- 8 files changed, 424 insertions(+), 19 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Asf/AsfFileSizeTests.cs create mode 100644 tests/TagLibSharp2.Tests/Asf/AsfSaveElsewhereTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index afc400f5..20ebb961 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An ASF save that changes the file's length keeps the File Properties Object's File Size, "the size, in bytes, of the entire file", true (#253). It was copied unchanged, so a 10,332-byte WMA given a long title read a File Size of 10,332 at 18,314 bytes. A save whose length differs from the file the object describes (the one it read, or the one it last saved over its source) now writes the length it writes, into the File Properties Object the read takes (the last, in a header holding more than the one the specification allows; any other stays as stored), on every save entry point, and after a save over the source `AsfFile.FileProperties` is the object the save wrote; a save to another path leaves the object describing its source. A save that keeps the length writes the object's File Size, so a save with no edit leaves the field as it was, even where another tagger left it stale (both WMA files in the TagLib# test set declare a size smaller than the file). A broadcast file's File Size, which the specification calls invalid, stays as it is - An MP4 ilst keeps its items in the order they were read, and a save after a save over the source writes what a fresh read of the saved file writes (#252). Standard atoms, freeform (`----`) fields, cover art and atoms the tag does not map share one order: a set field stays in its item's place and a new field goes after the others, in the order added. A save grouped them by kind and wrote the standard atoms in the order of a dictionary that reused a removed atom's slot, so a save with no edit reordered `sample.m4a`, `bgo_676934.m4a`, `bgo_701689.m4a`, `sample_replaygain.m4a` and `01 Horrible Theme.m4a` (it is now byte-identical). After a save over the source the object's tag takes the state a fresh read of the saved file has (its items, places, keys and key indexes, slots and metas), so the next save writes what that read's save writes in an iTunes `ilst`, a QuickTime `keys` meta, and a `moov/meta` beside `udta/meta` alike; the tag the object holds keeps its identity, whether the file read it, the caller assigned it or a view created it, and takes a new tag's state when the save wrote no `ilst`, so a reference to it stays live and a later edit through it is written. A save over the source is recognised as #179 recognises it, by what the file at `SourcePath` holds, under any spelling of the path or file system. A read where a second meta overrides n fields is linear in n again; it walked every field for each one. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read - A WAV or AVI INFO list keeps its fields in the order they were read (#251). A field added after a removal took the removed field's place, so after a save over the source a save from the same object and a save from a fresh read of that file, given the same edit, wrote the fields in different orders. A changed value now stays in its field's place and a new field goes after the others, in the order added, as for APE items (#238) - An AVI INFO list with a declared `CSET` saves a change its code page cannot hold next to a value whose code page is a guess (#220). The save was refused, naming the guessed field: a `CSET` of 932, 1251 or another code page this library does not decode, or a byte the declared code page leaves undefined (0x81 in 1252; 0x80-0x9F under code page 0). Copying a title read from such a field into another field failed. Under a code page this library does not decode, the save now drops the `CSET` and keeps every unchanged field's bytes, writing the change by the no-`CSET` read rule: this library already reads such a list by that rule, so every value reads back as it read, and the Shift-JIS or cp1251 bytes stay for a reader that decodes them. Under 1252 or code page 0 the list becomes UTF-8 under a `CSET` of 65001, as it already did next to text decoded exactly, and the guessed value is written as the UTF-8 of the text the reader returned. Both hold on every save entry point. Without the `CSET`, ExifTool reads a UTF-8 change as Latin-1 diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs index 6f9cb95f..9fbe21da 100644 --- a/src/TagLibSharp2/Asf/AsfFile.cs +++ b/src/TagLibSharp2/Asf/AsfFile.cs @@ -48,10 +48,16 @@ internal void MarkPicturesSkipped () /// /// /// takes its duration from this object, so - /// tells why a file still being written reads a duration of 0. A save copies the object unchanged, so after a save - /// over the source this is still the saved file's. + /// tells why a file still being written reads a duration of 0. A header with more than one (the specification allows + /// one) gives the last. A save copies the object and writes the length it wrote as its File Size when the length + /// changed (#253). After a successful save over the source this is the object that save wrote, as a fresh read of + /// the file shows it; after a save to another path it is still the source's, as the object still describes the source. /// - public AsfFileProperties? FileProperties { get; } + public AsfFileProperties? FileProperties { get; private set; } + + // The length of the file the object describes: -1 until a save over the source, when it is the length that save + // wrote (#253); until then it is the length the read saw. A save elsewhere leaves the source described. + long _describedLength = -1; /// /// Gets the source file path if the file was read from disk. @@ -520,8 +526,16 @@ static AudioProperties CreateAudioProperties (AsfFileProperties? fileProps, AsfS /// The original file data to preserve audio content from. /// /// The rendered file bytes, or empty when the header's objects do not fill it whole (#200). - public byte[] Render (ReadOnlySpan originalData) + public byte[] Render (ReadOnlySpan originalData) => Render (originalData, out _); + + byte[] Render (ReadOnlySpan originalData, out ulong? fileSize) => Render (originalData, out fileSize, out _); + + // headerLength is the length of the rebuilt header at the front of the bytes returned: 0 when the header did not parse. + byte[] Render (ReadOnlySpan originalData, out ulong? fileSize, out int headerLength) { + fileSize = null; + headerLength = 0; + // Parse original header to find structure var headerInfo = ParseHeaderStructure (originalData); if (!headerInfo.IsValid) @@ -529,7 +543,8 @@ public byte[] Render (ReadOnlySpan originalData) if (headerInfo.IsRefused) return []; - var newHeader = RenderRebuiltHeader (headerInfo); + var newHeader = RenderRebuiltHeader (headerInfo, originalData.Length, out fileSize); + headerLength = newHeader.Length; // Combine header with data object and remainder using var ms = new MemoryStream (); @@ -539,8 +554,9 @@ public byte[] Render (ReadOnlySpan originalData) return ms.ToArray (); } - // Same child objects Render writes. The bytes after HeaderEndOffset stay in the source file. - byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo) + // Same child objects Render writes. The bytes after HeaderEndOffset stay in the source file, which is + // sourceLength bytes long. fileSize is the File Size written, or null when the header has no File Properties Object. + byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo, long sourceLength, out ulong? fileSize) { var childObjects = new List (); @@ -574,7 +590,52 @@ byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo) if (extendedDesc.Descriptors.Count > 0) childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc)); - return RenderHeaderObject ([.. childObjects]); + var header = RenderHeaderObject ([.. childObjects]); + var writtenLength = sourceLength - headerInfo.HeaderEndOffset + header.Length; + fileSize = FileProperties is { } properties + ? AsfFileProperties.SavedFileSize (properties.FileSize, properties.Flags, + _describedLength >= 0 ? _describedLength : Source.First ?? sourceLength, writtenLength) + : null; + if (fileSize is { } size) + PatchFileSize (header, size); + return header; + } + + // Writes fileSize into the File Properties Object the read takes (#253): the last of the rebuilt header that holds a + // whole one. The value comes from the object, not from the source bytes, so a save writes the same File Size whichever + // file the payload is copied from (the one read, or one saved since). The specification allows one File Properties + // Object; any other one a header holds stays as stored, so a save with no edit is byte for byte (review 2). The rest + // of the header holds no length or offset that moves: the Header Object's size and count are written fresh, and + // nothing records where the Data Object starts. + static void PatchFileSize (byte[] header, ulong fileSize) + { + var offset = 30; + var last = -1; + while (MoreObjects (offset, header.Length)) { + var size = (int)BinaryPrimitives.ReadUInt64LittleEndian (header.AsSpan (offset + 16)); + if (AsfGuid.Parse (header.AsSpan (offset)).Value == AsfGuids.FilePropertiesObject && size >= 24 + AsfFileProperties.MinContentSize) + last = offset; + + offset += size; + } + + if (last >= 0) + BinaryPrimitives.WriteUInt64LittleEndian (header.AsSpan (last + 24 + AsfFileProperties.FileSizeOffset, 8), fileSize); + } + + // After a successful save over the source the object describes the file it wrote: its length, and the File Properties + // that save wrote. A save elsewhere leaves the source described, as a fresh read of it given the same edits describes + // it (contract suite round 3, R3); a failed save changes neither. Either way the payload of a later span save may come + // from any file the object saved (SourceLength). + FileWriteResult Wrote (FileWriteResult result, ulong? fileSize, long writtenLength, ReadOnlyMemory header, IFileSystem? fileSystem) + { + if (result.IsSuccess && SavedOverSource.Holds (SourcePath, _sourceFileSystem ?? fileSystem, writtenLength, new WrittenBytes (0, header))) { + _describedLength = writtenLength; + if (fileSize is { } size && FileProperties is { } properties) + FileProperties = properties.WithFileSize (size); + } + + return Source.Saved (result); } static byte[] RenderHeaderObject (byte[][] childObjects) @@ -738,10 +799,10 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, return mismatch; var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; - var rendered = Render (originalData); + var rendered = Render (originalData, out var fileSize, out var headerLength); if (rendered.Length == 0) return FileWriteResult.Failure (HeaderNotWhole); - return Source.Saved (AtomicFileWriter.Write (path, rendered, fs)); + return Wrote (AtomicFileWriter.Write (path, rendered, fs), fileSize, rendered.Length, rendered.AsMemory (0, headerLength), fs); } /// @@ -764,7 +825,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (SourcePath is not { Length: > 0 }) return FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead."); - return Source.Saved (SaveFromSource (path, fs)); + return SaveFromSource (path, fs); } // Same bytes as Render: rebuilt header, then every byte after the declared header size. @@ -785,6 +846,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, var opened = source!; var fileLength = opened.Length; byte[]? headerBytes = null; + ulong? fileSize = null; long copyStart = 0; var copyWhole = true; if (fileLength >= 30) { @@ -800,7 +862,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, if (info.IsRefused) return FileWriteResult.Failure (HeaderNotWhole); if (info.IsValid) { - headerBytes = RenderRebuiltHeader (info); + headerBytes = RenderRebuiltHeader (info, fileLength, out fileSize); copyStart = info.HeaderEndOffset; copyWhole = false; } @@ -821,7 +883,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, StreamCopy.Copy (opened.Stream, output, tail, copyBuffer); }); source = null; - return written; + return Wrote (written, fileSize, (headerBytes?.Length ?? 0) + tail, headerBytes ?? ReadOnlyMemory.Empty, fileSystem); } finally { source?.Dispose (); if (chunk is not null) @@ -884,10 +946,10 @@ public async Task SaveToFileAsync ( return mismatch; var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; - var rendered = Render (originalData.Span); + var rendered = Render (originalData.Span, out var fileSize, out var headerLength); if (rendered.Length == 0) return FileWriteResult.Failure (HeaderNotWhole); - return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false)); + return Wrote (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), fileSize, rendered.Length, rendered.AsMemory (0, headerLength), fs); } /// @@ -916,7 +978,7 @@ public Task SaveToFileAsync ( if (SourcePath is not { Length: > 0 }) return Task.FromResult (FileWriteResult.Failure ("No source path available. Use SaveToFileAsync(path) instead.")); - return Task.FromResult (Source.Saved (SaveFromSource (path, fs, cancellationToken))); + return Task.FromResult (SaveFromSource (path, fs, cancellationToken)); } /// diff --git a/src/TagLibSharp2/Asf/AsfFileProperties.cs b/src/TagLibSharp2/Asf/AsfFileProperties.cs index 39cc5d04..80f09eab 100644 --- a/src/TagLibSharp2/Asf/AsfFileProperties.cs +++ b/src/TagLibSharp2/Asf/AsfFileProperties.cs @@ -129,6 +129,29 @@ public TimeSpan Duration { MaxBitrate = maxBitrate; } + /// The offset of File Size in the object's content, after the File ID. + internal const int FileSizeOffset = 16; + + /// The offset of Flags in the object's content. + internal const int FlagsOffset = 64; + + /// This object with as its File Size, as a save that rewrote the field leaves it. + internal AsfFileProperties WithFileSize (ulong fileSize) => + new (FileId, fileSize, CreationDateFiletime, DataPacketsCount, PlayDurationNs, SendDurationNs, PrerollMs, Flags, + MinPacketSize, MaxPacketSize, MaxBitrate); + + /// + /// The File Size a save writes, given the one the object holds () and its + /// , when the file the object describes is bytes and the + /// save writes (#253). File Size is "the size, in bytes, of the entire file" (ASF + /// Specification 01.20.03, File Properties Object), so a save that changes the length writes the length it writes. A + /// save that keeps the length keeps the object's value, so a save with no edit leaves the field as it was, even where + /// another tagger left it wrong. Null while the Broadcast Flag is set: the specification calls the field invalid + /// then, and the save leaves the bytes as they are. + /// + internal static ulong? SavedFileSize (ulong stored, uint flags, long describedLength, long writtenLength) => + (flags & 0x01) != 0 ? null : writtenLength == describedLength ? stored : (ulong)writtenLength; + /// /// Parses a File Properties Object from binary data. /// diff --git a/src/TagLibSharp2/Core/SourceLength.cs b/src/TagLibSharp2/Core/SourceLength.cs index 0038bf82..3b04730a 100644 --- a/src/TagLibSharp2/Core/SourceLength.cs +++ b/src/TagLibSharp2/Core/SourceLength.cs @@ -61,6 +61,12 @@ public FileWriteResult Saved (FileWriteResult result) public async Task Saved (Task save) => Saved (await save.ConfigureAwait (false)); + /// + /// The length of the file the read saw, or of the file the object last saved over its source (); + /// null before a read recorded one. + /// + public long? First => _lengths.Count > 0 ? _lengths[0] : null; + /// Whether is the length of a file the object describes. public bool Describes (long length) => _lengths.Contains (length); diff --git a/tests/TagLibSharp2.Tests/Asf/AsfFileSizeTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfFileSizeTests.cs new file mode 100644 index 00000000..f9965977 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfFileSizeTests.cs @@ -0,0 +1,262 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// A save that changes an ASF file's length keeps the File Properties Object's File Size, "the size, in bytes, of the +/// entire file" (ASF Specification 01.20.03, File Properties Object), true (#253): on every save entry point, growing +/// or shrinking the header; a save with no edit stays byte for byte; and the object's +/// after a save over its source is what a fresh read of the file shows. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfFileSizeTests +{ + // The 30-byte Header Object, the File Properties Object's 24-byte header, then its File ID (16). + const int FileSizeOffset = 30 + 24 + 16; + const int FlagsOffset = FileSizeOffset + (6 * 8); + + static readonly string[] Edits = ["grow", "shrink", "none"]; + static readonly string[] Entries = ["span", "async-span", "path", "async-path", "source", "async-source", "stream-path", "stream-async-path"]; + + public static IEnumerable Cases => + from edit in Edits + from entry in Entries + select new object[] { edit, entry }; + + /// A WMA whose File Size is its length, as Windows Media writers leave it. + static byte[] Wma () + { + var bytes = AsfTestBuilder.CreateMinimalWma (title: "A title of some length", artist: "Artist"); + BinaryPrimitives.WriteUInt64LittleEndian (bytes.AsSpan (FileSizeOffset), (ulong)bytes.Length); + return bytes; + } + + [TestMethod] + [DynamicData (nameof (Cases))] + public void Save_FileSizeIsTheLengthWritten (string edit, string entry) + { + var original = Wma (); + var files = new MockFileSystem (); + files.AddFile ("/f.wma", original); + var file = Read (entry, original, files); + Apply (edit, file); + + Save (entry, file, original, files); + + var saved = files.ReadAllBytes ("/f.wma"); + var cell = $"{edit}, {entry}"; + Assert.AreEqual ((ulong)saved.Length, BinaryPrimitives.ReadUInt64LittleEndian (saved.AsSpan (FileSizeOffset)), cell); + if (edit == "none") + CollectionAssert.AreEqual (original, saved, $"{cell}: a save with no edit is byte for byte"); + else + Assert.AreNotEqual (original.Length, saved.Length, $"{cell}: the edit changes the length"); + // An object read from bytes has no source to save over: it still describes the bytes read (contract suite round 3). + var described = entry is "span" or "async-span" ? original : saved; + Assert.AreEqual (AsfFile.Read (described).File!.FileProperties!.FileSize, file.FileProperties!.FileSize, $"{cell}: the object describes the file it saved over, or the bytes it read"); + } + + /// A second save after a save over the source keeps the File Size true too, as a fresh read's save does. + [TestMethod] + [DataRow ("path")] + [DataRow ("source")] + public void SaveAfterSave_IsTheFreshReadsSave (string entry) + { + var files = new MockFileSystem (); + files.AddFile ("/f.wma", Wma ()); + var file = Read (entry, files.ReadAllBytes ("/f.wma"), files); + Apply ("grow", file); + Save (entry, file, files.ReadAllBytes ("/f.wma"), files); + var fresh = new MockFileSystem (); + fresh.AddFile ("/f.wma", files.ReadAllBytes ("/f.wma")); + + Apply ("shrink", file); + Save (entry, file, files.ReadAllBytes ("/f.wma"), files); + var reread = Read (entry, fresh.ReadAllBytes ("/f.wma"), fresh); + Apply ("shrink", reread); + Save (entry, reread, fresh.ReadAllBytes ("/f.wma"), fresh); + + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f.wma"), files.ReadAllBytes ("/f.wma"), entry); + } + + /// + /// A File Size that was not the file's length before (0, larger than the file as a file cut short holds, or smaller, + /// as another tagger that grew the header left it) is the written length after a save that changes the length, and + /// stays as it was after a save that does not. A broadcast file's, which the specification calls invalid, stays. + /// + [TestMethod] + [DataRow ("broadcast", true)] + [DataRow ("zero", true)] + [DataRow ("cut short", true)] + [DataRow ("stale", true)] + [DataRow ("zero", false)] + [DataRow ("stale", false)] + public void Save_FileSizeThatWasNotTheLength (string kind, bool grow) + { + var original = Wma (); + var declared = kind switch { + "zero" => 0UL, + "cut short" => (ulong)original.Length + 5000, + "stale" => (ulong)original.Length - 100, + _ => (ulong)original.Length, + }; + BinaryPrimitives.WriteUInt64LittleEndian (original.AsSpan (FileSizeOffset), declared); + if (kind == "broadcast") + BinaryPrimitives.WriteUInt32LittleEndian (original.AsSpan (FlagsOffset), 0x03); + var file = AsfFile.Read (original).File!; + if (grow) + Apply ("grow", file); + + var saved = file.Render (original); + + var expected = kind == "broadcast" || !grow ? declared : (ulong)saved.Length; + Assert.AreEqual (expected, BinaryPrimitives.ReadUInt64LittleEndian (saved.AsSpan (FileSizeOffset)), $"{kind}, grow {grow}"); + if (!grow) + CollectionAssert.AreEqual (original, saved, $"{kind}: a save with no edit is byte for byte"); + } + + /// + /// An object read from bytes whose File Size is stale: a save that grows the title, then one that sets another. An + /// object read from bytes has no source to save over, so both saves go elsewhere and it still describes the bytes + /// read: the second save writes what a fresh read of them, given both edits, writes, whichever bytes it copies the + /// payload from (review 1 N4; contract suite round 3 R3 for the oracle), and its File Properties stay the ones read. + /// + [TestMethod] + [DataRow ("path")] + [DataRow ("span")] + [DataRow ("span-saved")] + public void GrowThenRevert_FromBytesWithAStaleFileSize_IsTheFreshReadsSave (string entry) + { + var original = Wma (); + BinaryPrimitives.WriteUInt64LittleEndian (original.AsSpan (FileSizeOffset), 1234); + var files = new MockFileSystem (); + var file = AsfFile.Read (original).File!; + file.Tag.Title = new string ('L', 3000); + Assert.IsTrue (Save (entry, file, original, files).IsSuccess); + var firstWritten = files.ReadAllBytes ("/f.wma"); + + file.Tag.Title = "A title of some length"; + Assert.IsTrue (Save (entry, file, entry == "span-saved" ? firstWritten : original, files).IsSuccess); + var reread = AsfFile.Read (original).File!; + reread.Tag.Title = new string ('L', 3000); + reread.Tag.Title = "A title of some length"; + var fresh = new MockFileSystem (); + Assert.IsTrue (reread.SaveToFile ("/f.wma", original, fresh).IsSuccess); + + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/f.wma"), files.ReadAllBytes ("/f.wma"), entry); + Assert.AreEqual (1234UL, file.FileProperties!.FileSize, entry); + + static FileWriteResult Save (string entry, AsfFile file, byte[] payload, MockFileSystem files) => + entry == "path" ? file.SaveToFile ("/f.wma", files) : file.SaveToFile ("/f.wma", payload, files); + } + + /// + /// A header with two File Properties Objects (the specification allows one): a save that changes the length writes it + /// into the last, the one the read takes, and leaves the other as stored, so a save with no edit is byte for byte + /// (review 1 N4, review 2). The object, read from bytes, saved elsewhere, so its File Properties stay the last one as + /// read, as a fresh read of those bytes shows (contract suite round 3). + /// + [TestMethod] + public void TwoFilePropertiesObjects_TheLastHoldsTheLengthWritten () + { + var first = AsfTestBuilder.CreateFilePropertiesObject (1000, 128000); + var second = AsfTestBuilder.CreateFilePropertiesObject (1000, 128000); + BinaryPrimitives.WriteUInt64LittleEndian (first.AsSpan (24 + 16), 111); + BinaryPrimitives.WriteUInt64LittleEndian (second.AsSpan (24 + 16), 222); + byte[] original = [ + .. AsfTestBuilder.CreateHeaderObject (first, AsfTestBuilder.CreateAudioStreamPropertiesObject (44100, 2, 16), second), + .. AsfTestBuilder.CreateDataObject (0)]; + var file = AsfFile.Read (original).File!; + Assert.AreEqual (222UL, file.FileProperties!.FileSize, "the read takes the last"); + var files = new MockFileSystem (); + Assert.IsTrue (file.SaveToFile ("/same.wma", original, files).IsSuccess); + CollectionAssert.AreEqual (original, files.ReadAllBytes ("/same.wma"), "a save with no edit is byte for byte"); + file.Tag.Title = new string ('L', 300); + + Assert.IsTrue (file.SaveToFile ("/f.wma", original, files).IsSuccess); + + var saved = files.ReadAllBytes ("/f.wma"); + var at = saved.AsSpan ().IndexOf (AsfGuids.FilePropertiesObject.Render ().Span); + var next = saved.AsSpan (at + 24).IndexOf (AsfGuids.FilePropertiesObject.Render ().Span) + at + 24; + Assert.AreEqual (111UL, BinaryPrimitives.ReadUInt64LittleEndian (saved.AsSpan (at + 24 + 16)), "first, as stored"); + Assert.AreEqual ((ulong)saved.Length, BinaryPrimitives.ReadUInt64LittleEndian (saved.AsSpan (next + 24 + 16)), "last"); + Assert.AreEqual ((ulong)saved.Length, AsfFile.Read (saved).File!.FileProperties!.FileSize, "a fresh read"); + Assert.AreEqual (222UL, file.FileProperties.FileSize, "a save elsewhere leaves the object describing the bytes read"); + } + + /// + /// A File Properties Object too short to hold its fields, beside a whole one, is not written into: the save writes + /// the File Size into the whole one and leaves the short one and the bytes of the object after it as they were + /// (review 1 N5). + /// + [TestMethod] + public void ShortFilePropertiesObject_IsNotWrittenInto () + { + var shortObject = new byte[24 + 20]; + AsfGuids.FilePropertiesObject.Render ().Span.CopyTo (shortObject); + BinaryPrimitives.WriteUInt64LittleEndian (shortObject.AsSpan (16), (ulong)shortObject.Length); + var stream = AsfTestBuilder.CreateAudioStreamPropertiesObject (44100, 2, 16); + byte[] original = [ + .. AsfTestBuilder.CreateHeaderObject (AsfTestBuilder.CreateFilePropertiesObject (1000, 128000), shortObject, stream), + .. AsfTestBuilder.CreateDataObject (0)]; + var file = AsfFile.Read (original).File!; + Assert.IsNotNull (file.FileProperties); + file.Tag.Title = new string ('L', 300); + + var saved = file.Render (original); + + Assert.IsGreaterThanOrEqualTo (0, saved.AsSpan ().IndexOf ([.. shortObject, .. stream]), "the short object and the one after it are kept"); + } + + /// A save that fails changes neither the object's File Properties nor the length it describes (review 1 N5). + [TestMethod] + public void FailedSave_LeavesTheFileProperties () + { + var original = Wma (); + var files = new MockFileSystem (); + files.AddFile ("/f.wma", original); + var file = AsfFile.ReadFromFile ("/f.wma", files).File!; + file.Tag.Title = new string ('L', 3000); + + var failed = file.SaveToFile ("/f.wma", original, FaultFileSystem.Io (new IOException ("disk full"))); + + Assert.IsFalse (failed.IsSuccess); + Assert.AreEqual ((ulong)original.Length, file.FileProperties!.FileSize); + Assert.IsTrue (file.SaveToFile (files).IsSuccess); + Assert.AreEqual ((ulong)files.ReadAllBytes ("/f.wma").Length, file.FileProperties.FileSize); + } + + static void Apply (string edit, AsfFile file) + { + if (edit == "grow") + file.Tag.Title = new string ('L', 3000); + else if (edit == "shrink") + file.Tag.Title = "T"; + } + + static AsfFile Read (string entry, byte[] bytes, MockFileSystem files) => entry switch { + "span" or "async-span" => AsfFile.Read (bytes).File!, + "stream-path" or "stream-async-path" or "source" or "async-source" => (AsfFile)MediaFile.Read ("/f.wma", files).File!, + _ => AsfFile.ReadFromFile ("/f.wma", files).File!, + }; + + static void Save (string entry, AsfFile file, byte[] original, MockFileSystem files) + { + var result = entry switch { + "span" => file.SaveToFile ("/f.wma", original, files), + "async-span" => file.SaveToFileAsync ("/f.wma", original, files).GetAwaiter ().GetResult (), + "path" or "stream-path" => file.SaveToFile ("/f.wma", files), + "async-path" or "stream-async-path" => file.SaveToFileAsync ("/f.wma", files).GetAwaiter ().GetResult (), + "source" => file.SaveToFile (files), + _ => file.SaveToFileAsync (files).GetAwaiter ().GetResult (), + }; + Assert.IsTrue (result.IsSuccess, $"{entry}: {result.Error}"); + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs index 1cf7aee8..e662833f 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectsSaveTests.cs @@ -74,7 +74,10 @@ public async Task CountShortOrLong_SaveCarriesEveryObject (string shape, string Assert.IsTrue (result.IsSuccess, result.Error); var written = files.ReadAllBytes (target); - foreach (var kept in new[] { FileProperties, StreamProperties, Unknown }) + // The File Properties Object comes across with its File Size the length written (#253). + var fileProperties = (byte[])FileProperties.Clone (); + BinaryPrimitives.WriteUInt64LittleEndian (fileProperties.AsSpan (24 + 16), (ulong)written.Length); + foreach (var kept in new[] { fileProperties, StreamProperties, Unknown }) Assert.IsGreaterThanOrEqualTo (0, written.AsSpan ().IndexOf (kept), $"{shape} {save}: a header object was not carried across"); var back = (IMediaFile)MediaFile.ReadFromData (written, "/back.wma").File!; Assert.AreEqual ("New", back.Tag?.Title); diff --git a/tests/TagLibSharp2.Tests/Asf/AsfSaveElsewhereTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfSaveElsewhereTests.cs new file mode 100644 index 00000000..24f9ad5c --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfSaveElsewhereTests.cs @@ -0,0 +1,46 @@ +// 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.Tests.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// An ASF save to another path leaves the object describing its source (contract suite round 3, R3): a second save +/// elsewhere writes what a fresh read of the source, given both edits, writes. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfSaveElsewhereTests +{ + static readonly string[] Edits = ["title-null", "custom", "title", "clear"]; + static readonly bool[] Titled = [true, false]; + + public static IEnumerable Pairs => + from first in Edits + from second in Edits + from titled in Titled + select new object[] { titled, first, second }; + + [TestMethod] + [DynamicData (nameof (Pairs))] + public void SaveElsewhereTwice_IsTheFreshReadsSave (bool titled, string first, string second) + { + var source = titled ? AsfTestBuilder.CreateMinimalWma (title: "Title") : AsfTestBuilder.CreateMinimalWma (); + SaveElsewhere.AssertSecondSaveIsFresh (source, ".wma", file => Apply (file, first), file => Apply (file, second), + $"titled {titled}: {first}, then {second}"); + } + + static void Apply (IMediaFile file, string step) + { + var tag = file.Tag!; + switch (step) { + case "title-null": tag.Title = null; break; + case "custom": tag.SetCustomField ("MYFIELD", "c1"); break; + case "title": tag.Title = "T2"; break; + default: tag.Clear (); break; + } + } +} diff --git a/tests/TagLibSharp2.Tests/Asf/AsfSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfSaveStreamsAudioTests.cs index fbcf6b64..104f7969 100644 --- a/tests/TagLibSharp2.Tests/Asf/AsfSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Asf/AsfSaveStreamsAudioTests.cs @@ -36,7 +36,8 @@ public void SaveToFile_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (round 3 R3). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); @@ -62,7 +63,8 @@ public async Task SaveToFileAsync_CopiesAudioWithoutLoadingTheFile () var allocated = GC.GetAllocatedBytesForCurrentThread () - before; Assert.IsTrue (save.IsSuccess, save.Error); - Assert.AreEqual (1, fs.SourceLengthGets, "source length reads"); + // Open records the length once. The save then reads the source back to see whether it wrote over it (round 3 R3). + Assert.AreEqual (2, fs.SourceLengthGets, "source length reads"); Assert.IsTrue ( allocated < original.Length / 2, $"save allocated {allocated} bytes for a {original.Length} byte file"); From 3eb31d1d8d50036d8919e91bc24e9f93c353dedb Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:45:36 -0700 Subject: [PATCH 10/12] fix: Keep an ASF header's objects in the order they were read (#257) Cause: the header rebuild copied every object but the Content Description and Extended Content Description Objects, then appended those two rendered from the tag. A header that held them earlier ([File Properties, Header Extension, Extended Content Description, ...] in sample.wma) came out with them last, so a save with no edit changed both WMA files in the TagLib# test set (sample.wma from offset 4,330, "01 - I'm Yours.wma" from 6,297), with the same length. Found by review 1 of the v0.8.0 branch (N3). Fix: ParseHeaderStructure keeps every object, in order (HeaderParseInfo.Objects), and RenderRebuiltHeader renders each description object from the tag where the first of its kind was read; a later copy of either (the specification allows one) is dropped, as before, and one the file did not have goes after the others, as before. The specification sets no order for header objects (ASF Specification 01.20.03, Header Object), so the order read is kept. Tests: AsfHeaderObjectOrderTests. NoEditSave_IsByteForByte over every order of {File Properties, Extended Content Description, Stream Properties, Content Description} x {Render, path save, path save after a stream read}; Edit_KeepsEveryObjectInItsPlace over every order; NewDescriptionObjects_GoLast; SecondDescriptionObject_IsDropped_TheFirstKeepsItsPlace. Black box: the no-edit save of sample.wma and "01 - I'm Yours.wma" is now byte-identical. Red: 45 of 50 rows failed on the branch before the fix. --- CHANGELOG.md | 1 + src/TagLibSharp2/Asf/AsfFile.cs | 66 ++++---- .../Asf/AsfHeaderObjectOrderTests.cs | 143 ++++++++++++++++++ 3 files changed, 183 insertions(+), 27 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectOrderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 20ebb961..b4796ce2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- An ASF save writes the header's objects in the order they were read (#257). The Content Description and Extended Content Description Objects were moved to the end of the header, so a save with no edit changed both WMA files in the TagLib# test set (`sample.wma` from offset 4,330). They are now rewritten where they were, and a save with no edit of those files is byte for byte; one the file did not have goes after the others, as before, and a second copy of either (the specification allows one) is still dropped - An ASF save that changes the file's length keeps the File Properties Object's File Size, "the size, in bytes, of the entire file", true (#253). It was copied unchanged, so a 10,332-byte WMA given a long title read a File Size of 10,332 at 18,314 bytes. A save whose length differs from the file the object describes (the one it read, or the one it last saved over its source) now writes the length it writes, into the File Properties Object the read takes (the last, in a header holding more than the one the specification allows; any other stays as stored), on every save entry point, and after a save over the source `AsfFile.FileProperties` is the object the save wrote; a save to another path leaves the object describing its source. A save that keeps the length writes the object's File Size, so a save with no edit leaves the field as it was, even where another tagger left it stale (both WMA files in the TagLib# test set declare a size smaller than the file). A broadcast file's File Size, which the specification calls invalid, stays as it is - An MP4 ilst keeps its items in the order they were read, and a save after a save over the source writes what a fresh read of the saved file writes (#252). Standard atoms, freeform (`----`) fields, cover art and atoms the tag does not map share one order: a set field stays in its item's place and a new field goes after the others, in the order added. A save grouped them by kind and wrote the standard atoms in the order of a dictionary that reused a removed atom's slot, so a save with no edit reordered `sample.m4a`, `bgo_676934.m4a`, `bgo_701689.m4a`, `sample_replaygain.m4a` and `01 Horrible Theme.m4a` (it is now byte-identical). After a save over the source the object's tag takes the state a fresh read of the saved file has (its items, places, keys and key indexes, slots and metas), so the next save writes what that read's save writes in an iTunes `ilst`, a QuickTime `keys` meta, and a `moov/meta` beside `udta/meta` alike; the tag the object holds keeps its identity, whether the file read it, the caller assigned it or a view created it, and takes a new tag's state when the save wrote no `ilst`, so a reference to it stays live and a later edit through it is written. A save over the source is recognised as #179 recognises it, by what the file at `SourcePath` holds, under any spelling of the path or file system. A read where a second meta overrides n fields is linear in n again; it walked every field for each one. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read - A WAV or AVI INFO list keeps its fields in the order they were read (#251). A field added after a removal took the removed field's place, so after a save over the source a save from the same object and a save from a fresh read of that file, given the same edit, wrote the fields in different orders. A changed value now stays in its field's place and a new field goes after the others, in the order added, as for APE items (#238) diff --git a/src/TagLibSharp2/Asf/AsfFile.cs b/src/TagLibSharp2/Asf/AsfFile.cs index 9fbe21da..81ebdf93 100644 --- a/src/TagLibSharp2/Asf/AsfFile.cs +++ b/src/TagLibSharp2/Asf/AsfFile.cs @@ -560,12 +560,38 @@ byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo, long sourceLength, out u { var childObjects = new List (); - // Copy preserved objects (File Properties, Stream Properties, etc.). The Header Extension Object is - // rebuilt only when a write changed its Metadata or Metadata Library records. + // Every object goes back in the order it was read (#257); the specification sets no order. The Content + // Description and Extended Content Description Objects are rendered from the tag where the first of each was, + // and a later copy of either (the specification allows one) is dropped. The Header Extension Object is rebuilt + // only when a write changed its Metadata or Metadata Library records. + var contentDesc = Tag.ContentDescription; + var hasDescription = !string.IsNullOrEmpty (contentDesc.Title) || + !string.IsNullOrEmpty (contentDesc.Author) || + !string.IsNullOrEmpty (contentDesc.Copyright) || + !string.IsNullOrEmpty (contentDesc.Description) || + !string.IsNullOrEmpty (contentDesc.Rating); + var extendedDesc = Tag.ExtendedContentDescription; + var hasExtended = extendedDesc.Descriptors.Count > 0; var wroteExtension = false; - foreach (var obj in headerInfo.PreservedObjects) { - var isExtension = AsfGuid.Parse (obj).Value == AsfGuids.HeaderExtensionObject; - if (isExtension && Tag.HeaderExtensionChanged && !wroteExtension) { + var placedDescription = false; + var placedExtended = false; + foreach (var obj in headerInfo.Objects) { + var guid = AsfGuid.Parse (obj).Value; + if (guid == AsfGuids.ContentDescriptionObject) { + if (!placedDescription && hasDescription) + childObjects.Add (RenderContentDescriptionObject (contentDesc)); + placedDescription = true; + continue; + } + + if (guid == AsfGuids.ExtendedContentDescriptionObject) { + if (!placedExtended && hasExtended) + childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc)); + placedExtended = true; + continue; + } + + if (guid == AsfGuids.HeaderExtensionObject && Tag.HeaderExtensionChanged && !wroteExtension) { childObjects.Add (RenderHeaderExtension (obj, Tag)); wroteExtension = true; continue; @@ -575,19 +601,10 @@ byte[] RenderRebuiltHeader (HeaderParseInfo headerInfo, long sourceLength, out u if (!wroteExtension && Tag.HeaderExtensionChanged && Tag.LibraryRecords is { Count: > 0 }) childObjects.Add (RenderHeaderExtension (null, Tag)); - // Add Content Description if tag has content - var contentDesc = Tag.ContentDescription; - if (!string.IsNullOrEmpty (contentDesc.Title) || - !string.IsNullOrEmpty (contentDesc.Author) || - !string.IsNullOrEmpty (contentDesc.Copyright) || - !string.IsNullOrEmpty (contentDesc.Description) || - !string.IsNullOrEmpty (contentDesc.Rating)) { + // A description object the file did not have goes after the others. + if (!placedDescription && hasDescription) childObjects.Add (RenderContentDescriptionObject (contentDesc)); - } - - // Add Extended Content Description if tag has extended content - var extendedDesc = Tag.ExtendedContentDescription; - if (extendedDesc.Descriptors.Count > 0) + if (!placedExtended && hasExtended) childObjects.Add (RenderExtendedContentDescriptionObject (extendedDesc)); var header = RenderHeaderObject ([.. childObjects]); @@ -704,7 +721,8 @@ readonly struct HeaderParseInfo { public bool IsValid { get; } public int HeaderEndOffset { get; } - public List PreservedObjects { get; } + /// Every object of the header, in the order read. + public List Objects { get; } /// The header parsed, but its objects do not fill it whole: a save would drop bytes, and fails. public bool IsRefused { get; } @@ -713,7 +731,7 @@ public HeaderParseInfo (bool isValid, int headerEndOffset, List preserve { IsValid = isValid; HeaderEndOffset = headerEndOffset; - PreservedObjects = preservedObjects; + Objects = preservedObjects; IsRefused = isRefused; } @@ -753,8 +771,6 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data) if (!guidResult.IsSuccess) return HeaderParseInfo.Refused (); - var objectGuid = guidResult.Value; - var objectSize = BinaryPrimitives.ReadUInt64LittleEndian (data[(offset + 16)..]); if (objectSize < 24 || objectSize > int.MaxValue) return HeaderParseInfo.Refused (); @@ -763,12 +779,8 @@ static HeaderParseInfo ParseHeaderStructure (ReadOnlySpan data) if (offset + objSize > headerEnd) return HeaderParseInfo.Refused (); - // Preserve all objects except Content Description and Extended Content Description - // (those will be re-rendered from the Tag) - if (objectGuid != AsfGuids.ContentDescriptionObject && - objectGuid != AsfGuids.ExtendedContentDescriptionObject) { - preservedObjects.Add (data.Slice (offset, objSize).ToArray ()); - } + // Every object is kept in order; the description objects are rendered from the tag in their place. + preservedObjects.Add (data.Slice (offset, objSize).ToArray ()); offset += objSize; } diff --git a/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectOrderTests.cs b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectOrderTests.cs new file mode 100644 index 00000000..9ff13eec --- /dev/null +++ b/tests/TagLibSharp2.Tests/Asf/AsfHeaderObjectOrderTests.cs @@ -0,0 +1,143 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Asf; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Asf; + +/// +/// An ASF save writes the header's objects in the order they were read (#257). The Content Description and Extended +/// Content Description Objects are rewritten where they were, so a save with no edit is byte for byte; one the file did +/// not have goes after the others, as before. The specification sets no order for header objects (ASF Specification +/// 01.20.03, Header Object), so the order read is the one kept. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Asf")] +public class AsfHeaderObjectOrderTests +{ + static readonly string[] Entries = ["render", "path", "source"]; + + static readonly byte[] FileProperties = AsfTestBuilder.CreateFilePropertiesObject (1000, 128000); + static readonly byte[] StreamProperties = AsfTestBuilder.CreateAudioStreamPropertiesObject (44100, 2, 16); + static readonly byte[] Description = AsfTestBuilder.CreateContentDescriptionObject ("Title", "Artist"); + static readonly byte[] Extended = AsfTestBuilder.CreateExtendedContentDescriptionObject ( + AsfDescriptor.CreateString ("WM/AlbumTitle", "Album")); + + /// Every order of the four objects the file holds. + public static IEnumerable Orders () + { + foreach (var order in Permutations ([0, 1, 2, 3])) + yield return [string.Join ("", order)]; + } + + [TestMethod] + [DynamicData (nameof (Orders))] + public void NoEditSave_IsByteForByte (string order) + { + var original = Build (order); + var files = new MockFileSystem (); + files.AddFile ("/f.wma", original); + + foreach (var entry in Entries) { + var file = entry == "source" ? (AsfFile)MediaFile.Read ("/f.wma", files).File! : AsfFile.ReadFromFile ("/f.wma", files).File!; + var saved = entry == "render" ? file.Render (original) : Save (file, files); + CollectionAssert.AreEqual (original, saved, $"{order}, {entry}"); + } + } + + /// An edit rewrites the description objects where they were. + [TestMethod] + [DynamicData (nameof (Orders))] + public void Edit_KeepsEveryObjectInItsPlace (string order) + { + var file = AsfFile.Read (Build (order)).File!; + file.Tag.Title = "A longer title than before"; + file.Tag.Album = "A longer album than before"; + + var saved = file.Render (Build (order)); + + Assert.AreEqual (string.Join (",", Kinds (Build (order))), string.Join (",", Kinds (saved)), order); + } + + /// A description object the file did not have goes after the others. + [TestMethod] + public void NewDescriptionObjects_GoLast () + { + byte[] original = [.. AsfTestBuilder.CreateHeaderObject (StreamProperties, FileProperties), .. AsfTestBuilder.CreateDataObject (0)]; + var file = AsfFile.Read (original).File!; + file.Tag.Title = "New"; + file.Tag.Album = "New album"; + + var saved = file.Render (original); + + CollectionAssert.AreEqual ((string[])["stream", "file", "description", "extended"], Kinds (saved)); + } + + /// A second copy of a description object (the specification allows one) goes, as before; the first keeps its place. + [TestMethod] + [DataRow ("description")] + [DataRow ("extended")] + public void SecondDescriptionObject_IsDropped_TheFirstKeepsItsPlace (string kind) + { + var (first, second) = kind == "description" + ? (Description, AsfTestBuilder.CreateContentDescriptionObject ("Other", "Other")) + : (Extended, AsfTestBuilder.CreateExtendedContentDescriptionObject (AsfDescriptor.CreateString ("WM/AlbumTitle", "Other"))); + byte[] original = [.. AsfTestBuilder.CreateHeaderObject (first, FileProperties, second, StreamProperties), .. AsfTestBuilder.CreateDataObject (0)]; + var file = AsfFile.Read (original).File!; + file.Tag.Title = "Edited"; + file.Tag.Album = "Edited album"; + + var saved = file.Render (original); + + var expected = kind == "description" ? "description,file,stream,extended" : "extended,file,stream,description"; + Assert.AreEqual (expected, string.Join (",", Kinds (saved)), kind); + } + + static byte[] Save (AsfFile file, MockFileSystem files) + { + var result = file.SaveToFile ("/out.wma", files); + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes ("/out.wma"); + } + + static byte[] Build (string order) + { + byte[][] objects = [FileProperties, Extended, StreamProperties, Description]; + var header = AsfTestBuilder.CreateHeaderObject ([.. order.Select (c => objects[c - '0'])]); + return [.. header, .. AsfTestBuilder.CreateDataObject (0)]; + } + + static string[] Kinds (byte[] file) + { + var size = (int)BinaryPrimitives.ReadUInt64LittleEndian (file.AsSpan (16)); + var kinds = new List (); + for (var offset = 30; offset + 24 <= size;) { + var guid = AsfGuid.Parse (file.AsSpan (offset)).Value; + kinds.Add (guid == AsfGuids.FilePropertiesObject ? "file" + : guid == AsfGuids.StreamPropertiesObject ? "stream" + : guid == AsfGuids.ContentDescriptionObject ? "description" + : guid == AsfGuids.ExtendedContentDescriptionObject ? "extended" + : "other"); + offset += (int)BinaryPrimitives.ReadUInt64LittleEndian (file.AsSpan (offset + 16)); + } + + return [.. kinds]; + } + + static IEnumerable Permutations (int[] items) + { + if (items.Length <= 1) { + yield return items; + yield break; + } + + for (var i = 0; i < items.Length; i++) { + foreach (var rest in Permutations ([.. items[..i], .. items[(i + 1)..]])) + yield return [items[i], .. rest]; + } + } +} From db18df80d8586ddf8680972cfbec57b3c6e5956a Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:58:32 -0700 Subject: [PATCH 11/12] fix: Write no APE tag that holds no item (#258) Cause: an APE carrier rendered its tag whenever the object held one, so Clear on a tagged file wrote an empty 32-byte APE tag (header and footer when the tag was read with a header). The object that saved then still held the emptied tag, with the layout it was read with, while a fresh read of the saved file found an empty tag, so the two diverged: a fresh read cleared again wrote the empty footer where the object wrote nothing (review 1, NoLegacy-cut.ape), and a value set after the Clear went into a tag with a header from the object and a footer-only tag from a view-created one. Fix: ApeTag.RenderForSave (Monkey's Audio, WavPack, Musepack) and the raw AAC plan write nothing for a tag that StoresNothing. The object keeps the emptied tag, so a reference the caller holds stays the file's tag and a value set later through it is written (review 2 B1; a first version dropped the tag and lost that value with a success result). After a successful save over the source (HoldsFile in each carrier's Saved; AacFile's existing over-source Adopt) the file holds no APE tag, so the kept tag is no longer the tag read: the next value set is written footer-only, as a fresh read's view-created tag is, and raw AAC's view goes on without it (its first write goes to the ID3v2 tag, as a fresh read's does). After a save to another path the object still describes its source, whose tag it emptied, and keeps the read layout (contract suite round 3, R1: the same object wrote a 128-byte footer-only tag where a fresh read kept the source tag's header, 160 bytes). Tests: ApeEmptyTagTests over {.ape, .wv, .mpc, .aac} x {tagless, tag with a footer, tag with a header} x {no edit, title, Clear}: Clear and a save leave the audio with no APE tag, and the next save is the fresh read's; EmptyThenSaveElsewhere_TheNextSaveIsTheFreshReadsSave over {.ape, .wv, .mpc, .aac} x {footer, header} x {Title = null, Clear} x {title, custom field}, each saved twice to another path (sync and async). HeldTagTests (review 2 B1, across formats): {held ApeTag on .ape, .wv, .mpc, .aac; Mp4File.Tag; WAV Id3v2Tag and InfoTag; AIFF and AVI Id3v2Tag; MP3 Id3v2Tag, FLAC and Ogg VorbisComment as the reference} x {Clear, every field removed} x {save over the source, save elsewhere}, then a title through the held tag and the same save: the title is on disk, and the bytes are a fresh read's (of the source given the same edits after a save elsewhere; of the saved file given the title through its view after a save over it, where the view edits that tag); and Mp4_AssignedTag_TakesALaterEdit. Red: the 24 tagged rows failed on the branch before the fix; the 12 tagless rows passed. Of EmptyThenSaveElsewhere, 20 of 32 rows failed at the round-2 head: every header row, and the AAC footer rows (AAC's default is a header). Of HeldTagTests, 19 of 49 failed before the keep: every save-over-the-source row but the MP3, FLAC and Ogg references, and the assigned MP4 tag. --- CHANGELOG.md | 1 + src/TagLibSharp2/Aac/AacFile.cs | 33 +++- src/TagLibSharp2/Ape/ApeTag.cs | 4 +- src/TagLibSharp2/Ape/MonkeysAudioFile.cs | 22 ++- src/TagLibSharp2/Musepack/MusepackFile.cs | 22 ++- src/TagLibSharp2/WavPack/WavPackFile.cs | 22 ++- .../Ape/ApeEmptyTagTests.cs | 100 +++++++++++ .../Ape/ApeTagItemOrderTests.cs | 4 +- tests/TagLibSharp2.Tests/Core/HeldTagTests.cs | 158 ++++++++++++++++++ 9 files changed, 345 insertions(+), 21 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs create mode 100644 tests/TagLibSharp2.Tests/Core/HeldTagTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b4796ce2..21e3fbe0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2 frame in ISO-8859-1 given text that ISO-8859-1 cannot hold is written in an encoding that holds it, UTF-16 with a BOM in an ID3v2.3 tag and UTF-8 in an ID3v2.4 tag, where each such character was written as `?` (#262). This reaches a frame read from a file in ISO-8859-1 whose `Text`, `Description`, `Value`, `FileName` or pairs are then changed, and a frame built or set to `TextEncodingType.Latin1` with such text: text frames, `TXXX`, `COMM`, `USLT`, `WXXX` descriptions, `GEOB`, `SYLT`, the involved-people lists and `APIC` descriptions. A frame's own `RenderContent ()` writes such text in UTF-8, as a v2.4 tag does - A chapter or table-of-contents title in an ID3v2.3 tag whose TIT2 is 128 bytes or longer reads back (#261). The TIT2 that CHAP and CTOC embed was written with a syncsafe size, which only ID3v2.4 uses, and read with a big-endian one in v2.3, so the title was lost. The embedded frames now take the tag's own frame header when written, and are read with the same frame-header and frame-flag rules as the tag's top-level frames, so an embedded TIT2 that is grouped, compressed, unsynchronised or has a data length indicator reads too. A v2.3 file an earlier version wrote reads, since a v2.3 size that does not fit is read as syncsafe, as for a top-level frame - A frame written into an ID3v2.3 tag, or a v2.2 tag (which is written as v2.3), uses a text encoding ID3v2.3 defines: ISO-8859-1 when its text fits, otherwise UTF-16 with a BOM (#255). New frames start as UTF-8, which only ID3v2.4 defines, and were written with that encoding byte whatever the tag's version. So a picture added to an MP3 whose tag is ID3v2.3, as the QuickStart's "add album art" sample does, saved, but this library's own read of the file found no picture, because the v2.3 APIC reader rejects encoding 3. The text frames, `TXXX`, `COMM`, `USLT`, `WXXX`, `GEOB`, `SYLT`, the involved-people lists and the title inside `CHAP` and `CTOC` had the same encoding byte, which the other readers accepted. The tag's version now chooses the encoding when the tag is written, for every frame and every save path, in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI. A frame read from a v2.3 tag in UTF-8 or UTF-16BE is written back in ISO-8859-1 or UTF-16 too; one in ISO-8859-1 or UTF-16 keeps that encoding and is written as before. `SetCustomField` on a v2.3 tag now writes ISO-8859-1 when the values fit, where it always wrote UTF-16. An ID3v2.4 tag still writes UTF-8. A frame object keeps the encoding it was given, and its own `RenderContent ()` still writes that one. A v2.3 picture in UTF-8 or UTF-16BE, such as one an earlier version of this library wrote, is now read, as the other v2.3 frames are, and the next save rewrites it in an encoding v2.3 defines. The `Id3v2Tag` class example now compiles: its picture, custom-field and comment snippets used a wrong argument order and members that do not exist +- A save writes no APE tag that holds no item, in Monkey's Audio, WavPack, Musepack and raw AAC (#258). `Clear` on a tagged file wrote an empty 32-byte APE tag (with its header too, when it was read with one), so a fresh read of the saved file cleared again wrote that empty tag while the object that saved wrote none. Now `Clear` removes the tag, a file with no tag stays without one, and after such a save over its source the emptied tag the object keeps (a reference to it stays live) is no longer the tag read, so the next value set is written footer-only, as a fresh read's view writes it (raw AAC's view goes to its ID3v2 tag, as a fresh read's does); after a save to another path the object still describes its source and keeps the read layout - An ASF save writes the header's objects in the order they were read (#257). The Content Description and Extended Content Description Objects were moved to the end of the header, so a save with no edit changed both WMA files in the TagLib# test set (`sample.wma` from offset 4,330). They are now rewritten where they were, and a save with no edit of those files is byte for byte; one the file did not have goes after the others, as before, and a second copy of either (the specification allows one) is still dropped - An ASF save that changes the file's length keeps the File Properties Object's File Size, "the size, in bytes, of the entire file", true (#253). It was copied unchanged, so a 10,332-byte WMA given a long title read a File Size of 10,332 at 18,314 bytes. A save whose length differs from the file the object describes (the one it read, or the one it last saved over its source) now writes the length it writes, into the File Properties Object the read takes (the last, in a header holding more than the one the specification allows; any other stays as stored), on every save entry point, and after a save over the source `AsfFile.FileProperties` is the object the save wrote; a save to another path leaves the object describing its source. A save that keeps the length writes the object's File Size, so a save with no edit leaves the field as it was, even where another tagger left it stale (both WMA files in the TagLib# test set declare a size smaller than the file). A broadcast file's File Size, which the specification calls invalid, stays as it is - An MP4 ilst keeps its items in the order they were read, and a save after a save over the source writes what a fresh read of the saved file writes (#252). Standard atoms, freeform (`----`) fields, cover art and atoms the tag does not map share one order: a set field stays in its item's place and a new field goes after the others, in the order added. A save grouped them by kind and wrote the standard atoms in the order of a dictionary that reused a removed atom's slot, so a save with no edit reordered `sample.m4a`, `bgo_676934.m4a`, `bgo_701689.m4a`, `sample_replaygain.m4a` and `01 Horrible Theme.m4a` (it is now byte-identical). After a save over the source the object's tag takes the state a fresh read of the saved file has (its items, places, keys and key indexes, slots and metas), so the next save writes what that read's save writes in an iTunes `ilst`, a QuickTime `keys` meta, and a `moov/meta` beside `udta/meta` alike; the tag the object holds keeps its identity, whether the file read it, the caller assigned it or a view created it, and takes a new tag's state when the save wrote no `ilst`, so a reference to it stays live and a later edit through it is written. A save over the source is recognised as #179 recognises it, by what the file at `SourcePath` holds, under any spelling of the path or file system. A read where a second meta overrides n fields is linear in n again; it walked every field for each one. Before a save, or after a save to another path, a field cleared and set again still goes back where it was read diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs index 6d9ccb5e..072e6a2b 100644 --- a/src/TagLibSharp2/Aac/AacFile.cs +++ b/src/TagLibSharp2/Aac/AacFile.cs @@ -89,7 +89,24 @@ internal void MarkPicturesSkipped () /// /// Gets or sets the APEv2 tag after the stream. Set to null to remove it on save. /// - public ApeTag? ApeTag { get; set; } + public ApeTag? ApeTag { + get => _apeTag; + set { + _apeTag = value; + _apeGone = false; + } + } + + ApeTag? _apeTag; + + // The APE tag the view shows: an emptied tag a save over the source did not write is held for a caller who holds it + // (review 2 B1) and written again once it holds a value, but the file holds no APE tag, so the view goes on as a fresh + // read of that file does, its first write creating an ID3v2 tag. + ApeTag? ViewApe => _apeGone && _apeTag is { StoresNothing: true } ? null : _apeTag; + + // Whether the source holds no APE tag for the tag held: set by a save over the source that wrote none, cleared by one + // that wrote it, and by an assignment. A save elsewhere does not change it (contract suite round 3, R1). + bool _apeGone; /// /// Gets or sets the ID3v1 tag in the last 128 bytes. Set to null to remove it on save. @@ -134,7 +151,7 @@ internal void MarkPicturesSkipped () /// tag. The first write on a tagless file creates an ID3v2 tag, and a write that leaves that tag /// empty removes it again, so a save writes no empty tag. /// - public Tag? Tag => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, ApeTag, Id3v1Tag], + public Tag? Tag => _disposed ? null : CombinedTag.Over (() => [Id3v2Tag, ViewApe, Id3v1Tag], _creation ??= new TagCreation (() => new Id3v2Tag (), tag => Id3v2Tag = (Id3v2Tag?)tag)); /// @@ -448,12 +465,14 @@ Written Plan (AacTailSource source) // Lyrics3 belongs in front of ID3v1 and goes when that tag goes. var keepsLyrics = Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart; - var apeHeader = ApeTag is not null && ApeTag.HeaderForSave (ApeTag, _readApeTag, _readApeHeader, defaultHeader: true); + // An APE tag that holds nothing is not written (#258). + var ape = ApeTag is { StoresNothing: false } ? ApeTag : null; + var apeHeader = ape is not null && ApeTag.HeaderForSave (ape, _readApeTag, _readApeHeader, defaultHeader: true); return new Written ( Id3v2Tag?.Render () ?? BinaryData.Empty, audioStart, audioEnd - audioStart, - ApeTag?.RenderWithOptions (apeHeader) ?? BinaryData.Empty, + ape?.RenderWithOptions (apeHeader) ?? BinaryData.Empty, apeHeader, keepsLyrics ? tail.LyricsStart : 0, keepsLyrics ? tail.Id3v1Start - tail.LyricsStart : 0, @@ -475,7 +494,11 @@ FileWriteResult Adopt (FileWriteResult result, Written written, IFileSystem? fil _audioStart = written.Id3v2.Length; Id3v2Size = written.Id3v2.Length; - _readApeTag = ApeTag; + // No empty APE tag was written (#258), so the file holds none: the tag the object holds, kept for a caller who + // holds it (review 2 B1), is then not a tag the file read, and a value set next is written with the layout of a + // tag this file did not read, as a fresh read's view writes it. A save elsewhere does not get here (round 3, R1). + _apeGone = _apeTag is { StoresNothing: true }; + _readApeTag = _apeGone ? null : _apeTag; _readApeHeader = written.ApeHeader; Source.Rewrote (length); return result; diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index 3ffd60d8..de488ad1 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -1201,13 +1201,13 @@ internal static bool MoreItems (long offset, long length, int parsed, uint count public override BinaryData Render () => RenderWithOptions (_readWithHeader ?? false); /// - /// The bytes a save writes for , or none when it is null, in a file whose read produced + /// The bytes a save writes for , or none when it is null or holds no item (#258), in a file whose read produced /// . That tag keeps the layout it was read with, so a save with no edit reproduces it. /// Any other tag, one created here or one parsed from other bytes and assigned, gets /// : the carrier's layout for a tag it did not read. /// internal static BinaryData RenderForSave (ApeTag? tag, ApeTag? readTag, bool defaultHeader) => - tag?.RenderWithOptions (HeaderForSave (tag, readTag, null, defaultHeader)) ?? BinaryData.Empty; + tag is null || tag.StoresNothing ? BinaryData.Empty : tag.RenderWithOptions (HeaderForSave (tag, readTag, null, defaultHeader)); /// /// Whether a save writes with a header (see ). diff --git a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs index e5cf7487..b9432f8c 100644 --- a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs +++ b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs @@ -539,6 +539,20 @@ private void ParseApeTag (ReadOnlySpan data, int tagFloor) byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag, + // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set + // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it. + // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout + // (contract suite round 3, R1). + FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null + && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem)) + _readApeTag = null; + + return Source.Saved (result); + } + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -627,7 +641,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData); - return Source.Saved (AtomicFileWriter.Write (path, rendered, fs)); + return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs); } /// @@ -649,7 +663,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) return FileWriteResult.Failure ("No source path available. File was not read from disk."); var tag = ApeTagBytes (); - return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); + return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs); } /// @@ -690,7 +704,7 @@ public async Task SaveToFileAsync ( var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData.Span); - return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false)); + return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs); } /// @@ -716,7 +730,7 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); var tag = ApeTagBytes (); - return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); + return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs)); } /// diff --git a/src/TagLibSharp2/Musepack/MusepackFile.cs b/src/TagLibSharp2/Musepack/MusepackFile.cs index 296bc5ce..2b505675 100644 --- a/src/TagLibSharp2/Musepack/MusepackFile.cs +++ b/src/TagLibSharp2/Musepack/MusepackFile.cs @@ -585,6 +585,20 @@ private void ParseApeTag (ReadOnlySpan data, int tagFloor) byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag, + // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set + // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it. + // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout + // (contract suite round 3, R1). + FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null + && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem)) + _readApeTag = null; + + return Source.Saved (result); + } + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -673,7 +687,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData); - return Source.Saved (AtomicFileWriter.Write (path, rendered, fs)); + return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs); } /// @@ -695,7 +709,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) return FileWriteResult.Failure ("No source path available. File was not read from disk."); var tag = ApeTagBytes (); - return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); + return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs); } /// @@ -736,7 +750,7 @@ public async Task SaveToFileAsync ( var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData.Span); - return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false)); + return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs); } /// @@ -762,7 +776,7 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); var tag = ApeTagBytes (); - return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); + return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs)); } /// diff --git a/src/TagLibSharp2/WavPack/WavPackFile.cs b/src/TagLibSharp2/WavPack/WavPackFile.cs index f6138a0c..abdc251e 100644 --- a/src/TagLibSharp2/WavPack/WavPackFile.cs +++ b/src/TagLibSharp2/WavPack/WavPackFile.cs @@ -800,6 +800,20 @@ private static int ParseMultiChannelCount (ReadOnlySpan data) byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + // A save writes no APE tag that holds nothing (#258). After a successful one over the source the file holds no tag, + // so the tag the object holds, kept for a caller who holds it (review 2 B1), is no longer the tag read: a value set + // next is written with the layout of a tag this file did not read (footer only), as a fresh read's view writes it. + // After a save elsewhere the object still describes its source, whose tag it emptied, and keeps the read layout + // (contract suite round 3, R1). + FileWriteResult Saved (FileWriteResult result, string path, IFileSystem? fileSystem) + { + if (result.IsSuccess && ApeTag is { StoresNothing: true } && _readApeTag is not null + && SavedOverSource.HoldsFile (SourcePath, _sourceFileSystem ?? fileSystem, path, fileSystem)) + _readApeTag = null; + + return Source.Saved (result); + } + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -888,7 +902,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData); - return Source.Saved (AtomicFileWriter.Write (path, rendered, fs)); + return Saved (AtomicFileWriter.Write (path, rendered, fs), path, fs); } /// @@ -910,7 +924,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) return FileWriteResult.Failure ("No source path available. File was not read from disk."); var tag = ApeTagBytes (); - return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); + return Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag), path, fs); } /// @@ -951,7 +965,7 @@ public async Task SaveToFileAsync ( var fs = fileSystem ?? _sourceFileSystem ?? DefaultFileSystem.Instance; var rendered = Render (originalData.Span); - return Source.Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false)); + return Saved (await AtomicFileWriter.WriteAsync (path, rendered, fs, cancellationToken).ConfigureAwait (false), path, fs); } /// @@ -977,7 +991,7 @@ public Task SaveToFileAsync ( return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); var tag = ApeTagBytes (); - return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); + return Task.FromResult (Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken), path, fs)); } /// diff --git a/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs new file mode 100644 index 00000000..47ae0927 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeEmptyTagTests.cs @@ -0,0 +1,100 @@ +// 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.Tests.Core; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// A save writes no APE tag that holds no item (#258): Clear on a file with no tag writes no tag, Clear on a tagged file +/// removes the tag, and an emptied tag is gone from the object after the save, as from a fresh read of the saved file. +/// Every APE carrier: Monkey's Audio, WavPack, Musepack and raw AAC. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public class ApeEmptyTagTests +{ + static readonly string[] Carriers = [".ape", ".wv", ".mpc", ".aac"]; + static readonly string[] Starts = ["tagless", "footer", "header"]; + static readonly string[] Seconds = ["noop", "title", "clear"]; + + public static IEnumerable Cases => + from carrier in Carriers + from start in Starts + from second in Seconds + select new object[] { carrier, start, second }; + + /// {carrier} x {tagless, tag with a footer, tag with a header} x {second edit}: Clear, save, edit, save. + [TestMethod] + [DynamicData (nameof (Cases))] + public void ClearThenSave_WritesNoTag_AndTheNextSaveIsTheFreshReadsSave (string carrier, string start, string second) + { + var audio = ApeTagItemOrderTests.Carrier (carrier, []); + var original = start == "tagless" ? audio : ApeTagItemOrderTests.Carrier (carrier, ApeTagItemOrderTests.Tag (start == "header", ["Title=T", "Album=A"])); + var path = "/f" + carrier; + var files = new MockFileSystem (); + files.AddFile (path, original); + var file = (IMediaFile)MediaFile.Read (path, files).File!; + + file.Tag!.Clear (); + Save (file, files); + var cell = $"{carrier} {start} {second}"; + CollectionAssert.AreEqual (audio, files.ReadAllBytes (path), $"{cell}: Clear writes no APE tag"); + var fresh = new MockFileSystem (); + fresh.AddFile (path, files.ReadAllBytes (path)); + + Apply (file, second); + Save (file, files); + var reread = (IMediaFile)MediaFile.Read (path, fresh).File!; + Apply (reread, second); + Save (reread, fresh); + + CollectionAssert.AreEqual (fresh.ReadAllBytes (path), files.ReadAllBytes (path), cell); + } + + static readonly string[] Emptying = ["title-null", "clear"]; + static readonly string[] Refills = ["title", "custom"]; + + public static IEnumerable ElsewhereCases => + from carrier in Carriers + from start in Starts.Skip (1) + from first in Emptying + from second in Refills + select new object[] { carrier, start, first, second }; + + /// + /// {carrier} x {tag with a footer, tag with a header} x {Title = null, Clear} x {title, custom field}, each saved to + /// another path: the object still describes its source, whose tag it emptied, so a value set next goes into that tag + /// with the layout it was read with, as a fresh read of the source given both edits writes it (contract suite round 3, + /// R1). + /// + [TestMethod] + [DynamicData (nameof (ElsewhereCases))] + public void EmptyThenSaveElsewhere_TheNextSaveIsTheFreshReadsSave (string carrier, string start, string first, string second) + { + var source = ApeTagItemOrderTests.Carrier (carrier, ApeTagItemOrderTests.Tag (start == "header", ["Title=T"])); + SaveElsewhere.AssertSecondSaveIsFresh (source, carrier, file => Apply (file, first), file => Apply (file, second), + $"{carrier} {start} {first} {second}"); + } + + static void Apply (IMediaFile file, string step) + { + if (step == "title") + file.Tag!.Title = "New"; + else if (step == "title-null") + file.Tag!.Title = null; + else if (step == "custom") + file.Tag!.SetCustomField ("MYFIELD", "c1"); + else if (step == "clear") + file.Tag!.Clear (); + } + + static void Save (IMediaFile file, MockFileSystem files) + { + dynamic typed = file; + FileWriteResult result = typed.SaveToFile ((IFileSystem)files); + Assert.IsTrue (result.IsSuccess, result.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs index dd17759e..594bfd21 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagItemOrderTests.cs @@ -225,7 +225,7 @@ public void EditAndRender_AllocateLinearlyInTheItemCount () 2000); } - static byte[] Carrier (string extension, byte[] tag) => extension switch { + internal static byte[] Carrier (string extension, byte[] tag) => extension switch { ".ape" => [.. TestBuilders.MonkeysAudio.CreateMinimal (), .. tag], ".wv" => [.. TestBuilders.WavPack.CreateMinimal (), .. tag], ".aac" => [.. TagLibSharp2.Tests.Aac.AacTestBuilder.Adts (8), .. tag], @@ -233,7 +233,7 @@ public void EditAndRender_AllocateLinearlyInTheItemCount () }; /// An APEv2 tag holding text items "Key=value", in this order, with or without a header. - static byte[] Tag (bool header, string[] items) => + internal static byte[] Tag (bool header, string[] items) => Tag (header, [.. items.Select (item => (item[..item.IndexOf ('=')], 0u, Encoding.UTF8.GetBytes (item[(item.IndexOf ('=') + 1)..])))]); /// An APEv2 tag holding these items (key, item flags, value), in this order, with or without a header. diff --git a/tests/TagLibSharp2.Tests/Core/HeldTagTests.cs b/tests/TagLibSharp2.Tests/Core/HeldTagTests.cs new file mode 100644 index 00000000..3fb08030 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/HeldTagTests.cs @@ -0,0 +1,158 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Reflection; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; +using TagLibSharp2.Tests.Ape; +using TagLibSharp2.Tests.Riff; + +namespace TagLibSharp2.Tests.Core; + +/// +/// A tag the caller holds stays the file's tag after it is emptied and saved (review 2 B1): a save of an empty tag +/// writes no tag, but the object keeps the instance, so a later edit through it is written by the next save, as MP3, +/// FLAC and Ogg (the reference rows) already do. {held tag} x {Clear, every field removed} x {save over the source, save +/// elsewhere}, then a title through the held tag and the same save: the title is on disk, and the bytes are a fresh +/// read's (after a save elsewhere: of the source given the same edits; after a save over it: of the saved file, given +/// the title through its view, for a file whose held tag is its only tag). +/// +[TestClass] +[TestCategory ("Unit")] +public class HeldTagTests +{ + // fixture, held property, whether a fresh read's view edit goes to that tag (raw AAC's view writes ID3v2 first) + static readonly (string Fixture, string Property, bool Only)[] Holders = [ + (".ape", "ApeTag", true), (".wv", "ApeTag", true), (".mpc", "ApeTag", true), (".aac", "ApeTag", false), + (".m4a", "Tag", true), ("wav", "Id3v2Tag", false), ("wav", "InfoTag", false), ("aiff", "Id3v2Tag", false), + ("avi", "Id3v2Tag", false), (".mp3", "Id3v2Tag", true), (".flac", "VorbisComment", true), (".ogg", "VorbisComment", true)]; + static readonly string[] Emptyings = ["clear", "remove-each"]; + static readonly bool[] OverSource = [true, false]; + + public static IEnumerable Cases => + from holder in Holders + from emptying in Emptyings + from over in OverSource + select new object[] { holder.Fixture, holder.Property, holder.Only, emptying, over }; + + [TestMethod] + [DynamicData (nameof (Cases))] + public void EmptiedHeldTag_TakesALaterEdit (string fixture, string property, bool only, string emptying, bool over) + { + var (source, extension) = Fixture (fixture); + var cell = $"{fixture} {property} {emptying} over {over}"; + var files = new MockFileSystem (); + var path = "/s" + extension; + var target = over ? path : "/o" + extension; + files.AddFile (path, source); + using var file = (IMediaFile)MediaFile.Read (path, files).File!; + var held = Held (file, property); + + Empty (held, emptying); + Save (file, target, over, files); + var firstWritten = files.ReadAllBytes (target); + held.Title = "LATER"; + Save (file, target, over, files); + + var written = files.ReadAllBytes (target); + var reread = new MockFileSystem (); + reread.AddFile (path, written); + using (var again = (IMediaFile)MediaFile.Read (path, reread).File!) + Assert.AreEqual ("LATER", Held (again, property)?.Title, $"{cell}: the title set through the held tag is on disk"); + + if (!over) { + CollectionAssert.AreEqual (FreshHeld (source, extension, property, emptying), written, $"{cell}: a fresh read of the source"); + } else if (only) { + var fresh = new MockFileSystem (); + fresh.AddFile (path, firstWritten); + using var other = (IMediaFile)MediaFile.Read (path, fresh).File!; + other.Tag!.Title = "LATER"; + Save (other, "/o" + extension, over: false, fresh); + CollectionAssert.AreEqual (fresh.ReadAllBytes ("/o" + extension), written, $"{cell}: a fresh read of the saved file"); + } + } + + /// + /// An MP4 tag the caller assigned stays the file's tag after a save over the source writes it, so a later edit through + /// it is written (review 2 B1). + /// + [TestMethod] + public void Mp4_AssignedTag_TakesALaterEdit () + { + var (source, extension) = Fixture (".m4a"); + var files = new MockFileSystem (); + files.AddFile ("/s" + extension, source); + using var file = (Mp4File)MediaFile.Read ("/s" + extension, files).File!; + var assigned = new Mp4Tag { Title = "Assigned" }; + file.Tag = assigned; + Assert.IsTrue (file.SaveToFile (files).IsSuccess); + + assigned.Album = "LATER"; + Assert.IsTrue (file.SaveToFile (files).IsSuccess); + + using var again = (IMediaFile)MediaFile.Read ("/s" + extension, files).File!; + Assert.AreEqual ("LATER", again.Tag!.Album); + Assert.AreEqual ("Assigned", again.Tag!.Title); + } + + static (byte[] Bytes, string Extension) Fixture (string name) + { + if (name is "wav" or "aiff" or "avi") + return (RiffTagViewTests.Build (name), name == "aiff" ? ".aif" : "." + name); + if (name is ".ape" or ".wv" or ".mpc" or ".aac") + return (ApeTagItemOrderTests.Carrier (name, ApeTagItemOrderTests.Tag (true, ["Title=T", "Artist=A"])), name); + + var tagless = TaglessFixtures.All[name[1..]]; + var files = new MockFileSystem (); + var path = "/t" + tagless.Extension; + files.AddFile (path, tagless.Build ()); + using (var file = (IMediaFile)MediaFile.Read (path, files).File!) { + file.Tag!.Title = "T"; + file.Tag!.Artist = "A"; + Save (file, path, over: true, files); + } + + return (files.ReadAllBytes (path), tagless.Extension); + } + + static byte[] FreshHeld (byte[] source, string extension, string property, string emptying) + { + var files = new MockFileSystem (); + files.AddFile ("/s" + extension, source); + using var file = (IMediaFile)MediaFile.Read ("/s" + extension, files).File!; + var held = Held (file, property); + Empty (held, emptying); + held.Title = "LATER"; + Save (file, "/o" + extension, over: false, files); + return files.ReadAllBytes ("/o" + extension); + } + + static Tag Held (IMediaFile file, string property) => + (Tag)file.GetType ().GetProperty (property, BindingFlags.Public | BindingFlags.Instance)!.GetValue (file)!; + + static void Empty (Tag tag, string emptying) + { + if (emptying == "clear") { + tag.Clear (); + return; + } + + foreach (var property in typeof (Tag).GetProperties ().Where (p => p.CanWrite && p.GetSetMethod () is not null)) { + if (property.PropertyType == typeof (string) && property.GetValue (tag) is not null) + property.SetValue (tag, null); + else if (property.PropertyType == typeof (uint?) && property.GetValue (tag) is not null) + property.SetValue (tag, null); + else if (property.PropertyType == typeof (string[]) && property.GetValue (tag) is string[] { Length: > 0 }) + property.SetValue (tag, Array.Empty ()); + } + + tag.Pictures = []; + } + + static void Save (IMediaFile file, string path, bool over, MockFileSystem files) + { + dynamic typed = file; + FileWriteResult result = over ? typed.SaveToFile ((IFileSystem)files) : typed.SaveToFile (path, (IFileSystem)files); + Assert.IsTrue (result.IsSuccess, result.Error); + } +} From cb3f401a040b5690a59e56b96f0792121e3e60c5 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 10:04:28 -0700 Subject: [PATCH 12/12] test: Pin the order of pictures set on an ID3v2 tag on every carrier (#259) Review 1 saw the APIC frames of a WAV, AIFF or AAC file in a different place from a same-object save than from a fresh read's after Pictures = [back, front]. The cause is not the order: a picture is written into an ID3v2.3 tag with text encoding 3 (UTF-8), which ID3v2.3 does not define and which PictureFrame.Read rejects, so a fresh read of the saved file has no pictures and keeps the APIC frames as unread frames, written after the comments. That is #255, fixed on its own branch (fix/id3v23-encoding), which also reads such frames leniently and covers every other frame with an encoding byte. No order fix is needed here. Tests: Id3v2PictureOrderTests over {mp3, aac, wav, aiff, dsf, dff, mpg, avi} x {v2.3, v2.4}: Pictures = [back with a non-Latin-1 description, front with a Latin-1 one] reads back in that order with those descriptions, and the next save is the fresh read's. The 8 v2.3 rows fail until #255 is on main; the 8 v2.4 rows pass. With an APIC encoding fix applied (Latin-1 when the description fits, else UTF-16 with BOM, in a v2.3 tag) all 16 passed. --- .../Id3/Id3v2PictureOrderTests.cs | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2PictureOrderTests.cs diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2PictureOrderTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2PictureOrderTests.cs new file mode 100644 index 00000000..13b82e39 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2PictureOrderTests.cs @@ -0,0 +1,83 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mp4; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Id3; + +/// +/// Pictures set on an ID3v2 tag read back in the order given, in an ID3v2.3 tag as in an ID3v2.4 one, on every ID3v2 +/// carrier, and the next save from the object is the fresh read's (#259). The v2.3 rows fail until #255 is on main: a +/// picture is written into an ID3v2.3 tag with text encoding 3 (UTF-8), which ID3v2.3 does not define and which this +/// library's reader rejects, so a fresh read of the saved file has no pictures and writes the APIC frames after the +/// comments. #255 fixes the encoding; this test pins the property for every carrier. +/// +[TestClass] +[TestCategory ("Unit")] +public class Id3v2PictureOrderTests +{ + static readonly string[] Carriers = ["mp3", "aac", "wav", "aiff", "dsf", "dff", "mpg", "avi"]; + static readonly Id3v2Version[] Versions = [Id3v2Version.V23, Id3v2Version.V24]; + + public static IEnumerable Cases => + from carrier in Carriers + from version in Versions + select new object[] { carrier, (int)version }; + + static readonly PictureType[] ExpectedTypes = [PictureType.BackCover, PictureType.FrontCover]; + static readonly string[] ExpectedDescriptions = ["Back ☕", "Café"]; + + static readonly BinaryData Png = new ([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D]); + static readonly BinaryData Jpeg = new ([0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1]); + + [TestMethod] + [DynamicData (nameof (Cases))] + public void PicturesSet_ReadBackInTheOrderGiven_AndTheNextSaveIsTheFreshReadsSave (string carrier, int version) + { + var fixture = TaglessFixtures.All[carrier]; + var path = "/f" + fixture.Extension; + var files = new MockFileSystem (); + files.AddFile (path, WithId3 (carrier, (Id3v2Version)version)); + var file = (IMediaFile)MediaFile.Read (path, files).File!; + + file.Tag!.Pictures = [new Mp4Picture ("image/png", PictureType.BackCover, "Back ☕", Png), new Mp4Picture ("image/jpeg", PictureType.FrontCover, "Café", Jpeg)]; + Save (file, files); + + var cell = $"{carrier} v2.{version}"; + var reread = (IMediaFile)MediaFile.Read (path, files).File!; + CollectionAssert.AreEqual (ExpectedTypes, reread.Tag!.Pictures.Select (p => p.PictureType).ToArray (), cell); + CollectionAssert.AreEqual (ExpectedDescriptions, reread.Tag.Pictures.Select (p => p.Description).ToArray (), $"{cell}: descriptions, Latin-1 and not"); + + var fresh = new MockFileSystem (); + fresh.AddFile (path, files.ReadAllBytes (path)); + file.Tag.Title = "Later"; + Save (file, files); + var freshFile = (IMediaFile)MediaFile.Read (path, fresh).File!; + freshFile.Tag!.Title = "Later"; + Save (freshFile, fresh); + CollectionAssert.AreEqual (fresh.ReadAllBytes (path), files.ReadAllBytes (path), cell); + } + + /// The fixture with an ID3v2 tag of holding a title, saved by the library. + static byte[] WithId3 (string carrier, Id3v2Version version) + { + var fixture = TaglessFixtures.All[carrier]; + var path = "/build" + fixture.Extension; + var files = new MockFileSystem (); + files.AddFile (path, fixture.Build ()); + var file = MediaFile.Read (path, files).File!; + file.GetType ().GetProperty ("Id3v2Tag")!.SetValue (file, new Id3v2Tag (version) { Title = "Title", Comment = "Comment" }); + Save ((IMediaFile)file, files); + return files.ReadAllBytes (path); + } + + static void Save (IMediaFile file, MockFileSystem files) + { + dynamic typed = file; + FileWriteResult result = typed.SaveToFile ((IFileSystem)files); + Assert.IsTrue (result.IsSuccess, result.Error); + } +}