From 36846dc0d282eb88bb0fe34b41cb1058abec78a5 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:43:09 -0700 Subject: [PATCH 1/7] fix: Write ID3v2.3 frames in an encoding v2.3 defines, and read a v2.3 picture written in UTF-8 (#255) --- CHANGELOG.md | 1 + .../Id3/Id3v2/Frames/ChapterFrame.cs | 14 +- .../Id3/Id3v2/Frames/CommentFrame.cs | 19 +- .../Id3/Id3v2/Frames/GeneralObjectFrame.cs | 19 +- .../Id3/Id3v2/Frames/InvolvedPeopleFrame.cs | 21 +- .../Id3/Id3v2/Frames/LyricsFrame.cs | 19 +- .../Id3/Id3v2/Frames/PictureFrame.cs | 38 +- .../Id3/Id3v2/Frames/SyncLyricsFrame.cs | 19 +- .../Id3/Id3v2/Frames/TableOfContentsFrame.cs | 14 +- .../Id3/Id3v2/Frames/TextFrame.cs | 20 +- .../Id3/Id3v2/Frames/UserTextFrame.cs | 24 +- .../Id3/Id3v2/Frames/UserUrlFrame.cs | 17 +- src/TagLibSharp2/Id3/Id3v2/Id3Text.cs | 21 + src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 44 +- .../Id3/Id3v2/TextEncodingType.cs | 5 + .../Core/CustomFieldTests.cs | 6 +- .../Docs/AlbumArtSampleTests.cs | 117 ++++ .../Docs/DocExamplesCompileTests.cs | 41 ++ .../Id3/Id3v2/Frames/PictureFrameTests.cs | 23 +- .../Id3v2/Id3v2WrittenEncodingCarrierTests.cs | 128 +++++ .../Id3/Id3v2/Id3v2WrittenEncodingTests.cs | 521 ++++++++++++++++++ .../Id3/Id3v2/Utf16MultiStringTests.cs | 34 +- 22 files changed, 1060 insertions(+), 105 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Docs/AlbumArtSampleTests.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 72726dec..b080b706 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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 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/Id3/Id3v2/Frames/ChapterFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs index 35d532be..3c7823ec 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs @@ -180,14 +180,18 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); + + /// + /// Renders the frame content for a tag of : the embedded TIT2 is in an encoding that + /// version defines (). + /// + internal BinaryData RenderContent (Id3v2Version version) { // Render embedded TIT2 if title is set BinaryData? titleFrameData = null; - if (!string.IsNullOrEmpty (Title)) { - var titleFrame = new TextFrame ("TIT2", Title!, TextEncodingType.Utf8); - titleFrameData = titleFrame.RenderContent (); - } + if (!string.IsNullOrEmpty (Title)) + titleFrameData = new TextFrame ("TIT2", Title!).RenderContent (version); var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); var baseSize = elementIdBytes.Length + 1 + 16; // +1 for null, +16 for times/offsets diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs index 2bc05b42..91f5cd8f 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs @@ -109,18 +109,27 @@ public static CommentFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content including encoding byte, language, description, and text. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, Description, Text)); + + BinaryData Render (TextEncodingType encoding) { - var descriptionBytes = EncodeText (Description, Encoding); - var textBytes = EncodeText (Text, Encoding); - var terminatorSize = GetTerminatorSize (Encoding); + var descriptionBytes = EncodeText (Description, encoding); + var textBytes = EncodeText (Text, encoding); + var terminatorSize = GetTerminatorSize (encoding); var totalSize = 1 + LanguageSize + descriptionBytes.Length + terminatorSize + textBytes.Length; using var builder = new BinaryDataBuilder (totalSize); // Encoding byte - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); // Language (3 bytes, ASCII, padded with spaces) var langBytes = System.Text.Encoding.ASCII.GetBytes (NormalizeLanguage (Language)); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs index ad3f551a..efcb39d4 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs @@ -121,12 +121,21 @@ public static GeneralObjectFrameReadResult Read (ReadOnlySpan data, Id3v2V /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, FileName, Description)); + + BinaryData Render (TextEncodingType encoding) { var mimeTypeBytes = Polyfills.Latin1.GetBytes (MimeType); - var fileNameBytes = EncodeString (FileName, Encoding); - var descriptionBytes = EncodeString (Description, Encoding); - var terminatorSize = GetTerminatorSize (Encoding); + var fileNameBytes = EncodeString (FileName, encoding); + var descriptionBytes = EncodeString (Description, encoding); + var terminatorSize = GetTerminatorSize (encoding); var totalSize = 1 + mimeTypeBytes.Length + 1 + fileNameBytes.Length + terminatorSize + @@ -136,7 +145,7 @@ public BinaryData RenderContent () using var builder = new BinaryDataBuilder (totalSize); // Encoding - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); // MIME type (null-terminated) builder.Add (mimeTypeBytes); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs index 18b9c03c..54e1d745 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs @@ -264,11 +264,20 @@ public static InvolvedPeopleFrameReadResult Read (string frameId, ReadOnlySpan /// The frame content including encoding byte. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, [.. _pairs.SelectMany (pair => new[] { pair.Role, pair.Person })])); + + BinaryData Render (TextEncodingType encoding) { if (_pairs.Count == 0) { using var emptyBuilder = new BinaryDataBuilder (1); - emptyBuilder.Add ((byte)Encoding); + emptyBuilder.Add ((byte)encoding); return emptyBuilder.ToBinaryData (); } @@ -281,13 +290,13 @@ public BinaryData RenderContent () // Build the content - encode directly without intermediate list using var builder = new BinaryDataBuilder (estimatedSize); - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); - var terminator = GetTerminatorBytes (Encoding); + var terminator = GetTerminatorBytes (encoding); for (var i = 0; i < _pairs.Count; i++) { - builder.Add (EncodeText (_pairs[i].Role, Encoding)); + builder.Add (EncodeText (_pairs[i].Role, encoding)); builder.Add (terminator); - builder.Add (EncodeText (_pairs[i].Person, Encoding)); + builder.Add (EncodeText (_pairs[i].Person, encoding)); builder.Add (terminator); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs index 9f40be57..e8a87926 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs @@ -109,18 +109,27 @@ public static LyricsFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content including encoding byte, language, description, and lyrics. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, Description, Text)); + + BinaryData Render (TextEncodingType encoding) { - var descriptionBytes = EncodeText (Description, Encoding); - var textBytes = EncodeText (Text, Encoding); - var terminatorSize = GetTerminatorSize (Encoding); + var descriptionBytes = EncodeText (Description, encoding); + var textBytes = EncodeText (Text, encoding); + var terminatorSize = GetTerminatorSize (encoding); var totalSize = 1 + LanguageSize + descriptionBytes.Length + terminatorSize + textBytes.Length; using var builder = new BinaryDataBuilder (totalSize); // Encoding byte - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); // Language (3 bytes, ASCII, padded with spaces) var langBytes = System.Text.Encoding.ASCII.GetBytes (NormalizeLanguage (Language)); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs index 2e3a08b6..dab28f54 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs @@ -76,7 +76,8 @@ public sealed class PictureFrame : Picture /// A description of the image. Use empty string if no description is needed. /// /// The raw image data. - /// The text encoding for the description. Defaults to UTF-8. + /// The text encoding for the description. Defaults to UTF-8, which an ID3v2.3 tag writes as one + /// that version defines (). /// /// Thrown when , , /// or is null. @@ -101,7 +102,8 @@ public PictureFrame (string mimeType, PictureType pictureType, string descriptio /// A description of the image. Use empty string if no description is needed. /// /// The raw image data as . - /// The text encoding for the description. Defaults to UTF-8. + /// The text encoding for the description. Defaults to UTF-8, which an ID3v2.3 tag writes as one + /// that version defines (). /// /// Thrown when or is null. /// @@ -196,7 +198,7 @@ public static PictureFrame FromFile (string path, PictureType pictureType = Pict /// Common failure reasons: /// /// Data too short (less than 4 bytes) - /// Invalid text encoding byte for the version + /// Invalid text encoding byte (above 3) /// MIME type not null-terminated /// /// @@ -207,13 +209,10 @@ public static PictureFrameReadResult Read (ReadOnlySpan data, Id3v2Version var offset = 0; - // Text encoding - validate based on version + // ID3v2.3 defines only encodings 0 (Latin1) and 1 (UTF-16 with BOM), and ID3v2.4 adds 2 (UTF-16BE) and 3 + // (UTF-8). A v2.3 picture in 2 or 3 is read as the other v2.3 frames are, so a picture written that way (as this + // library wrote one before #255) shows; a save writes it in an encoding v2.3 defines (Id3Text.WrittenEncoding). var encodingByte = data[offset++]; - - // ID3v2.3 only supports encodings 0 (Latin1) and 1 (UTF-16 with BOM) - // ID3v2.4 adds encodings 2 (UTF-16BE) and 3 (UTF-8) - if (version == Id3v2Version.V23 && encodingByte > 1) - return PictureFrameReadResult.Failure ($"Invalid text encoding for ID3v2.3: {encodingByte} (only 0-1 allowed)"); if (encodingByte > 3) return PictureFrameReadResult.Failure ($"Invalid text encoding: {encodingByte}"); @@ -319,11 +318,20 @@ static bool StartsWithImageMimeType (ReadOnlySpan afterEncoding) => /// The returned data does NOT include the frame header (frame ID + size + flags). /// Use to create a complete tag with frame headers. /// - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (TextEncoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (TextEncoding, version, Description)); + + BinaryData Render (TextEncodingType encoding) { var mimeBytes = System.Text.Encoding.ASCII.GetBytes (MimeType); - var descBytes = EncodeString (Description, TextEncoding); - var nullSize = GetNullTerminatorSize (TextEncoding); + var descBytes = EncodeString (Description, encoding); + var nullSize = GetNullTerminatorSize (encoding); // Calculate total size var totalSize = 1 + // encoding @@ -333,13 +341,13 @@ public BinaryData RenderContent () PictureData.Length; // image data // Add BOM size for UTF-16 - if (TextEncoding == TextEncodingType.Utf16WithBom) + if (encoding == TextEncodingType.Utf16WithBom) totalSize += 2; using var builder = new BinaryDataBuilder (totalSize); // Encoding byte - builder.Add ((byte)TextEncoding); + builder.Add ((byte)encoding); // MIME type (null-terminated) builder.Add (mimeBytes); @@ -349,7 +357,7 @@ public BinaryData RenderContent () builder.Add ((byte)PictureType); // Description with BOM if UTF-16 - if (TextEncoding == TextEncodingType.Utf16WithBom) { + if (encoding == TextEncodingType.Utf16WithBom) { builder.Add (0xFF); builder.Add (0xFE); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs index 794cd61b..50919501 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs @@ -276,12 +276,21 @@ public static SyncLyricsFrameReadResult Read (ReadOnlySpan data, Id3v2Vers /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, [Description, .. _syncItems.Select (item => item.Text)])); + + BinaryData Render (TextEncodingType encoding) { using var builder = new BinaryDataBuilder (); // Encoding - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); // Language (3 bytes) var normalizedLang = NormalizeLanguage (Language); @@ -297,14 +306,14 @@ public BinaryData RenderContent () builder.Add ((byte)ContentType); // Description (null-terminated) - var descBytes = EncodeString (Description, Encoding); - var terminatorSize = GetTerminatorSize (Encoding); + var descBytes = EncodeString (Description, encoding); + var terminatorSize = GetTerminatorSize (encoding); builder.Add (descBytes); builder.AddZeros (terminatorSize); // Synchronized items foreach (var item in _syncItems) { - var textBytes = EncodeString (item.Text, Encoding); + var textBytes = EncodeString (item.Text, encoding); builder.Add (textBytes); builder.AddZeros (terminatorSize); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs index 6a02d6ed..899e8183 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs @@ -203,14 +203,18 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); + + /// + /// Renders the frame content for a tag of : the embedded TIT2 is in an encoding that + /// version defines (). + /// + internal BinaryData RenderContent (Id3v2Version version) { // Render embedded TIT2 if title is set BinaryData? titleFrameData = null; - if (!string.IsNullOrEmpty (Title)) { - var titleFrame = new TextFrame ("TIT2", Title!, TextEncodingType.Utf8); - titleFrameData = titleFrame.RenderContent (); - } + if (!string.IsNullOrEmpty (Title)) + titleFrameData = new TextFrame ("TIT2", Title!).RenderContent (version); var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs index aaad333f..c6fdfae1 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -86,14 +86,24 @@ public static TextFrameReadResult Read (string frameId, ReadOnlySpan data, /// Renders the frame content to binary data. /// /// The frame content including encoding byte. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => Render (Id3Text.WrittenEncoding (Encoding, version, Text)); + + BinaryData Render (TextEncodingType encoding) { - var textBytes = Encoding == TextEncodingType.Utf16WithBom - ? Utf16Text.Encode (Text, Utf16Layout) - : EncodeText (Text, Encoding); + // A value written in UTF-16 that was held in another encoding has no layout of its own; it gets a BOM before + // every string, as ID3v2.3 §3.3 asks. + var textBytes = encoding == TextEncodingType.Utf16WithBom + ? Utf16Text.Encode (Text, encoding == Encoding ? Utf16Layout : Utf16Layout.BomOnEvery) + : EncodeText (Text, encoding); using var builder = new BinaryDataBuilder (1 + textBytes.Length); - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); builder.Add (textBytes); return builder.ToBinaryData (); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs index 51d7a216..8f688fb7 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -117,16 +117,26 @@ public static UserTextFrameReadResult Read (ReadOnlySpan data, Id3v2Versio /// Renders the frame content to binary data. /// /// The frame content including encoding byte, description, null terminator, and value. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, Description, Value)); + + BinaryData Render (TextEncodingType encoding) { - var descriptionBytes = EncodeText (Description, Encoding); - var terminatorBytes = GetTerminatorBytes (Encoding); - var valueBytes = Encoding == TextEncodingType.Utf16WithBom - ? Utf16Text.Encode (Value, Utf16Layout) - : EncodeText (Value, Encoding); + var descriptionBytes = EncodeText (Description, encoding); + var terminatorBytes = GetTerminatorBytes (encoding); + // As in TextFrame: a value newly written in UTF-16 gets a BOM before every string (ID3v2.3 §3.3). + var valueBytes = encoding == TextEncodingType.Utf16WithBom + ? Utf16Text.Encode (Value, encoding == Encoding ? Utf16Layout : Utf16Layout.BomOnEvery) + : EncodeText (Value, encoding); using var builder = new BinaryDataBuilder (1 + descriptionBytes.Length + terminatorBytes.Length + valueBytes.Length); - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); builder.Add (descriptionBytes); builder.Add (terminatorBytes); builder.Add (valueBytes); diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs index 06c457e2..9535df40 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs @@ -90,17 +90,26 @@ public static UserUrlFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () + public BinaryData RenderContent () => Render (Encoding); + + /// + /// Renders the frame content for a tag of , in an encoding that version defines + /// (). + /// + internal BinaryData RenderContent (Id3v2Version version) => + Render (Id3Text.WrittenEncoding (Encoding, version, Description)); + + BinaryData Render (TextEncodingType encoding) { - var descriptionBytes = EncodeDescription (Description, Encoding); + var descriptionBytes = EncodeDescription (Description, encoding); var urlBytes = Polyfills.Latin1.GetBytes (Url); - var terminatorSize = GetTerminatorSize (Encoding); + var terminatorSize = GetTerminatorSize (encoding); var totalSize = 1 + descriptionBytes.Length + terminatorSize + urlBytes.Length; using var builder = new BinaryDataBuilder (totalSize); - builder.Add ((byte)Encoding); + builder.Add ((byte)encoding); builder.Add (descriptionBytes); builder.AddZeros (terminatorSize); builder.Add (urlBytes); diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs index dc927aa2..df2c3bab 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -54,6 +54,27 @@ internal static ReadOnlySpan CutAtFirstNul (ReadOnlySpan data, TextE /// The one UTF-16 decoder, , does the work. internal static string DecodeUtf16BomText (ReadOnlySpan data) => Frames.Utf16Text.Decode (data); + /// + /// The encoding a frame asking for is written with in a tag of . + /// ID3v2.4 defines all four encodings (https://id3.org/id3v2.4.0-structure §4). ID3v2.3 defines only $00 ISO-8859-1 + /// and $01 UTF-16 with a BOM (https://id3.org/id3v2.3.0 §3.3), so there a frame asking for UTF-16BE or UTF-8 is written + /// in ISO-8859-1 when every one of its fits, and in UTF-16 with a BOM otherwise. + /// + internal static TextEncodingType WrittenEncoding (TextEncodingType encoding, Id3v2Version version, params string[] texts) + { + if (version >= Id3v2Version.V24 || encoding is TextEncodingType.Latin1 or TextEncodingType.Utf16WithBom) + return encoding; + + foreach (var text in texts) { + foreach (var c in text) { + if (c > '\u00FF') + return TextEncodingType.Utf16WithBom; + } + } + + return TextEncodingType.Latin1; + } + static int IndexOfUtf16Nul (ReadOnlySpan data) { for (var i = 0; i + 1 < data.Length; i += 2) { diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index e78df124..1425b426 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -32,7 +32,7 @@ namespace TagLibSharp2.Id3.Id3v2; /// /// Reading basic metadata: /// -/// var tag = mp3File.Tag; +/// var tag = mp3File.Id3v2Tag!; /// Console.WriteLine($"Title: {tag.Title}"); /// Console.WriteLine($"Artist: {tag.Artist}"); /// Console.WriteLine($"Album: {tag.Album}"); @@ -45,7 +45,7 @@ namespace TagLibSharp2.Id3.Id3v2; /// Console.WriteLine($"Type: {picture.PictureType}, Size: {picture.PictureData.Length}"); /// } /// // Add a new picture -/// tag.Pictures = [.. tag.Pictures, new PictureFrame(coverArtBytes, "image/jpeg", PictureType.FrontCover)]; +/// tag.Pictures = [.. tag.Pictures, new PictureFrame("image/jpeg", PictureType.FrontCover, "", coverArtBytes)]; /// /// /// Working with user-defined text frames (TXXX): @@ -54,13 +54,13 @@ namespace TagLibSharp2.Id3.Id3v2; /// var customTag = tag.UserTextFrames.FirstOrDefault(f => f.Description == "CUSTOM_FIELD"); /// /// // Add/update custom tag -/// tag.SetUserTextFrame("CUSTOM_FIELD", "custom value"); +/// tag.SetUserText("CUSTOM_FIELD", "custom value"); /// /// /// Working with comments (COMM): /// /// // Add a comment -/// tag.Comments = [.. tag.Comments, new CommentFrame("eng", "My comment text", "Comment description")]; +/// tag.AddComment(new CommentFrame("My comment text", "eng", "Comment description")); /// /// /// Copying tags between files: @@ -1887,12 +1887,15 @@ public void RemoveAllPictures () /// The rendered tag data. public BinaryData Render (int paddingSize, bool withFooter = false) { + // Every frame with a text encoding is written in one this version defines (Id3Text.WrittenEncoding). + var version = (Id3v2Version)WrittenVersion; + // Render all frames and calculate size in single pass var frameDataList = new List ((_frames.Count + _pictures.Count + _comments.Count) * 2); var framesSize = 0; for (var i = 0; i < _frames.Count; i++) { - var content = _frames[i].RenderContent (); + var content = _frames[i].RenderContent (version); var frameHeader = RenderFrameHeader (_frames[i].Id, content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1901,7 +1904,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render picture frames for (var i = 0; i < _pictures.Count; i++) { - var content = _pictures[i].RenderContent (); + var content = _pictures[i].RenderContent (version); var frameHeader = RenderFrameHeader ("APIC", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1910,7 +1913,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render comment frames for (var i = 0; i < _comments.Count; i++) { - var content = _comments[i].RenderContent (); + var content = _comments[i].RenderContent (version); var frameHeader = RenderFrameHeader ("COMM", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1919,7 +1922,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render user-defined text frames (TXXX) for (var i = 0; i < _userTextFrames.Count; i++) { - var content = _userTextFrames[i].RenderContent (); + var content = _userTextFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("TXXX", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1928,7 +1931,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render lyrics frames (USLT) for (var i = 0; i < _lyricsFrames.Count; i++) { - var content = _lyricsFrames[i].RenderContent (); + var content = _lyricsFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("USLT", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1946,7 +1949,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render involved people frames (TIPL, TMCL) for (var i = 0; i < _involvedPeopleFrames.Count; i++) { - var content = _involvedPeopleFrames[i].RenderContent (); + var content = _involvedPeopleFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader (_involvedPeopleFrames[i].Id, content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1973,7 +1976,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render user URL frames (WXXX) for (var i = 0; i < _userUrlFrames.Count; i++) { - var content = _userUrlFrames[i].RenderContent (); + var content = _userUrlFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("WXXX", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1982,7 +1985,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render synchronized lyrics frames (SYLT) for (var i = 0; i < _syncLyricsFrames.Count; i++) { - var content = _syncLyricsFrames[i].RenderContent (); + var content = _syncLyricsFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("SYLT", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -1991,7 +1994,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render general encapsulated object frames (GEOB) for (var i = 0; i < _generalObjectFrames.Count; i++) { - var content = _generalObjectFrames[i].RenderContent (); + var content = _generalObjectFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("GEOB", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -2009,7 +2012,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render chapter frames (CHAP) for (var i = 0; i < _chapterFrames.Count; i++) { - var content = _chapterFrames[i].RenderContent (); + var content = _chapterFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("CHAP", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -2018,7 +2021,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render table of contents frames (CTOC) for (var i = 0; i < _tableOfContentsFrames.Count; i++) { - var content = _tableOfContentsFrames[i].RenderContent (); + var content = _tableOfContentsFrames[i].RenderContent (version); var frameHeader = RenderFrameHeader ("CTOC", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -2318,9 +2321,9 @@ public override IReadOnlyList GetCustomField (string name) /// (https://id3.org/id3v2.4.0-structure §4). /// /// - /// An ID3v2.4 tag writes UTF-8. An older tag writes UTF-16 with a byte order mark, because ID3v2.3 - /// defines only ISO-8859-1 and UCS-2 text (https://id3.org/id3v2.3.0 §3.3). ID3v2.3 has no multiple-value - /// text: a reader that follows it strictly shows only the first value. + /// An ID3v2.4 tag writes UTF-8. An older tag writes ISO-8859-1 when the text fits and UTF-16 with a byte order + /// mark otherwise, because ID3v2.3 defines only ISO-8859-1 and UCS-2 text (https://id3.org/id3v2.3.0 §3.3). ID3v2.3 + /// has no multiple-value text: a reader that follows it strictly shows only the first value. /// /// public override bool SetCustomField (string name, params string[] values) @@ -2335,9 +2338,8 @@ public override bool SetCustomField (string name, params string[] values) if (kept.Count == 0) return true; - var encoding = Version >= 4 ? TextEncodingType.Utf8 : TextEncodingType.Utf16WithBom; - // ID3v2.3 §3.3: every Unicode string begins with a BOM. - var frame = new UserTextFrame (name, string.Join ("\0", kept), encoding) { Utf16Layout = Utf16Layout.BomOnEvery }; + // Written in an encoding the tag's version defines (Id3Text.WrittenEncoding). + var frame = new UserTextFrame (name, string.Join ("\0", kept)); _userTextFrames.Insert (at < 0 ? _userTextFrames.Count : at, frame); return true; } diff --git a/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs b/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs index 9f2676a8..8a073ef2 100644 --- a/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs +++ b/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs @@ -8,6 +8,11 @@ namespace TagLibSharp2.Id3.Id3v2; /// /// Text encoding types used in ID3v2 frames. /// +/// +/// A frame keeps the encoding it was given, and a tag writes it in one its version defines: an ID3v2.3 tag, and a +/// v2.2 tag, which is written as v2.3, writes a frame that asks for or in +/// when its text fits and in otherwise (https://id3.org/id3v2.3.0 §3.3). +/// [SuppressMessage ("Design", "CA1028:Enum storage should be Int32", Justification = "Matches ID3v2 spec single-byte encoding field")] public enum TextEncodingType : byte { diff --git a/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs index 3e8cb8f5..fb87ec66 100644 --- a/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs +++ b/tests/TagLibSharp2.Tests/Core/CustomFieldTests.cs @@ -473,8 +473,10 @@ public void Id3v23_WritesUtf16 () tag.SetCustomField ("My Field", "日本"); - Assert.AreEqual (TextEncodingType.Utf16WithBom, tag.UserTextFrames[0].Encoding); - var again = Id3v2Tag.Read (tag.Render ().Span).Tag!; + var rendered = tag.Render ().ToArray (); + var txxx = TagLibSharp2.Tests.Id3.Id3v2.Id3v2WrittenEncodingTests.WrittenFrames (rendered).Single (f => f.Id == "TXXX").Body; + Assert.AreEqual ((byte)TextEncodingType.Utf16WithBom, txxx[0]); + var again = Id3v2Tag.Read (rendered).Tag!; Assert.AreEqual (3, again.Version); AssertValues (again.GetCustomField ("My Field"), "日本"); } diff --git a/tests/TagLibSharp2.Tests/Docs/AlbumArtSampleTests.cs b/tests/TagLibSharp2.Tests/Docs/AlbumArtSampleTests.cs new file mode 100644 index 00000000..62bdf41b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Docs/AlbumArtSampleTests.cs @@ -0,0 +1,117 @@ +// 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.Id3.Id3v2.Frames; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Id3.Id3v2; + +namespace TagLibSharp2.Tests.Docs; + +/// +/// The "add album art" samples of the QuickStart, the Cookbook and the migration guide, run on an MP3 with no tag and +/// with an ID3v2.2, 2.3 and 2.4 tag: the pictures they add read back from the saved file (issue #255), and every +/// encoding byte written is one the tag's version defines. The file system is a mock; otherwise the code is the +/// sample's. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +public class AlbumArtSampleTests +{ + static readonly byte[] CoverJpg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 0xFF, 0xD9]; + static readonly byte[] BackJpg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 2, 0xFF, 0xD9]; + + public enum Sample + { + QuickStart, + Cookbook, + Migration, + } + + public static IEnumerable Rows => + from sample in Enum.GetValues () + from version in new Id3v2Version?[] { null, Id3v2Version.V22, Id3v2Version.V23, Id3v2Version.V24 } + select new object?[] { sample, version }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void AddAlbumArtSample_SavedPicturesReadBack (Sample sample, Id3v2Version? sourceTag) + { + var fs = new MockFileSystem (); + fs.AddFile ("song.mp3", Mp3 (sourceTag)); + + var result = Mp3File.ReadFromFile ("song.mp3", fs); + Assert.IsTrue (result.IsSuccess, result.Error); + var mp3 = result.File!; + var imageBytes = CoverJpg; + switch (sample) { + case Sample.QuickStart: { + // docs/QuickStart.md, "Adding Album Art" + var picture = new PictureFrame ( + "image/jpeg", + PictureType.FrontCover, + "Album Cover", + imageBytes); + + var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag (); + id3v2.AddPicture (picture); + break; + } + case Sample.Cookbook: { + // docs/Cookbook.md, "Add Album Art to MP3" + var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag (); + var picture = new PictureFrame ( + "image/jpeg", + PictureType.FrontCover, + "Album Cover", + imageBytes); + + id3v2.AddPicture (picture); + + var backCover = new PictureFrame ( + "image/jpeg", + PictureType.BackCover, + "Back Cover", + BackJpg); + id3v2.AddPicture (backCover); + break; + } + default: { + // docs/MIGRATION-FROM-TAGLIB.md, album art, "TagLibSharp2 (ID3v2)" + var picture = new PictureFrame ( + "image/jpeg", + PictureType.FrontCover, + "Album Art", + new BinaryData (imageBytes)); + + var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag (); + id3v2.AddPicture (picture); + break; + } + } + Assert.IsTrue (mp3.SaveToFile (fs).IsSuccess); + + var saved = fs.ReadAllBytes ("song.mp3"); + var reread = Mp3File.ReadFromFile ("song.mp3", fs).File!; + var pictures = reread.Id3v2Tag!.Pictures; + var expected = sample switch { + Sample.QuickStart => "FrontCover:Album Cover:" + CoverJpg.Length, + Sample.Cookbook => "FrontCover:Album Cover:" + CoverJpg.Length + "|BackCover:Back Cover:" + BackJpg.Length, + _ => "FrontCover:Album Art:" + CoverJpg.Length, + }; + Assert.AreEqual (expected, string.Join ("|", pictures.Select (p => $"{p.PictureType}:{p.Description}:{p.PictureData.Length}"))); + CollectionAssert.AreEqual (CoverJpg, pictures[0].PictureData.ToArray ()); + var defined = saved[3] == 4 ? 3 : 1; + foreach (var (id, body) in Id3v2WrittenEncodingTests.WrittenFrames (saved).Where (f => f.Id == "APIC")) + Assert.IsLessThanOrEqualTo (defined, (int)body[0], $"{id} encoding byte in a v2.{saved[3]} tag"); + } + + // An MP3 with an ID3v2 tag of the version, holding only padding, or with no tag at all. + static byte[] Mp3 (Id3v2Version? version) => + version is { } v + ? [.. TestBuilders.Id3v2.CreateHeader ((byte)v, 64), .. new byte[64], .. new byte[256]] + : new byte[256]; +} diff --git a/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs b/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs index c3ea59ca..5e05b3e4 100644 --- a/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs +++ b/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs @@ -44,6 +44,47 @@ public void QuickStart_FormatSpecificAccess_Compiles () Assert.IsNotNull (typeof (OggVorbisFile).GetMethod ("ReadFromFile", new[] { typeof (string), typeof (IFileSystem), typeof (bool) })); } + // Id3v2Tag class documentation : the snippets run on an MP3 with an ID3v2.3 tag, and what they write reads + // back (the picture snippet had its arguments in the wrong order, #255). + [TestMethod] + public void Id3v2TagClassExample_RunsAndReadsBack () + { + byte[] coverArtBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0xFF, 0xD9]; + byte[] bytes = [.. TestBuilders.Id3v2.CreateHeader (3, 32), .. new byte[32], .. new byte[256]]; + var mp3File = Mp3File.Read (bytes).File!; + var sourceTag = new Id3v2Tag (Id3v2Version.V24) { Title = "Copied" }; + var destinationTag = mp3File.Id3v2Tag!; + + // Reading basic metadata + var tag = mp3File.Id3v2Tag!; + Console.WriteLine ($"Title: {tag.Title}"); + Console.WriteLine ($"Artist: {tag.Artist}"); + Console.WriteLine ($"Album: {tag.Album}"); + // Accessing pictures + foreach (var picture in tag.Pictures) { + Console.WriteLine ($"Type: {picture.PictureType}, Size: {picture.PictureData.Length}"); + } + // Add a new picture + tag.Pictures = [.. tag.Pictures, new PictureFrame ("image/jpeg", PictureType.FrontCover, "", coverArtBytes)]; + // Read custom tag + var customTag = tag.UserTextFrames.FirstOrDefault (f => f.Description == "CUSTOM_FIELD"); + // Add/update custom tag + tag.SetUserText ("CUSTOM_FIELD", "custom value"); + // Add a comment + tag.AddComment (new CommentFrame ("My comment text", "eng", "Comment description")); + // Copy all metadata from source to destination + sourceTag.CopyTo (destinationTag); + + Assert.IsNull (customTag); + var again = Mp3File.Read (mp3File.Render (bytes).Span).File!.Id3v2Tag!; + Assert.AreEqual (3, again.Version); + Assert.AreEqual ("Copied", again.Title); + Assert.HasCount (1, again.Pictures); + CollectionAssert.AreEqual (coverArtBytes, again.Pictures[0].PictureData.ToArray ()); + Assert.AreEqual ("custom value", again.GetUserText ("CUSTOM_FIELD")); + Assert.AreEqual ("Comment description=My comment text", again.Comments[0].Description + "=" + again.Comments[0].Text); + } + // QuickStart.md - BatchProcessor example [TestMethod] public void QuickStart_BatchProcessor_Compiles () diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs index 3de5a0c0..7126ce57 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Frames/PictureFrameTests.cs @@ -261,28 +261,31 @@ public void Read_InvalidEncodingV24_ReturnsFailure () StringAssert.Contains (result.Error!, "Invalid text encoding"); } + // ID3v2.3 defines only encodings 0 and 1, but a v2.3 picture in UTF-8 or UTF-16BE (as this library wrote one + // before #255) is read, as the other v2.3 frames are. [TestMethod] - public void Read_Utf8InV23_ReturnsFailure () + public void Read_Utf8InV23_ReadsLeniently () { - // UTF-8 (0x03) is not valid in ID3v2.3 - only Latin1 and UTF-16 with BOM - var data = new byte[] { 0x03, (byte)'i', (byte)'m', (byte)'g', 0x00, 0x03, 0x00, 0x01 }; + var data = new byte[] { 0x03, (byte)'i', (byte)'m', (byte)'g', 0x00, 0x03, 0xC3, 0xA9, 0x00, 0x01 }; var result = PictureFrame.Read (data, Id3v2Version.V23); - Assert.IsFalse (result.IsSuccess); - StringAssert.Contains (result.Error!, "Invalid text encoding for ID3v2.3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("\u00E9", result.Frame!.Description); + Assert.AreEqual (TextEncodingType.Utf8, result.Frame.TextEncoding); + CollectionAssert.AreEqual (new byte[] { 0x01 }, result.Frame.PictureData.ToArray ()); } [TestMethod] - public void Read_Utf16BEInV23_ReturnsFailure () + public void Read_Utf16BEInV23_ReadsLeniently () { - // UTF-16BE (0x02) is not valid in ID3v2.3 - var data = new byte[] { 0x02, (byte)'i', (byte)'m', (byte)'g', 0x00, 0x03, 0x00, 0x00, 0x01 }; + var data = new byte[] { 0x02, (byte)'i', (byte)'m', (byte)'g', 0x00, 0x03, 0x00, 0xE9, 0x00, 0x00, 0x01 }; var result = PictureFrame.Read (data, Id3v2Version.V23); - Assert.IsFalse (result.IsSuccess); - StringAssert.Contains (result.Error!, "Invalid text encoding for ID3v2.3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("\u00E9", result.Frame!.Description); + CollectionAssert.AreEqual (new byte[] { 0x01 }, result.Frame.PictureData.ToArray ()); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs new file mode 100644 index 00000000..751c546d --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs @@ -0,0 +1,128 @@ +// 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.Id3.Id3v2.Frames; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Pictures and text added to the ID3v2 tag of every format that carries one (MP3, raw AAC, MPEG-PS, WAV, AIFF, DSF, +/// DFF and AVI) read back in order from the saved file, and every encoding byte written is one the tag's version +/// defines: ISO-8859-1 or UTF-16 with a BOM in ID3v2.3, the frame's own UTF-8 in ID3v2.4 (issue #255). Each carrier +/// is saved by every save entry point it has: its span render, path save with the original bytes (sync and async), path +/// save from its source (sync and async), and in-place save (sync and async). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2WrittenEncodingCarrierTests +{ + static readonly byte[] Front = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 0xFF, 0xD9]; + static readonly byte[] Back = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 2, 0xFF, 0xD9]; + + static readonly string[] Saves = ["render", "path-with-data", "async-path-with-data", "path", "async-path", "in-place", "async-in-place"]; + static readonly byte[] Versions = [3, 4]; + static readonly string[] Texts = ["Cover", "日本語"]; + + public static IEnumerable Rows => + from format in Id3v22CarrierBuilder.Formats + from version in Versions + from text in Texts + from save in Saves + // WAV and AIFF have no save that takes the original bytes. + where !(format.Format is "wav" or "aiff" && save.EndsWith ("with-data", StringComparison.Ordinal)) + select new object[] { format.Format, format.Extension, version, text, save }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task Save_PicturesAndTitleInCarrier_ReadBackInOrderWithTheVersionsEncoding (string format, string extension, byte version, string text, string save) + { + var original = Id3v22CarrierBuilder.Build (format, [.. TestBuilders.Id3v2.CreateHeader (version, 16), .. new byte[16]]); + var files = new MockFileSystem (); + var name = "/file" + extension; + files.AddFile (name, original); + var read = save == "render" ? MediaFile.ReadFromData (original, name) : MediaFile.Read (name, files); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + var id3 = Id3v22CarrierBuilder.Id3 (file)!; + Assert.AreEqual (version, id3.Version, "source tag version"); + + id3.Title = text; + id3.AddPicture (new PictureFrame ("image/jpeg", PictureType.FrontCover, text, Front)); + id3.AddPicture (new PictureFrame ("image/jpeg", PictureType.BackCover, "Back", Back)); + var saved = await SaveAsync (file, original, files, name, save); + + var reread = MediaFile.ReadFromData (saved, name); + Assert.IsTrue (reread.IsSuccess, reread.Error); + var tag = Id3v22CarrierBuilder.Id3 (reread.File!)!; + Assert.AreEqual (text, tag.Title); + Assert.AreEqual ($"FrontCover:{text}:{Front.Length}|BackCover:Back:{Back.Length}", + string.Join ("|", tag.Pictures.Select (p => $"{p.PictureType}:{p.Description}:{p.PictureData.Length}"))); + CollectionAssert.AreEqual (Back, tag.Pictures[1].PictureData.ToArray ()); + + var written = WrittenTag (saved); + Assert.AreEqual (version, written[3], "written version"); + var expected = version == 4 ? (byte)TextEncodingType.Utf8 + : text == "Cover" ? (byte)TextEncodingType.Latin1 : (byte)TextEncodingType.Utf16WithBom; + foreach (var (id, body) in Id3v2WrittenEncodingTests.WrittenFrames (written).Where (f => f.Id is "TIT2" || f.Id == "APIC" && f.Body.AsSpan ().IndexOf (System.Text.Encoding.ASCII.GetBytes ("Back")) < 0)) + Assert.AreEqual (expected, body[0], id + " encoding byte"); + } + + static async Task SaveAsync (IMediaFile file, byte[] original, MockFileSystem files, string name, string save) + { + if (save == "render") + return SkipPicturesFixtures.Render (file, original)!; + + var type = file.GetType (); + var result = save switch { + "path-with-data" => file switch { + TagLibSharp2.Mpeg.Mp3File f => f.SaveToFile ("/out", original, files), + TagLibSharp2.Aac.AacFile f => f.SaveToFile ("/out", original, files), + TagLibSharp2.Mpeg.MpegPsFile f => f.SaveToFile ("/out", original, files), + TagLibSharp2.Dsf.DsfFile f => f.SaveToFile ("/out", original, files), + TagLibSharp2.Dff.DffFile f => f.SaveToFile ("/out", original, files), + TagLibSharp2.Riff.AviFile f => f.SaveToFile ("/out", original, files), + _ => throw new ArgumentException (type.Name), + }, + "async-path-with-data" => await (file switch { + TagLibSharp2.Mpeg.Mp3File f => f.SaveToFileAsync ("/out", original, files), + TagLibSharp2.Aac.AacFile f => f.SaveToFileAsync ("/out", original, files), + TagLibSharp2.Mpeg.MpegPsFile f => f.SaveToFileAsync ("/out", original, files), + TagLibSharp2.Dsf.DsfFile f => f.SaveToFileAsync ("/out", original, files), + TagLibSharp2.Dff.DffFile f => f.SaveToFileAsync ("/out", original, files), + TagLibSharp2.Riff.AviFile f => f.SaveToFileAsync ("/out", original, files), + _ => throw new ArgumentException (type.Name), + }), + "path" => (FileWriteResult)type.GetMethod ("SaveToFile", [typeof (string), typeof (IFileSystem)])!.Invoke (file, ["/out", files])!, + "async-path" => await (Task)type.GetMethod ("SaveToFileAsync", [typeof (string), typeof (IFileSystem), typeof (CancellationToken)])! + .Invoke (file, ["/out", files, CancellationToken.None])!, + "async-in-place" => await (Task)type.GetMethod ("SaveToFileAsync", [typeof (IFileSystem), typeof (CancellationToken)])! + .Invoke (file, [files, CancellationToken.None])!, + // SaveToFile (fileSystem), or, for WAV and AIFF, which have none, a path save over the source. + _ => type.GetMethod ("SaveToFile", [typeof (IFileSystem)]) is { } inPlace + ? (FileWriteResult)inPlace.Invoke (file, [files])! + : (FileWriteResult)type.GetMethod ("SaveToFile", [typeof (string), typeof (IFileSystem)])!.Invoke (file, [name, files])!, + }; + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes (save.EndsWith ("in-place", StringComparison.Ordinal) ? name : "/out"); + } + + /// The ID3v2.3 or ID3v2.4 tag in a saved carrier. + static byte[] WrittenTag (byte[] file) + { + for (var at = file.AsSpan ().IndexOf ("ID3"u8); at >= 0;) { + if (file[at + 3] is 3 or 4 && file[at + 4] == 0) { + var size = Id3v2Header.Read (file.AsSpan (at)).Header.TotalSize; + return file.AsSpan (at, (int)size).ToArray (); + } + var next = file.AsSpan (at + 1).IndexOf ("ID3"u8); + at = next < 0 ? -1 : at + 1 + next; + } + Assert.Fail ("no ID3v2.3 or v2.4 tag in the saved file"); + return []; + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs new file mode 100644 index 00000000..3815a032 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs @@ -0,0 +1,521 @@ +// 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.Id3.Id3v2.Frames; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// Every frame with a text encoding byte is written with an encoding its tag's version defines, and reads back +/// (issue #255). ID3v2.3 defines only $00 ISO-8859-1 and $01 UTF-16 with a BOM (https://id3.org/id3v2.3.0 §3.3), so a +/// v2.3 tag, and a v2.2 tag, which is written as v2.3 (#187), gets ISO-8859-1 when the text fits and UTF-16 with a +/// BOM otherwise. ID3v2.4 also defines $03 UTF-8 (https://id3.org/id3v2.4.0-structure §4), which a v2.4 tag keeps. +/// The matrix is {frame kind} × {version} × {text} × {save entry point}. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2WrittenEncodingTests +{ + static readonly byte[] Jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 0xFF, 0xD9]; + + /// The frame IDs whose body starts with a text encoding byte, and the frames that embed one (CHAP, CTOC). + static bool HasEncodingByte (string id) => + id[0] == 'T' || id is "IPLS" or "COMM" or "USLT" or "APIC" or "WXXX" or "GEOB" or "SYLT" or "MVNM" or "MVIN"; + + /// A way a caller puts text into a tag, and what a fresh read of that tag gives back. + public sealed record Kind (string Name, Action Set, Func Get, Func Expected) + { + public override string ToString () => Name; + } + + static string Same (string text) => text; + + static readonly Kind[] Kinds = [ + new ("TIT2 Title", (t, s) => t.Title = s, t => t.Title, Same), + new ("TPE1 Performers multi-value", (t, s) => t.Performers = [s, s + "2"], t => string.Join ("|", t.Performers), s => s + "|" + s + "2"), + new ("TCOM SetTextFrameValues", (t, s) => t.SetTextFrameValues ("TCOM", [s]), t => t.Composers.FirstOrDefault (), Same), + new ("TXXX SetUserText", (t, s) => t.SetUserText ("NOTE", s), t => t.GetUserText ("NOTE"), Same), + new ("TXXX UserTextFrame description", (t, s) => t.AddUserTextFrame (new UserTextFrame (s, s)), t => t.UserTextFrames.Count == 1 ? t.UserTextFrames[0].Description + "=" + t.UserTextFrames[0].Value : null, s => s + "=" + s), + new ("TXXX SetCustomField", (t, s) => t.SetCustomField ("NOTE", s, s + "2"), t => string.Join ("|", t.GetCustomField ("NOTE")), s => s + "|" + s + "2"), + new ("COMM Comment", (t, s) => t.Comment = s, t => t.Comment, Same), + new ("COMM CommentFrame description", (t, s) => t.AddComment (new CommentFrame (s, "eng", s)), t => t.Comments.Count == 1 ? t.Comments[0].Description + "=" + t.Comments[0].Text : null, s => s + "=" + s), + new ("USLT Lyrics", (t, s) => t.Lyrics = s, t => t.Lyrics, Same), + new ("USLT LyricsFrame description", (t, s) => t.AddLyrics (new LyricsFrame (s, "eng", s)), t => t.LyricsFrames.Count == 1 ? t.LyricsFrames[0].Description + "=" + t.LyricsFrames[0].Text : null, s => s + "=" + s), + new ("APIC AddPicture", (t, s) => t.AddPicture (new PictureFrame ("image/jpeg", PictureType.FrontCover, s, Jpeg)), DescribePicture, Same), + new ("APIC FromBytes", (t, s) => t.AddPicture (PictureFrame.FromBytes (Jpeg, PictureType.FrontCover, s)), DescribePicture, Same), + new ("APIC CoverArt", (t, s) => t.CoverArt = new PictureFrame ("image/jpeg", PictureType.FrontCover, s, new BinaryData (Jpeg)), DescribePicture, Same), + new ("APIC Pictures setter from FLAC", (t, s) => t.Pictures = [new FlacPicture ("image/jpeg", PictureType.FrontCover, s, new BinaryData (Jpeg), 1, 1, 24, 0)], DescribePicture, Same), + new ("WXXX SetUserUrl", (t, s) => t.SetUserUrl (s, "http://a.b/"), t => t.UserUrlFrames.Count == 1 ? t.UserUrlFrames[0].Description + "=" + t.GetUserUrl (t.UserUrlFrames[0].Description) : null, s => s + "=http://a.b/"), + new ("GEOB", (t, s) => t.AddGeneralObject (new GeneralObjectFrame ("application/octet-stream", s, s, new BinaryData ([1, 2, 3]))), t => t.GetGeneralObject () is { } g ? g.FileName + "=" + g.Description : null, s => s + "=" + s), + new ("SYLT", AddSyncLyrics, t => t.GetSyncLyrics () is { SyncItems.Count: 2 } f ? f.Description + "=" + f.SyncItems[0].Text + "|" + f.SyncItems[1].Text : null, s => s + "=" + s + "|" + s + "2"), + new ("TIPL InvolvedPeopleFrame", AddInvolvedPeople, t => t.GetInvolvedPeopleFrame ("TIPL") is { Count: 1 } f ? f.Pairs[0].Role + "=" + f.Pairs[0].Person : null, s => s + "=" + s), + new ("CHAP title", (t, s) => t.AddChapter (new ChapterFrame ("ch1", 0, 1000) { Title = s }), t => t.GetChapter ("ch1")?.Title, Same), + new ("CTOC title", AddTableOfContents, t => t.GetTableOfContents ()?.Title, Same), + new ("CopyTo from Vorbis", CopyFromVorbis, t => t.Title + "|" + t.Comment + "|" + DescribePicture (t), s => s + "|" + s + "|" + s), + ]; + + static string? DescribePicture (Id3v2Tag tag) => tag.Pictures.Length == 1 ? tag.Pictures[0].Description : null; + + static void AddSyncLyrics (Id3v2Tag tag, string text) + { + var frame = new SyncLyricsFrame { Description = text }; + frame.AddSyncItem (text, 1000); + frame.AddSyncItem (text + "2", 2000); + tag.AddSyncLyrics (frame); + } + + static void AddInvolvedPeople (Id3v2Tag tag, string text) + { + var frame = new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople); + frame.Add (text, text); + tag.AddInvolvedPeopleFrame (frame); + } + + static void AddTableOfContents (Id3v2Tag tag, string text) + { + var toc = new TableOfContentsFrame ("toc") { Title = text, IsTopLevel = true }; + toc.AddChildElement ("ch1"); + tag.AddTableOfContents (toc); + } + + static void CopyFromVorbis (Id3v2Tag tag, string text) + { + var source = new VorbisComment { Title = text, Comment = text }; + source.AddPicture (new FlacPicture ("image/jpeg", PictureType.FrontCover, text, new BinaryData (Jpeg), 1, 1, 24, 0)); + source.CopyTo (tag); + } + + public enum Text + { + Ascii, + Latin1, + Wide, + } + + static string Sample (Text text) => text switch { + Text.Ascii => "Cover", + Text.Latin1 => "Café Ñandú ÿ", + _ => "日本語 \U0001F3B5", + }; + + public enum Entry + { + TagRender, + SpanRender, + PathWithData, + Path, + AsyncPathWithData, + AsyncPath, + InPlace, + AsyncInPlace, + } + + public static IEnumerable Matrix => + from kind in Kinds + from version in new[] { Id3v2Version.V22, Id3v2Version.V23, Id3v2Version.V24 } + from text in Enum.GetValues () + from entry in Enum.GetValues () + select new object[] { kind, version, text, entry }; + + [TestMethod] + [DynamicData (nameof (Matrix), DynamicDataDisplayName = nameof (RowName))] + public async Task Save_FrameWithText_WritesEncodingTheVersionDefinesAndReadsBack (Kind kind, Id3v2Version version, Text text, Entry entry) + { + var value = Sample (text); + + var (written, reread) = await SaveAsync (version, entry, tag => kind.Set (tag, value)); + + var writtenVersion = version == Id3v2Version.V24 ? 4 : 3; + Assert.AreEqual (writtenVersion, written[3], "major version written"); + // A v2.4 tag keeps the UTF-8 every new frame starts with; a v2.3 tag gets ISO-8859-1 when the text fits. + var expected = writtenVersion == 4 ? TextEncodingType.Utf8 + : text == Text.Wide ? TextEncodingType.Utf16WithBom : TextEncodingType.Latin1; + var encodings = EncodingBytes (written); + Assert.IsNotEmpty (encodings, "no frame with an encoding byte was written"); + foreach (var (id, encoding) in encodings) + Assert.AreEqual ((byte)expected, encoding, $"{id} encoding byte"); + + Assert.AreEqual (kind.Expected (value), kind.Get (reread), "fresh read"); + } + + /// A frame object built with an encoding the caller chose, and what a fresh read of a tag holding it gives back. + public sealed record Framed (string Name, Func Create, Func Get, Func Expected) + { + public override string ToString () => Name; + } + + static readonly Framed[] FrameKinds = [ + new ("TIT2", (s, e) => new TextFrame ("TIT2", s, e), t => t.Title, Same), + new ("TPE1 multi-value", (s, e) => new TextFrame ("TPE1", s + "\0" + s + "2", e), t => string.Join ("|", t.Performers), s => s + "|" + s + "2"), + new ("TXXX", (s, e) => new UserTextFrame (s, s + "\0" + s + "2", e), t => t.UserTextFrames.Count == 1 ? t.UserTextFrames[0].Description + "=" + string.Join ("|", t.GetCustomField (t.UserTextFrames[0].Description)) : null, s => s + "=" + s + "|" + s + "2"), + new ("COMM", (s, e) => new CommentFrame (s, "eng", s, e), t => t.Comments.Count == 1 ? t.Comments[0].Description + "=" + t.Comments[0].Text : null, s => s + "=" + s), + new ("USLT", (s, e) => new LyricsFrame (s, "eng", s, e), t => t.LyricsFrames.Count == 1 ? t.LyricsFrames[0].Description + "=" + t.LyricsFrames[0].Text : null, s => s + "=" + s), + new ("WXXX", (s, e) => new UserUrlFrame ("http://a.b/", s, e), t => t.UserUrlFrames.Count == 1 ? t.UserUrlFrames[0].Description + "=" + t.UserUrlFrames[0].Url : null, s => s + "=http://a.b/"), + new ("GEOB", (s, e) => new GeneralObjectFrame ("application/octet-stream", s, s, new BinaryData ([1, 2, 3]), e), t => t.GetGeneralObject () is { } g ? g.FileName + "=" + g.Description : null, s => s + "=" + s), + new ("APIC", (s, e) => new PictureFrame ("image/jpeg", PictureType.FrontCover, s, Jpeg, e), DescribePicture, Same), + new ("SYLT", CreateSyncLyrics, t => t.GetSyncLyrics () is { SyncItems.Count: 2 } f ? f.Description + "=" + f.SyncItems[0].Text + "|" + f.SyncItems[1].Text : null, s => s + "=" + s + "|" + s + "2"), + new ("TIPL", CreateInvolvedPeople, t => t.GetInvolvedPeopleFrame ("TIPL") is { Count: 1 } f ? f.Pairs[0].Role + "=" + f.Pairs[0].Person : null, s => s + "=" + s), + ]; + + static SyncLyricsFrame CreateSyncLyrics (string text, TextEncodingType encoding) + { + var frame = new SyncLyricsFrame { Description = text, Encoding = encoding }; + frame.AddSyncItem (text, 1000); + frame.AddSyncItem (text + "2", 2000); + return frame; + } + + static InvolvedPeopleFrame CreateInvolvedPeople (string text, TextEncodingType encoding) + { + var frame = new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople) { Encoding = encoding }; + frame.Add (text, text); + return frame; + } + + /// The frame's ID and its body as its public RenderContent () gives it, in the encoding it holds. + static (string Id, byte[] Body) Body (object frame) => frame switch { + TextFrame f => (f.Id, f.RenderContent ().ToArray ()), + UserTextFrame f => ("TXXX", f.RenderContent ().ToArray ()), + CommentFrame f => ("COMM", f.RenderContent ().ToArray ()), + LyricsFrame f => ("USLT", f.RenderContent ().ToArray ()), + UserUrlFrame f => ("WXXX", f.RenderContent ().ToArray ()), + GeneralObjectFrame f => ("GEOB", f.RenderContent ().ToArray ()), + PictureFrame f => ("APIC", f.RenderContent ().ToArray ()), + SyncLyricsFrame f => ("SYLT", f.RenderContent ().ToArray ()), + InvolvedPeopleFrame f => (f.Id, f.RenderContent ().ToArray ()), + _ => throw new ArgumentException (frame.GetType ().Name), + }; + + /// + /// Adds a frame object through the tag's public API. A and a have + /// none (the setters, in the first matrix, build their own). + /// + static bool TryAdd (Id3v2Tag tag, object frame) + { + switch (frame) { + case UserTextFrame f: tag.AddUserTextFrame (f); return true; + case CommentFrame f: tag.AddComment (f); return true; + case LyricsFrame f: tag.AddLyrics (f); return true; + case GeneralObjectFrame f: tag.AddGeneralObject (f); return true; + case PictureFrame f: tag.AddPicture (f); return true; + case SyncLyricsFrame f: tag.AddSyncLyrics (f); return true; + case InvolvedPeopleFrame f: tag.AddInvolvedPeopleFrame (f); return true; + default: return false; + } + } + + static readonly TextEncodingType[] AllEncodings = [TextEncodingType.Latin1, TextEncodingType.Utf16WithBom, TextEncodingType.Utf16BE, TextEncodingType.Utf8]; + + // ISO-8859-1 cannot hold the wide text; a frame that asks for it with that text is a separate question. + static IEnumerable<(TextEncodingType Encoding, Text Text)> EncodingsAndTexts => + from encoding in AllEncodings + from text in Enum.GetValues () + where !(encoding == TextEncodingType.Latin1 && text == Text.Wide) + select (encoding, text); + + public static IEnumerable AddedMatrix => + from kind in FrameKinds + where TryAdd (new Id3v2Tag (), kind.Create ("x", TextEncodingType.Utf8)) + from version in new[] { Id3v2Version.V22, Id3v2Version.V23, Id3v2Version.V24 } + from row in EncodingsAndTexts + select new object[] { kind, version, row.Encoding, row.Text }; + + public static IEnumerable ReadMatrix => + from kind in FrameKinds + from row in EncodingsAndTexts + select new object[] { kind, row.Encoding, row.Text }; + + public static string RowName (System.Reflection.MethodInfo method, object[] row) => + $"{method.Name} ({string.Join (", ", row)})"; + + /// + /// The encoding a v2.3 tag writes for a frame that asks for : that one when v2.3 defines + /// it, otherwise ISO-8859-1 when the text fits and UTF-16 with a BOM when it does not. + /// + static TextEncodingType V23Encoding (TextEncodingType encoding, Text text) => + encoding is TextEncodingType.Latin1 or TextEncodingType.Utf16WithBom ? encoding + : text == Text.Wide ? TextEncodingType.Utf16WithBom : TextEncodingType.Latin1; + + // A frame a caller builds with its own encoding and adds to the tag: v2.4 writes that encoding, v2.3 one it defines. + [TestMethod] + [DynamicData (nameof (AddedMatrix), DynamicDataDisplayName = nameof (RowName))] + public void Render_FrameWithChosenEncoding_WritesEncodingTheVersionDefinesAndReadsBack (Framed kind, Id3v2Version version, TextEncodingType encoding, Text text) + { + var value = Sample (text); + var tag = new Id3v2Tag (version); + Assert.IsTrue (TryAdd (tag, kind.Create (value, encoding))); + + var rendered = tag.Render ().ToArray (); + + var expected = version == Id3v2Version.V24 ? encoding : V23Encoding (encoding, text); + Assert.IsNotEmpty (EncodingBytes (rendered)); + foreach (var (id, written) in EncodingBytes (rendered)) + Assert.AreEqual ((byte)expected, written, $"{id} encoding byte"); + Assert.AreEqual (kind.Expected (value), kind.Get (Id3v2Tag.Read (rendered).Tag!), "fresh read"); + } + + // A frame read from a v2.3 or v2.2 tag in an encoding v2.3 does not define (as this library wrote before #255) is + // written back in one it does, with the same text. A frame in an encoding v2.3 defines keeps its bytes. + [TestMethod] + [DynamicData (nameof (ReadMatrix), DynamicDataDisplayName = nameof (RowName))] + public void Render_UnchangedFrameReadFromV23_WritesEncodingTheVersionDefines (Framed kind, TextEncodingType encoding, Text text) + { + var value = Sample (text); + var (id, body) = Body (kind.Create (value, encoding)); + var original = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader (3, (uint)(10 + body.Length)), .. TestBuilders.Id3v2.CreateFrame (id, body, 3)]).Tag!; + var read = kind.Get (original); + + var rendered = original.Render ().ToArray (); + + var written = WrittenFrames (rendered).Single (f => f.Id == id).Body; + var expected = V23Encoding (encoding, text); + Assert.AreEqual ((byte)expected, written[0], $"{id} encoding byte"); + if (expected == encoding) + CollectionAssert.AreEqual (body, written, "a frame in an encoding v2.3 defines keeps its bytes"); + Assert.AreEqual (read, kind.Get (Id3v2Tag.Read (rendered).Tag!), "fresh read"); + } + + const string W = "\u65E5"; + + /// + /// Frames with several strings where one alone is outside ISO-8859-1, each a frame, what a fresh read gives, and + /// what it should give. The encoding byte covers every string in the frame, so that one string makes it UTF-16. + /// + public static IEnumerable OneWideString => new (string Name, Action Add, Func Get, string Expected)[] { + ("TPE1 second value", t => t.Performers = ["a", W], t => string.Join ("|", t.Performers), "a|" + W), + ("TXXX description", t => t.SetUserText (W, "v"), t => t.GetUserText (W), "v"), + ("TXXX value", t => t.SetUserText ("d", W), t => t.GetUserText ("d"), W), + ("TXXX second value", t => t.SetCustomField ("d", "a", W), t => string.Join ("|", t.GetCustomField ("d")), "a|" + W), + ("COMM description", t => t.AddComment (new CommentFrame ("t", "eng", W)), t => t.Comments[0].Description + "=" + t.Comments[0].Text, W + "=t"), + ("COMM text", t => t.AddComment (new CommentFrame (W, "eng", "d")), t => t.Comments[0].Description + "=" + t.Comments[0].Text, "d=" + W), + ("USLT description", t => t.AddLyrics (new LyricsFrame ("t", "eng", W)), t => t.LyricsFrames[0].Description + "=" + t.LyricsFrames[0].Text, W + "=t"), + ("USLT text", t => t.AddLyrics (new LyricsFrame (W, "eng", "d")), t => t.LyricsFrames[0].Description + "=" + t.LyricsFrames[0].Text, "d=" + W), + ("GEOB file name", t => t.AddGeneralObject (new GeneralObjectFrame ("x/y", W, "d", new BinaryData ([1]))), t => t.GetGeneralObject ()!.FileName + "=" + t.GetGeneralObject ()!.Description, W + "=d"), + ("GEOB description", t => t.AddGeneralObject (new GeneralObjectFrame ("x/y", "f", W, new BinaryData ([1]))), t => t.GetGeneralObject ()!.FileName + "=" + t.GetGeneralObject ()!.Description, "f=" + W), + ("SYLT description", t => t.AddSyncLyrics (SyncLyrics (W, "a", "b")), DescribeSyncLyrics, W + "=a|b"), + ("SYLT first item", t => t.AddSyncLyrics (SyncLyrics ("d", W, "b")), DescribeSyncLyrics, "d=" + W + "|b"), + ("SYLT last item", t => t.AddSyncLyrics (SyncLyrics ("d", "a", W)), DescribeSyncLyrics, "d=a|" + W), + ("TIPL role", t => t.AddInvolvedPeopleFrame (People ((W, "p"))), DescribePeople, W + "=p"), + ("TIPL person", t => t.AddInvolvedPeopleFrame (People (("r", W))), DescribePeople, "r=" + W), + ("TIPL last person", t => t.AddInvolvedPeopleFrame (People (("r", "p"), ("s", W))), DescribePeople, "r=p|s=" + W), + }.Select (c => new object[] { c.Name, c.Add, c.Get, c.Expected }); + + static SyncLyricsFrame SyncLyrics (string description, params string[] items) + { + var frame = new SyncLyricsFrame { Description = description }; + for (var i = 0; i < items.Length; i++) + frame.AddSyncItem (items[i], (uint)(1000 * (i + 1))); + return frame; + } + + static string? DescribeSyncLyrics (Id3v2Tag tag) => + tag.GetSyncLyrics () is { } f ? f.Description + "=" + string.Join ("|", f.SyncItems.Select (i => i.Text)) : null; + + static InvolvedPeopleFrame People (params (string Role, string Person)[] pairs) + { + var frame = new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople); + foreach (var (role, person) in pairs) + frame.Add (role, person); + return frame; + } + + static string? DescribePeople (Id3v2Tag tag) => + tag.GetInvolvedPeopleFrame ("TIPL") is { } f ? string.Join ("|", f.Pairs.Select (p => p.Role + "=" + p.Person)) : null; + + [TestMethod] + [DynamicData (nameof (OneWideString))] + public void Render_V23FrameWithOneStringOutsideLatin1_WritesUtf16 (string name, Action add, Func get, string expected) + { + var tag = new Id3v2Tag (Id3v2Version.V23); + add (tag); + + var rendered = tag.Render ().ToArray (); + + var encodings = EncodingBytes (rendered); + Assert.HasCount (1, encodings, name); + Assert.AreEqual ((byte)TextEncodingType.Utf16WithBom, encodings[0].Encoding, name); + Assert.AreEqual (expected, get (Id3v2Tag.Read (rendered).Tag!), name); + } + + // A CHAP or CTOC rendered on its own, outside a tag, embeds its title as ID3v2.4 does: in UTF-8. + [TestMethod] + public void RenderContent_ChapterAndTableOfContentsOnTheirOwn_EmbedUtf8Title () + { + var chapter = new ChapterFrame ("ch1", 0, 1000) { Title = "Intro" }.RenderContent ().ToArray (); + var toc = new TableOfContentsFrame ("toc") { Title = "Intro" }.RenderContent ().ToArray (); + + foreach (var body in new[] { chapter, toc }) { + var at = body.AsSpan ().IndexOf ("TIT2"u8); + Assert.AreEqual ((byte)TextEncodingType.Utf8, body[at + 10]); + } + } + + // The description of a v2.3 picture written in UTF-16 starts with a BOM (ID3v2.3 §3.3), which APIC writes itself. + [TestMethod] + public void Render_V23PictureWithWideDescription_WritesBomBeforeDescription () + { + var tag = new Id3v2Tag (Id3v2Version.V23); + tag.AddPicture (new PictureFrame ("image/jpeg", PictureType.FrontCover, W, Jpeg)); + + var body = WrittenFrames (tag.Render ().ToArray ()).Single (f => f.Id == "APIC").Body; + + byte[] expected = [0x01, .. "image/jpeg"u8, 0, 0x03, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes (W), 0, 0, .. Jpeg]; + CollectionAssert.AreEqual (expected, body); + } + + // An involved-people frame with no pairs still has an encoding byte, one v2.3 defines. + [TestMethod] + public void Render_V23EmptyInvolvedPeopleFrame_WritesLatin1EncodingByte () + { + var tag = new Id3v2Tag (Id3v2Version.V23); + tag.AddInvolvedPeopleFrame (new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople)); + + var encodings = EncodingBytes (tag.Render ().ToArray ()); + + Assert.HasCount (1, encodings); + Assert.AreEqual ((byte)TextEncodingType.Latin1, encodings[0].Encoding); + } + + // A v2.3 picture in UTF-8 or UTF-16BE, as this library wrote one before #255, reads, and a save, from any entry + // point, writes it in an encoding v2.3 defines, with the same description and picture data. + public static IEnumerable RecoveryRows => + from encoding in new[] { TextEncodingType.Utf8, TextEncodingType.Utf16BE } + from text in Enum.GetValues () + from entry in Enum.GetValues () + where entry != Entry.TagRender + select new object[] { encoding, text, entry }; + + [TestMethod] + [DynamicData (nameof (RecoveryRows), DynamicDataDisplayName = nameof (RowName))] + public async Task Save_V23PictureInUndefinedEncoding_ReadsAndIsRewritten (TextEncodingType encoding, Text text, Entry entry) + { + var value = Sample (text); + var apic = new PictureFrame ("image/jpeg", PictureType.FrontCover, value, Jpeg, encoding).RenderContent ().ToArray (); + Assert.AreEqual ((byte)encoding, apic[0]); + byte[] tag = [.. TestBuilders.Id3v2.CreateHeader (3, (uint)(10 + apic.Length)), .. TestBuilders.Id3v2.CreateFrame ("APIC", apic, 3)]; + var source = Mp3File.Read ([.. tag, .. new byte[256]]).File!; + Assert.AreEqual (value, DescribePicture (source.Id3v2Tag!), "read of the stored frame"); + + var (written, reread) = await SaveAsync ([.. tag, .. new byte[256]], entry, _ => { }); + + var body = WrittenFrames (written).Single (f => f.Id == "APIC").Body; + Assert.AreEqual ((byte)(text == Text.Wide ? TextEncodingType.Utf16WithBom : TextEncodingType.Latin1), body[0]); + Assert.AreEqual (value, DescribePicture (reread)); + CollectionAssert.AreEqual (Jpeg, reread.Pictures[0].PictureData.ToArray ()); + } + + /// + /// Saves an MP3 whose tag is after , through + /// , and returns the ID3v2 tag bytes written and a fresh read of them. + /// + static async Task<(byte[] Written, Id3v2Tag Reread)> SaveAsync (Id3v2Version version, Entry entry, Action edit) + { + if (entry == Entry.TagRender) { + var tag = new Id3v2Tag (version); + edit (tag); + var rendered = tag.Render ().ToArray (); + return (rendered, Id3v2Tag.Read (rendered).Tag!); + } + + var original = Mp3 (version); + Assert.AreEqual ((int)version, Mp3File.Read (original).File!.Id3v2Tag!.Version, "source tag version"); + return await SaveAsync (original, entry, edit); + } + + /// Reads the MP3 , edits its ID3v2 tag and saves it through . + static async Task<(byte[] Written, Id3v2Tag Reread)> SaveAsync (byte[] original, Entry entry, Action edit) + { + var files = new MockFileSystem (); + files.AddFile ("/in.mp3", original); + var file = Mp3File.ReadFromFile ("/in.mp3", files).File!; + edit (file.Id3v2Tag!); + + byte[] saved; + switch (entry) { + case Entry.SpanRender: + saved = file.Render (original).ToArray (); + break; + case Entry.InPlace: + Assert.IsTrue (file.SaveToFile (files).IsSuccess); + saved = files.ReadAllBytes ("/in.mp3"); + break; + case Entry.AsyncInPlace: + Assert.IsTrue ((await file.SaveToFileAsync (files)).IsSuccess); + saved = files.ReadAllBytes ("/in.mp3"); + break; + default: + var result = entry switch { + Entry.PathWithData => file.SaveToFile ("/out.mp3", original, files), + Entry.Path => file.SaveToFile ("/out.mp3", files), + Entry.AsyncPathWithData => await file.SaveToFileAsync ("/out.mp3", original, files), + _ => await file.SaveToFileAsync ("/out.mp3", files), + }; + Assert.IsTrue (result.IsSuccess, result.Error); + saved = files.ReadAllBytes ("/out.mp3"); + break; + } + + var reread = Mp3File.Read (saved); + Assert.IsTrue (reread.IsSuccess, reread.Error); + var size = Id3v2Header.Read (saved).Header.TotalSize; + return (saved[..(int)size], reread.File!.Id3v2Tag!); + } + + /// An MP3 holding an ID3v2 tag of with no frames, only padding, and some audio bytes. + static byte[] Mp3 (Id3v2Version version) => + [.. TestBuilders.Id3v2.CreateHeader ((byte)version, 64), .. new byte[64], .. new byte[256]]; + + /// The encoding byte of every frame in a rendered tag that has one (). + static List<(string Id, byte Encoding)> EncodingBytes (byte[] tag) => + [.. WrittenFrames (tag).Where (f => HasEncodingByte (f.Id)).Select (f => (f.Id, f.Body[0]))]; + + /// + /// Every frame in a rendered v2.3 or v2.4 tag, as its ID and body, with the sub-frames of a CHAP or CTOC (ID3v2 + /// Chapter Frame Addendum §3.1, §3.2) right after it. The tags this library renders have no unsynchronisation, no + /// extended header and no frame flags. + /// + internal static List<(string Id, byte[] Body)> WrittenFrames (byte[] tag) + { + var found = new List<(string, byte[])> (); + var end = 10 + (int)Id3v2Header.Read (tag).Header.TagSize; + Walk (tag.AsSpan (10, end - 10), tag[3] == 4, found); + return found; + } + + static void Walk (ReadOnlySpan frames, bool syncSafe, List<(string, byte[])> found) + { + var offset = 0; + while (offset + 10 <= frames.Length && frames[offset] != 0) { + var id = System.Text.Encoding.ASCII.GetString (frames.Slice (offset, 4)); + var s = frames.Slice (offset + 4, 4); + var size = syncSafe + ? (s[0] << 21) | (s[1] << 14) | (s[2] << 7) | s[3] + : (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3]; + var body = frames.Slice (offset + 10, size); + found.Add ((id, body.ToArray ())); + if (id == "CHAP") + Walk (body.Slice (body.IndexOf ((byte)0) + 1 + 16), syncSafe, found); + else if (id == "CTOC") + Walk (AfterChildIds (body), syncSafe, found); + offset += 10 + size; + } + } + + // CTOC: element ID, NUL, flags, entry count, then that many NUL-terminated child IDs. + static ReadOnlySpan AfterChildIds (ReadOnlySpan body) + { + var offset = body.IndexOf ((byte)0) + 1; + var count = body[offset + 1]; + offset += 2; + for (var i = 0; i < count; i++) + offset += body.Slice (offset).IndexOf ((byte)0) + 1; + return body.Slice (offset); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs index 27a5f3ec..cbeb8035 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Utf16MultiStringTests.cs @@ -85,18 +85,42 @@ public void TextFrame_Read_StripsEveryBom () Assert.AreEqual ("first\0second", frame.Text); } + // Text that ISO-8859-1 cannot hold is UTF-16 in a v2.3 tag (#255), with a BOM before every string. [TestMethod] public void Id3v23_SetCustomField_WritesABomBeforeEachValue () { var tag = new Id3v2Tag (Id3v2Version.V23); + string[] values = ["first\u65E5", "second\u65E5"]; - tag.SetCustomField ("F", "first", "second"); + tag.SetCustomField ("F", values); - var content = tag.UserTextFrames[0].RenderContent ().ToArray (); - byte[] expected = [0x01, .. Le, .. Utf16 ("F", false), 0, 0, .. Le, .. Utf16 ("first", false), 0, 0, .. Le, .. Utf16 ("second", false)]; + var rendered = tag.Render ().ToArray (); + var content = Id3v2WrittenEncodingTests.WrittenFrames (rendered).Single (f => f.Id == "TXXX").Body; + byte[] expected = [0x01, .. Le, .. Utf16 ("F", false), 0, 0, .. Le, .. Utf16 (values[0], false), 0, 0, .. Le, .. Utf16 (values[1], false)]; + CollectionAssert.AreEqual (expected, content); + var again = Id3v2Tag.Read (rendered).Tag!; + CollectionAssert.AreEqual (values, again.GetCustomField ("F").ToArray ()); + } + + // A text frame or TXXX value that a v2.3 tag writes in UTF-16 though it holds another encoding gets the same + // layout: a BOM before every string (ID3v2.3 §3.3). + [TestMethod] + [DataRow ("TPE1")] + [DataRow ("TXXX")] + public void Id3v23_MultiValueWrittenInUtf16_WritesABomBeforeEachValue (string frameId) + { + var tag = new Id3v2Tag (Id3v2Version.V23); + string[] values = ["first\u65E5", "second\u65E5"]; + if (frameId == "TPE1") + tag.Performers = values; + else + tag.AddUserTextFrame (new UserTextFrame ("F", string.Join ("\0", values))); + + var content = Id3v2WrittenEncodingTests.WrittenFrames (tag.Render ().ToArray ()).Single (f => f.Id == frameId).Body; + + byte[] valueBytes = [.. Le, .. Utf16 (values[0], false), 0, 0, .. Le, .. Utf16 (values[1], false)]; + byte[] expected = frameId == "TPE1" ? [0x01, .. valueBytes] : [0x01, .. Le, .. Utf16 ("F", false), 0, 0, .. valueBytes]; CollectionAssert.AreEqual (expected, content); - var again = Id3v2Tag.Read (tag.Render ().Span).Tag!; - CollectionAssert.AreEqual (FirstSecond, again.GetCustomField ("F").ToArray ()); } [TestMethod] From afe3b14714560872762773778a53288fa41f2868 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:48:10 -0700 Subject: [PATCH 2/7] fix: Write and read the frames CHAP and CTOC embed with the tag version's frame header (#261) --- CHANGELOG.md | 1 + .../Id3/Id3v2/Frames/ChapterFrame.cs | 70 +----- .../Id3/Id3v2/Frames/TableOfContentsFrame.cs | 77 +----- .../Id3/Id3v2/Id3v2Tag.FrameWalk.cs | 51 ++++ src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 19 +- .../Id3/Id3v2/Id3v2EmbeddedFrameTests.cs | 231 ++++++++++++++++++ 6 files changed, 296 insertions(+), 153 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b080b706..bed06132 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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 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/Id3/Id3v2/Frames/ChapterFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs index 3c7823ec..b92302cf 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs @@ -134,44 +134,8 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version EndByteOffset = endOffset }; - // Parse embedded sub-frames if present - while (offset + 10 <= data.Length) // Frame header is 10 bytes - { - // Read frame ID - var frameIdBytes = data.Slice (offset, 4); - if (frameIdBytes[0] == 0) - break; // End of frames - - // Check if valid frame ID (A-Z, 0-9) - var isValidFrame = true; - for (var i = 0; i < 4; i++) { - var c = frameIdBytes[i]; - if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { - isValidFrame = false; - break; - } - } - - if (!isValidFrame) - break; - - var subFrameId = System.Text.Encoding.ASCII.GetString (frameIdBytes); - var frameSize = GetFrameSize (data.Slice (offset + 4, 4), version); - - if (frameSize <= 0 || offset + 10 + frameSize > data.Length) - break; - - var subFrameData = data.Slice (offset + 10, frameSize); - offset += 10 + frameSize; - - // Handle known sub-frames - if (subFrameId == "TIT2") { - var titleResult = TextFrame.Read (subFrameId, subFrameData, version); - if (titleResult.IsSuccess) - frame.Title = titleResult.Frame!.Text; - } - // Other sub-frames could be parsed here (TIT3, WXXX, APIC, etc.) - } + // Embedded sub-frames, with the tag's frame header and flags. Only the title is read. + frame.Title = Id3v2Tag.ReadEmbeddedTitle (data.Slice (offset), version); return ChapterFrameReadResult.Success (frame, data.Length); } @@ -218,15 +182,10 @@ internal BinaryData RenderContent (Id3v2Version version) // End byte offset (4 bytes, big-endian) AddUInt32BE (builder, EndByteOffset); - // Embedded TIT2 frame + // Embedded TIT2 frame, with the tag's frame header if (titleFrameData.HasValue) { - var tfd = titleFrameData.Value; - // Frame header: ID (4) + Size (4) + Flags (2) - builder.Add (System.Text.Encoding.ASCII.GetBytes ("TIT2")); - AddSyncSafeUInt32 (builder, (uint)tfd.Length); - builder.Add ((byte)0x00); - builder.Add ((byte)0x00); - builder.Add (tfd); + Id3v2Tag.AddFrameHeader (builder, "TIT2", titleFrameData.Value.Length, version); + builder.Add (titleFrameData.Value); } return builder.ToBinaryData (); @@ -240,18 +199,6 @@ static uint ReadUInt32BE (ReadOnlySpan data) (uint)data[3]; } - static int GetFrameSize (ReadOnlySpan data, Id3v2Version version) - { - if (version == Id3v2Version.V24) { - // Syncsafe integer - return ((data[0] & 0x7F) << 21) | - ((data[1] & 0x7F) << 14) | - ((data[2] & 0x7F) << 7) | - (data[3] & 0x7F); - } - // Big-endian for v2.3 - return (int)ReadUInt32BE (data); - } static void AddUInt32BE (BinaryDataBuilder builder, uint value) { @@ -261,13 +208,6 @@ static void AddUInt32BE (BinaryDataBuilder builder, uint value) builder.Add ((byte)(value & 0xFF)); } - static void AddSyncSafeUInt32 (BinaryDataBuilder builder, uint value) - { - builder.Add ((byte)((value >> 21) & 0x7F)); - builder.Add ((byte)((value >> 14) & 0x7F)); - builder.Add ((byte)((value >> 7) & 0x7F)); - builder.Add ((byte)(value & 0x7F)); - } } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs index 899e8183..c307f2bc 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs @@ -157,44 +157,8 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v offset += childNullIndex + 1; } - // Parse embedded sub-frames if present - while (offset + 10 <= data.Length) // Frame header is 10 bytes - { - // Read frame ID - var frameIdBytes = data.Slice (offset, 4); - if (frameIdBytes[0] == 0) - break; // End of frames - - // Check if valid frame ID (A-Z, 0-9) - var isValidFrame = true; - for (var i = 0; i < 4; i++) { - var c = frameIdBytes[i]; - if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { - isValidFrame = false; - break; - } - } - - if (!isValidFrame) - break; - - var subFrameId = System.Text.Encoding.ASCII.GetString (frameIdBytes); - var frameSize = GetFrameSize (data.Slice (offset + 4, 4), version); - - if (frameSize <= 0 || offset + 10 + frameSize > data.Length) - break; - - var subFrameData = data.Slice (offset + 10, frameSize); - offset += 10 + frameSize; - - // Handle known sub-frames - if (subFrameId == "TIT2") { - var titleResult = TextFrame.Read (subFrameId, subFrameData, version); - if (titleResult.IsSuccess) - frame.Title = titleResult.Frame!.Text; - } - // Other sub-frames could be parsed here (TIT3, WXXX, APIC, etc.) - } + // Embedded sub-frames, with the tag's frame header and flags. Only the title is read. + frame.Title = Id3v2Tag.ReadEmbeddedTitle (data.Slice (offset), version); return TableOfContentsFrameReadResult.Success (frame, data.Length); } @@ -252,48 +216,17 @@ internal BinaryData RenderContent (Id3v2Version version) builder.Add ((byte)0x00); } - // Embedded TIT2 frame + // Embedded TIT2 frame, with the tag's frame header if (titleFrameData.HasValue) { - var tfd = titleFrameData.Value; - // Frame header: ID (4) + Size (4) + Flags (2) - builder.Add (System.Text.Encoding.ASCII.GetBytes ("TIT2")); - AddSyncSafeUInt32 (builder, (uint)tfd.Length); - builder.Add ((byte)0x00); - builder.Add ((byte)0x00); - builder.Add (tfd); + Id3v2Tag.AddFrameHeader (builder, "TIT2", titleFrameData.Value.Length, version); + builder.Add (titleFrameData.Value); } return builder.ToBinaryData (); } - static int GetFrameSize (ReadOnlySpan data, Id3v2Version version) - { - if (version == Id3v2Version.V24) { - // Syncsafe integer - return ((data[0] & 0x7F) << 21) | - ((data[1] & 0x7F) << 14) | - ((data[2] & 0x7F) << 7) | - (data[3] & 0x7F); - } - // Big-endian for v2.3 - return (int)ReadUInt32BE (data); - } - static uint ReadUInt32BE (ReadOnlySpan data) - { - return ((uint)data[0] << 24) | - ((uint)data[1] << 16) | - ((uint)data[2] << 8) | - (uint)data[3]; - } - static void AddSyncSafeUInt32 (BinaryDataBuilder builder, uint value) - { - builder.Add ((byte)((value >> 21) & 0x7F)); - builder.Add ((byte)((value >> 14) & 0x7F)); - builder.Add ((byte)((value >> 7) & 0x7F)); - builder.Add ((byte)(value & 0x7F)); - } } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs index dac0c9d9..b1f02b65 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs @@ -1,6 +1,9 @@ // 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.Frames; + namespace TagLibSharp2.Id3.Id3v2; /// @@ -111,4 +114,52 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt return FrameStep.Stop; return new FrameStep (id.Length == 3 ? FrameStepKind.Unmapped : FrameStepKind.Frame, id, size); } + + /// + /// The title among the frames a CHAP or CTOC embeds, which use "the same frame header format as the tag" (ID3v2 + /// Chapter Frame Addendum §3.1, §3.2): each header is read by and each frame's format flags + /// by , as a top-level frame of is. The last TIT2 that + /// reads wins; null when none does. + /// + internal static string? ReadEmbeddedTitle (ReadOnlySpan subFrames, Id3v2Version version) + { + var major = (byte)version; + var headerSize = FrameHeaderLength (major); + string? title = null; + while (true) { + var step = NextFrame (subFrames, subFrames.Length, major); + if (step.Kind == FrameStepKind.Stop) + break; + + if (step.Kind == FrameStepKind.Frame && step.Id == "TIT2") { + var format = major == 2 ? (byte)0 : subFrames[9]; + var content = ProcessFrameFlags (subFrames.Slice (headerSize, step.Size), format, major); + var read = TextFrame.Read (step.Id, content, version); + if (read.IsSuccess) + title = read.Frame!.Text; + } + + subFrames = subFrames.Slice (headerSize + step.Size); + } + + return title; + } + + /// + /// Adds a 10-byte frame header for a tag written as : a syncsafe size in ID3v2.4 + /// (https://id3.org/id3v2.4.0-structure §4) and a big-endian one otherwise (https://id3.org/id3v2.3.0 §3.3). The + /// frames a CHAP or CTOC embeds take the same header as the tag's own frames. + /// + internal static void AddFrameHeader (BinaryDataBuilder builder, string frameId, int contentSize, Id3v2Version version, + byte status = 0, byte format = 0) + { + var idBytes = System.Text.Encoding.ASCII.GetBytes (frameId); + builder.Add (idBytes.AsSpan ().Slice (0, 4)); + if (version == Id3v2Version.V24) + builder.AddSyncSafeUInt32 ((uint)contentSize); + else + builder.AddUInt32BE ((uint)contentSize); + builder.Add (status); + builder.Add (format); + } } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 1425b426..0c598cb9 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -2080,23 +2080,10 @@ public BinaryData Render (int paddingSize, bool withFooter = false) BinaryData RenderFrameHeader (string frameId, int contentSize, byte status = 0, byte format = 0) { - // Always render in v2.3/v2.4 format (10-byte headers) + // Always render in v2.3/v2.4 format (10-byte headers). Flags: status, then format (zero for every frame this + // library renders itself). using var builder = new BinaryDataBuilder (FrameHeaderSizeV23); - - // Frame ID (4 bytes) - var idBytes = System.Text.Encoding.ASCII.GetBytes (frameId); - builder.Add (idBytes.AsSpan ().Slice (0, 4)); - - // Size (syncsafe for v2.4, big-endian for v2.3) - if (Version == 4) - builder.AddSyncSafeUInt32 ((uint)contentSize); - else - builder.AddUInt32BE ((uint)contentSize); - - // Flags: status, then format (zero for every frame this library renders itself) - builder.Add (status); - builder.Add (format); - + AddFrameHeader (builder, frameId, contentSize, (Id3v2Version)WrittenVersion, status, format); return builder.ToBinaryData (); } diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs new file mode 100644 index 00000000..622327db --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs @@ -0,0 +1,231 @@ +// 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.IO.Compression; + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// The frames embedded in CHAP and CTOC (ID3v2 Chapter Frame Addendum §3.1, §3.2: "zero or more frames, using the +/// same frame header format as the tag") are written and read with their tag's frame header: a big-endian size in +/// ID3v2.3 (https://id3.org/id3v2.3.0 §3.3) and a syncsafe one in ID3v2.4 (https://id3.org/id3v2.4.0-structure §4), +/// and each version's frame flags (issue #261). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2EmbeddedFrameTests +{ + public enum Holder + { + Chapter, + TableOfContents, + } + + static void Add (Id3v2Tag tag, Holder holder, string title) + { + if (holder == Holder.Chapter) { + tag.AddChapter (new ChapterFrame ("ch1", 0, 1000) { Title = title }); + return; + } + var toc = new TableOfContentsFrame ("toc") { Title = title, IsTopLevel = true }; + toc.AddChildElement ("ch1"); + tag.AddTableOfContents (toc); + } + + static string? Title (Id3v2Tag tag, Holder holder) => + holder == Holder.Chapter ? tag.GetChapter ("ch1")?.Title : tag.GetTableOfContents ()?.Title; + + static readonly Id3v2Version[] Versions = [Id3v2Version.V23, Id3v2Version.V24]; + + // TIT2 body sizes on each side of the largest size one and two syncsafe bytes hold. + static readonly int[] BodySizes = [127, 128, 16383, 16384]; + + static readonly bool[] ViaFile = [false, true]; + + public static IEnumerable SizeMatrix => + from holder in Enum.GetValues () + from version in Versions + from bodySize in BodySizes + from viaFile in ViaFile + select new object[] { holder, version, bodySize, viaFile }; + + [TestMethod] + [DynamicData (nameof (SizeMatrix))] + public void Save_EmbeddedTitle_WritesTheTagVersionsSizeAndReadsBack (Holder holder, Id3v2Version version, int bodySize, bool viaFile) + { + // An ASCII title: the TIT2 body is the encoding byte and one byte a character in either version. + var title = new string ('t', bodySize - 1); + var tag = new Id3v2Tag (version); + Add (tag, holder, title); + + byte[] written; + Id3v2Tag reread; + if (viaFile) { + byte[] mp3 = [.. TestBuilders.Id3v2.CreateHeader ((byte)version, 16), .. new byte[16], .. new byte[256]]; + var file = Mp3File.Read (mp3).File!; + Add (file.Id3v2Tag!, holder, title); + written = file.Render (mp3).ToArray (); + reread = Mp3File.Read (written).File!.Id3v2Tag!; + } else { + written = tag.Render ().ToArray (); + reread = Id3v2Tag.Read (written).Tag!; + } + + var at = written.AsSpan ().IndexOf ("TIT2"u8); + var size = written.AsSpan (at + 4, 4).ToArray (); + byte[] expected = version == Id3v2Version.V24 + ? [(byte)((bodySize >> 21) & 0x7F), (byte)((bodySize >> 14) & 0x7F), (byte)((bodySize >> 7) & 0x7F), (byte)(bodySize & 0x7F)] + : [(byte)(bodySize >> 24), (byte)(bodySize >> 16), (byte)(bodySize >> 8), (byte)bodySize]; + CollectionAssert.AreEqual (expected, size, "embedded TIT2 size"); + Assert.AreEqual (title, Title (reread, holder)); + } + + /// A tag holding one CHAP or CTOC whose sub-frames are . + static byte[] TagWith (Holder holder, byte version, byte[] subFrames) + { + byte[] fixedPart = holder == Holder.Chapter + ? [.. "ch1"u8, 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] + : [.. "toc"u8, 0, 0x03, 1, .. "ch1"u8, 0]; + var frame = TestBuilders.Id3v2.CreateFrame (holder == Holder.Chapter ? "CHAP" : "CTOC", [.. fixedPart, .. subFrames], version); + return [.. TestBuilders.Id3v2.CreateHeader (version, (uint)frame.Length), .. frame]; + } + + static byte[] SubFrameHeader (string id, int size, byte version, byte format) => + [.. System.Text.Encoding.ASCII.GetBytes (id), + .. version == 4 + ? new[] { (byte)((size >> 21) & 0x7F), (byte)((size >> 14) & 0x7F), (byte)((size >> 7) & 0x7F), (byte)(size & 0x7F) } + : new[] { (byte)(size >> 24), (byte)(size >> 16), (byte)(size >> 8), (byte)size }, + 0, format]; + + static readonly byte[] TitleBody = [0, .. "Intro"u8]; + + static byte[] Deflate (byte[] data) + { + using var output = new MemoryStream (); + using (var zlib = new ZLibStream (output, CompressionLevel.Optimal)) + zlib.Write (data); + return output.ToArray (); + } + + /// + /// An embedded TIT2 with each version's format flags: v2.3 grouping (0x20) and compression (0x80, a 4-byte + /// decompressed size first), v2.4 grouping (0x40), data length indicator (0x01), unsynchronisation with it + /// (0x03) and compression with it (0x09). The same rules as a top-level frame. + /// + public static IEnumerable FlagRows () + { + var deflated = Deflate (TitleBody); + var rows = new (string Name, byte Version, byte Format, byte[] Body)[] { + ("v2.3 grouping", 3, 0x20, [0x07, .. TitleBody]), + ("v2.3 compression", 3, 0x80, [0, 0, 0, (byte)TitleBody.Length, .. deflated]), + ("v2.4 grouping", 4, 0x40, [0x07, .. TitleBody]), + ("v2.4 data length", 4, 0x01, [0, 0, 0, (byte)TitleBody.Length, .. TitleBody]), + ("v2.4 unsync", 4, 0x03, [0, 0, 0, (byte)TitleBody.Length, .. TitleBody]), + ("v2.4 compression", 4, 0x09, [0, 0, 0, (byte)TitleBody.Length, .. deflated]), + }; + foreach (var holder in Enum.GetValues ()) { + foreach (var row in rows) + yield return [holder, row.Name, row.Version, row.Format, row.Body]; + } + } + + [TestMethod] + [DynamicData (nameof (FlagRows))] + public void Read_EmbeddedTitleWithFrameFlags_ReadsTheTitle (Holder holder, string name, byte version, byte format, byte[] body) + { + var data = TagWith (holder, version, [.. SubFrameHeader ("TIT2", body.Length, version, format), .. body]); + + var tag = Id3v2Tag.Read (data).Tag!; + + Assert.AreEqual ("Intro", Title (tag, holder), name); + } + + // A v2.3 tag this library wrote before #261 gave a TIT2 of 128 bytes or more a syncsafe size. The frame walk reads + // a v2.3 size that does not fit, but whose bytes could be syncsafe, as syncsafe (iTunes writes them), so it reads. + [TestMethod] + [DataRow (Holder.Chapter)] + [DataRow (Holder.TableOfContents)] + public void Read_V23EmbeddedTitleWithSyncsafeSize_ReadsTheTitle (Holder holder) + { + var title = new string ('t', 199); + byte[] body = [0, .. System.Text.Encoding.ASCII.GetBytes (title)]; + var data = TagWith (holder, 3, [.. SubFrameHeader ("TIT2", body.Length, 4, 0), .. body]); + + Assert.AreEqual (title, Title (Id3v2Tag.Read (data).Tag!, holder)); + } + + // A sub-frame before the title, of another ID, is stepped over by its size in the tag's version. + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.Chapter, (byte)4)] + [DataRow (Holder.TableOfContents, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)4)] + public void Read_EmbeddedTitleAfterLargeSubFrame_ReadsTheTitle (Holder holder, byte version) + { + var other = new byte[300]; + var data = TagWith (holder, version, [ + .. SubFrameHeader ("TIT3", other.Length, version, 0), .. other, + .. SubFrameHeader ("TIT2", TitleBody.Length, version, 0), .. TitleBody]); + + Assert.AreEqual ("Intro", Title (Id3v2Tag.Read (data).Tag!, holder)); + } + + // Only a TIT2 is the title: another text frame after it is not read as one. + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.Chapter, (byte)4)] + [DataRow (Holder.TableOfContents, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)4)] + public void Read_EmbeddedTitleBeforeAnotherTextFrame_ReadsTheTitle (Holder holder, byte version) + { + byte[] subtitle = [0, .. "Sub"u8]; + var data = TagWith (holder, version, [ + .. SubFrameHeader ("TIT2", TitleBody.Length, version, 0), .. TitleBody, + .. SubFrameHeader ("TIT3", subtitle.Length, version, 0), .. subtitle]); + + Assert.AreEqual ("Intro", Title (Id3v2Tag.Read (data).Tag!, holder)); + } + + // Two TIT2 sub-frames, which the addendum does not forbid: the last one that reads is the title, as before #261. + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)4)] + public void Read_TwoEmbeddedTitles_ReadsTheLast (Holder holder, byte version) + { + byte[] second = [0, .. "Outro"u8]; + var data = TagWith (holder, version, [ + .. SubFrameHeader ("TIT2", TitleBody.Length, version, 0), .. TitleBody, + .. SubFrameHeader ("TIT2", second.Length, version, 0), .. second]); + + Assert.AreEqual ("Outro", Title (Id3v2Tag.Read (data).Tag!, holder)); + } + + // The embedded walk takes sizes and flags from the file: no cut or changed byte makes a read or a save throw. + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.Chapter, (byte)4)] + [DataRow (Holder.TableOfContents, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)4)] + public void ReadAndRender_DamagedEmbeddedFrames_DoNotThrow (Holder holder, byte version) + { + var data = TagWith (holder, version, [ + .. SubFrameHeader ("TIT3", 3, version, 0), 0, (byte)'a', (byte)'b', + .. SubFrameHeader ("TIT2", 5, version, version == 4 ? (byte)0x01 : (byte)0x20), 0, 0, 0, 1, 0]); + + static void ReadAndRender (byte[] bytes) + { + if (Id3v2Tag.Read (bytes).Tag is { } tag) + tag.Render (); + } + + Assert.IsGreaterThan (0, Hostile.EveryTruncation (data, ReadAndRender)); + Assert.IsGreaterThan (0, Hostile.ByteFlips (data, ReadAndRender)); + } +} From 1a4fd501ffa7fea4b692a0ca542e6256249ae802 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:53:11 -0700 Subject: [PATCH 3/7] fix: Write an ID3v2 frame's text in an encoding that holds it, never as '?' (#262) --- CHANGELOG.md | 1 + .../Id3/Id3v2/Frames/CommentFrame.cs | 3 +- .../Id3/Id3v2/Frames/GeneralObjectFrame.cs | 3 +- .../Id3/Id3v2/Frames/InvolvedPeopleFrame.cs | 3 +- .../Id3/Id3v2/Frames/LyricsFrame.cs | 3 +- .../Id3/Id3v2/Frames/PictureFrame.cs | 3 +- .../Id3/Id3v2/Frames/SyncLyricsFrame.cs | 3 +- .../Id3/Id3v2/Frames/TextFrame.cs | 3 +- .../Id3/Id3v2/Frames/UserTextFrame.cs | 3 +- .../Id3/Id3v2/Frames/UserUrlFrame.cs | 3 +- src/TagLibSharp2/Id3/Id3v2/Id3Text.cs | 17 ++- .../Id3/Id3v2/TextEncodingType.cs | 2 + .../Id3/Id3v2/Id3v2WrittenEncodingTests.cs | 117 +++++++++++++++++- 13 files changed, 147 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bed06132..bc492e91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- 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 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/Id3/Id3v2/Frames/CommentFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs index 91f5cd8f..cdc4756e 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/CommentFrame.cs @@ -109,7 +109,8 @@ public static CommentFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content including encoding byte, language, description, and text. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs index efcb39d4..4260fec0 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/GeneralObjectFrame.cs @@ -121,7 +121,8 @@ public static GeneralObjectFrameReadResult Read (ReadOnlySpan data, Id3v2V /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs index 54e1d745..4518d7e7 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/InvolvedPeopleFrame.cs @@ -264,7 +264,8 @@ public static InvolvedPeopleFrameReadResult Read (string frameId, ReadOnlySpan /// The frame content including encoding byte. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs index e8a87926..3d19b297 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/LyricsFrame.cs @@ -109,7 +109,8 @@ public static LyricsFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content including encoding byte, language, description, and lyrics. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs index dab28f54..7ae57e1d 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/PictureFrame.cs @@ -317,8 +317,9 @@ static bool StartsWithImageMimeType (ReadOnlySpan afterEncoding) => /// /// The returned data does NOT include the frame header (frame ID + size + flags). /// Use to create a complete tag with frame headers. + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. /// - public BinaryData RenderContent () => Render (TextEncoding); + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs index 50919501..bd9679f9 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/SyncLyricsFrame.cs @@ -276,7 +276,8 @@ public static SyncLyricsFrameReadResult Read (ReadOnlySpan data, Id3v2Vers /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs index c6fdfae1..065cf37d 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TextFrame.cs @@ -86,7 +86,8 @@ public static TextFrameReadResult Read (string frameId, ReadOnlySpan data, /// Renders the frame content to binary data. /// /// The frame content including encoding byte. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs index 8f688fb7..81b3d431 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserTextFrame.cs @@ -117,7 +117,8 @@ public static UserTextFrameReadResult Read (ReadOnlySpan data, Id3v2Versio /// Renders the frame content to binary data. /// /// The frame content including encoding byte, description, null terminator, and value. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs index 9535df40..bb8b1837 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs @@ -90,7 +90,8 @@ public static UserUrlFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () => Render (Encoding); + /// Written as an ID3v2.4 tag writes the frame: in , or in UTF-8 when that is ISO-8859-1 and the text does not fit in it. + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); /// /// Renders the frame content for a tag of , in an encoding that version defines diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs index df2c3bab..65917589 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -58,21 +58,30 @@ internal static ReadOnlySpan CutAtFirstNul (ReadOnlySpan data, TextE /// The encoding a frame asking for is written with in a tag of . /// ID3v2.4 defines all four encodings (https://id3.org/id3v2.4.0-structure §4). ID3v2.3 defines only $00 ISO-8859-1 /// and $01 UTF-16 with a BOM (https://id3.org/id3v2.3.0 §3.3), so there a frame asking for UTF-16BE or UTF-8 is written - /// in ISO-8859-1 when every one of its fits, and in UTF-16 with a BOM otherwise. + /// in ISO-8859-1 when every one of its fits, and in UTF-16 with a BOM otherwise. A frame + /// never writes text its encoding cannot hold: one asking for ISO-8859-1 with text outside it is written in UTF-8 in + /// v2.4 and in UTF-16 with a BOM in v2.3 (#262). /// internal static TextEncodingType WrittenEncoding (TextEncodingType encoding, Id3v2Version version, params string[] texts) { - if (version >= Id3v2Version.V24 || encoding is TextEncodingType.Latin1 or TextEncodingType.Utf16WithBom) + if (encoding == TextEncodingType.Latin1) + return FitLatin1 (texts) ? encoding : version >= Id3v2Version.V24 ? TextEncodingType.Utf8 : TextEncodingType.Utf16WithBom; + if (version >= Id3v2Version.V24 || encoding == TextEncodingType.Utf16WithBom) return encoding; + return FitLatin1 (texts) ? TextEncodingType.Latin1 : TextEncodingType.Utf16WithBom; + } + /// True when ISO-8859-1 holds every character of every one of . + static bool FitLatin1 (string[] texts) + { foreach (var text in texts) { foreach (var c in text) { if (c > '\u00FF') - return TextEncodingType.Utf16WithBom; + return false; } } - return TextEncodingType.Latin1; + return true; } static int IndexOfUtf16Nul (ReadOnlySpan data) diff --git a/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs b/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs index 8a073ef2..447fc1d2 100644 --- a/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs +++ b/src/TagLibSharp2/Id3/Id3v2/TextEncodingType.cs @@ -12,6 +12,8 @@ namespace TagLibSharp2.Id3.Id3v2; /// A frame keeps the encoding it was given, and a tag writes it in one its version defines: an ID3v2.3 tag, and a /// v2.2 tag, which is written as v2.3, writes a frame that asks for or in /// when its text fits and in otherwise (https://id3.org/id3v2.3.0 §3.3). +/// A frame that asks for with text outside it is written in in v2.4 and in +/// in v2.3, never with that text replaced. /// [SuppressMessage ("Design", "CA1028:Enum storage should be Int32", Justification = "Matches ID3v2 spec single-byte encoding field")] public enum TextEncodingType : byte diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs index 3815a032..6324d513 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingTests.cs @@ -213,11 +213,9 @@ static bool TryAdd (Id3v2Tag tag, object frame) static readonly TextEncodingType[] AllEncodings = [TextEncodingType.Latin1, TextEncodingType.Utf16WithBom, TextEncodingType.Utf16BE, TextEncodingType.Utf8]; - // ISO-8859-1 cannot hold the wide text; a frame that asks for it with that text is a separate question. static IEnumerable<(TextEncodingType Encoding, Text Text)> EncodingsAndTexts => from encoding in AllEncodings from text in Enum.GetValues () - where !(encoding == TextEncodingType.Latin1 && text == Text.Wide) select (encoding, text); public static IEnumerable AddedMatrix => @@ -227,9 +225,11 @@ where TryAdd (new Id3v2Tag (), kind.Create ("x", TextEncodingType.Utf8)) from row in EncodingsAndTexts select new object[] { kind, version, row.Encoding, row.Text }; + // A file cannot hold the wide text in ISO-8859-1. public static IEnumerable ReadMatrix => from kind in FrameKinds from row in EncodingsAndTexts + where !(row.Encoding == TextEncodingType.Latin1 && row.Text == Text.Wide) select new object[] { kind, row.Encoding, row.Text }; public static string RowName (System.Reflection.MethodInfo method, object[] row) => @@ -240,9 +240,18 @@ public static string RowName (System.Reflection.MethodInfo method, object[] row) /// it, otherwise ISO-8859-1 when the text fits and UTF-16 with a BOM when it does not. /// static TextEncodingType V23Encoding (TextEncodingType encoding, Text text) => - encoding is TextEncodingType.Latin1 or TextEncodingType.Utf16WithBom ? encoding + encoding == TextEncodingType.Utf16WithBom || (encoding == TextEncodingType.Latin1 && text != Text.Wide) ? encoding : text == Text.Wide ? TextEncodingType.Utf16WithBom : TextEncodingType.Latin1; + /// + /// The encoding a tag of writes for a frame that asks for . A + /// frame never writes text its encoding cannot hold (#262): ISO-8859-1 with text outside it becomes UTF-16 with a + /// BOM in v2.3 and UTF-8 in v2.4. + /// + static TextEncodingType ExpectedEncoding (TextEncodingType encoding, Id3v2Version version, Text text) => + version != Id3v2Version.V24 ? V23Encoding (encoding, text) + : encoding == TextEncodingType.Latin1 && text == Text.Wide ? TextEncodingType.Utf8 : encoding; + // A frame a caller builds with its own encoding and adds to the tag: v2.4 writes that encoding, v2.3 one it defines. [TestMethod] [DynamicData (nameof (AddedMatrix), DynamicDataDisplayName = nameof (RowName))] @@ -254,7 +263,7 @@ public void Render_FrameWithChosenEncoding_WritesEncodingTheVersionDefinesAndRea var rendered = tag.Render ().ToArray (); - var expected = version == Id3v2Version.V24 ? encoding : V23Encoding (encoding, text); + var expected = ExpectedEncoding (encoding, version, text); Assert.IsNotEmpty (EncodingBytes (rendered)); foreach (var (id, written) in EncodingBytes (rendered)) Assert.AreEqual ((byte)expected, written, $"{id} encoding byte"); @@ -344,6 +353,106 @@ public void Render_V23FrameWithOneStringOutsideLatin1_WritesUtf16 (string name, Assert.AreEqual (expected, get (Id3v2Tag.Read (rendered).Tag!), name); } + /// + /// Each public property that sets a frame's text or encoding after the frame exists, applied to a frame read in + /// ISO-8859-1, with text ISO-8859-1 cannot hold (#262). + /// + public static IEnumerable EditRows => new (string Name, Func Create, Action Edit)[] { + ("TextFrame.Text", (s, e) => new TextFrame ("TIT2", s, e), f => ((TextFrame)f).Text = W), + ("UserTextFrame.Description", (s, e) => new UserTextFrame (s, s, e), f => ((UserTextFrame)f).Description = W), + ("UserTextFrame.Value", (s, e) => new UserTextFrame (s, s, e), f => ((UserTextFrame)f).Value = W), + ("CommentFrame.Text", (s, e) => new CommentFrame (s, "eng", s, e), f => ((CommentFrame)f).Text = W), + ("CommentFrame.Description", (s, e) => new CommentFrame (s, "eng", s, e), f => ((CommentFrame)f).Description = W), + ("LyricsFrame.Text", (s, e) => new LyricsFrame (s, "eng", s, e), f => ((LyricsFrame)f).Text = W), + ("LyricsFrame.Description", (s, e) => new LyricsFrame (s, "eng", s, e), f => ((LyricsFrame)f).Description = W), + ("UserUrlFrame.Description", (s, e) => new UserUrlFrame ("http://a.b/", s, e), f => ((UserUrlFrame)f).Description = W), + ("GeneralObjectFrame.FileName", (s, e) => new GeneralObjectFrame ("x/y", s, s, new BinaryData ([1]), e), f => ((GeneralObjectFrame)f).FileName = W), + ("GeneralObjectFrame.Description", (s, e) => new GeneralObjectFrame ("x/y", s, s, new BinaryData ([1]), e), f => ((GeneralObjectFrame)f).Description = W), + ("SyncLyricsFrame.Description", CreateSyncLyrics, f => ((SyncLyricsFrame)f).Description = W), + ("SyncLyricsFrame.AddSyncItem", CreateSyncLyrics, f => ((SyncLyricsFrame)f).AddSyncItem (W, 3000)), + ("InvolvedPeopleFrame.Add", CreateInvolvedPeople, f => ((InvolvedPeopleFrame)f).Add ("r", W)), + ("InvolvedPeopleFrame.Set", CreateInvolvedPeople, f => ((InvolvedPeopleFrame)f).Set ("Cover", W)), + ("CommentFrame.Encoding", (s, e) => new CommentFrame (W, "eng", s, TextEncodingType.Utf8), f => ((CommentFrame)f).Encoding = TextEncodingType.Latin1), + ("TextFrame.Encoding", (s, e) => new TextFrame ("TIT2", W, TextEncodingType.Utf8), f => ((TextFrame)f).Encoding = TextEncodingType.Latin1), + }.SelectMany (r => new[] { Id3v2Version.V23, Id3v2Version.V24 }.Select (v => new object[] { r.Name, r.Create, r.Edit, v })); + + /// A tag of holding the frame, read from its bytes, and that frame as read. + static (Id3v2Tag Tag, object Frame) ReadBack (object frame, Id3v2Version version) + { + var (id, body) = Body (frame); + var tag = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader ((byte)version, (uint)(10 + body.Length)), .. TestBuilders.Id3v2.CreateFrame (id, body, (byte)version)]).Tag!; + object read = frame switch { + TextFrame => tag.Frames[0], + UserTextFrame => tag.UserTextFrames[0], + CommentFrame => tag.Comments[0], + LyricsFrame => tag.LyricsFrames[0], + UserUrlFrame => tag.UserUrlFrames[0], + GeneralObjectFrame => tag.GeneralObjectFrames[0], + SyncLyricsFrame => tag.SyncLyricsFrames[0], + _ => tag.InvolvedPeopleFrames[0], + }; + return (tag, read); + } + + // A frame read in ISO-8859-1 and then given text ISO-8859-1 cannot hold is written in UTF-16 with a BOM in v2.3 and + // UTF-8 in v2.4, never as '?' (#262); what the edit set reads back. + [TestMethod] + [DynamicData (nameof (EditRows), DynamicDataDisplayName = nameof (RowName))] + public void Render_FrameEditedToTextLatin1CannotHold_WritesAnEncodingThatHoldsIt (string name, Func create, Action edit, Id3v2Version version) + { + var (tag, frame) = ReadBack (create ("Cover", TextEncodingType.Latin1), version); + edit (frame); + var expected = Describe (frame); + Assert.Contains (W, expected, name); + + var rendered = tag.Render ().ToArray (); + + var encodings = EncodingBytes (rendered); + Assert.HasCount (1, encodings, name); + Assert.AreEqual ((byte)(version == Id3v2Version.V24 ? TextEncodingType.Utf8 : TextEncodingType.Utf16WithBom), encodings[0].Encoding, name); + Assert.AreEqual (expected, Describe (ReadBack (frame, version).Frame), name + " (the frame's own render)"); + var again = Id3v2Tag.Read (rendered).Tag!; + Assert.AreEqual (expected, Describe (ReadBack (Frame (again, frame), version).Frame), name + " (fresh read)"); + } + + /// Every string a frame holds, in order. + static string Describe (object frame) => frame switch { + TextFrame f => f.Text, + UserTextFrame f => f.Description + "=" + f.Value, + CommentFrame f => f.Description + "=" + f.Text, + LyricsFrame f => f.Description + "=" + f.Text, + UserUrlFrame f => f.Description + "=" + f.Url, + GeneralObjectFrame f => f.FileName + "=" + f.Description, + SyncLyricsFrame f => f.Description + "=" + string.Join ("|", f.SyncItems.Select (i => i.Text)), + InvolvedPeopleFrame f => string.Join ("|", f.Pairs.Select (p => p.Role + "=" + p.Person)), + _ => throw new ArgumentException (frame.GetType ().Name), + }; + + /// The frame of 's kind in . + static object Frame (Id3v2Tag tag, object like) => like switch { + TextFrame => tag.Frames[0], + UserTextFrame => tag.UserTextFrames[0], + CommentFrame => tag.Comments[0], + LyricsFrame => tag.LyricsFrames[0], + UserUrlFrame => tag.UserUrlFrames[0], + GeneralObjectFrame => tag.GeneralObjectFrames[0], + SyncLyricsFrame => tag.SyncLyricsFrames[0], + _ => tag.InvolvedPeopleFrames[0], + }; + + // A frame's own RenderContent (), outside a tag, writes text ISO-8859-1 cannot hold in UTF-8 (#262), as a v2.4 tag + // does; the picture's description too. + [TestMethod] + public void RenderContent_Latin1FrameWithWideText_WritesUtf8 () + { + foreach (var kind in FrameKinds) { + var (id, body) = Body (kind.Create (W, TextEncodingType.Latin1)); + Assert.AreEqual ((byte)TextEncodingType.Utf8, body[0], id); + var tag = Id3v2Tag.Read ([.. TestBuilders.Id3v2.CreateHeader (4, (uint)(10 + body.Length)), .. TestBuilders.Id3v2.CreateFrame (id, body, 4)]).Tag!; + Assert.AreEqual (kind.Expected (W), kind.Get (tag), id); + } + } + // A CHAP or CTOC rendered on its own, outside a tag, embeds its title as ID3v2.4 does: in UTF-8. [TestMethod] public void RenderContent_ChapterAndTableOfContentsOnTheirOwn_EmbedUtf8Title () From 096805159a27aba3b9ccb69efb488b6b428dd7c9 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 10:32:59 -0700 Subject: [PATCH 4/7] fix: Keep every frame an ID3v2 CHAP or CTOC embeds across a save (#265) --- CHANGELOG.md | 1 + .../Id3/Id3v2/Frames/ChapterFrame.cs | 22 +- .../Id3/Id3v2/Frames/TableOfContentsFrame.cs | 22 +- .../Id3/Id3v2/Id3v2Tag.FrameWalk.cs | 141 +++++++- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 25 +- src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs | 6 + .../Id3/Id3v2/Id3v2EmbeddedFrameTests.cs | 340 ++++++++++++++++++ .../Id3v2/Id3v2WrittenEncodingCarrierTests.cs | 28 +- 8 files changed, 540 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc492e91..22271d70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A save keeps every frame an ID3v2 CHAP or CTOC embeds, such as a chapter's subtitle (TIT3), link (WXXX) or image (APIC), and frames this library does not know (#265). Only the embedded title (TIT2) was kept, and every other embedded frame was dropped on any save. A save that does not change the chapter's title writes the CHAP or CTOC as it was read; a new title is written as a new TIT2 where the old one was, and the other frames as they were stored, with their flags. An embedded frame read from a v2.3 tag in a text encoding v2.3 does not define, such as a chapter title 0.6 and earlier wrote in UTF-8, is written again in ISO-8859-1 or UTF-16 with a BOM, as the tag's other frames are (#255), keeping its status flags and group byte but not its compression; deciding this inflates a compressed frame's first byte only, and a frame that cannot be re-encoded is kept as stored. A chapter moved to a tag of another version writes each embedded frame this library reads as that version writes it, and any other frame with its content as its format flags give it and no flags; an encrypted one is left out - 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 diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs index b92302cf..b0e26bc6 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs @@ -74,6 +74,9 @@ public sealed class ChapterFrame /// public string? Title { get; set; } + // The frames embedded when this frame was read, written back by a save (#265); null for a frame built here. + EmbeddedFrames? _embedded; + /// /// Initializes a new instance of the class. /// @@ -134,8 +137,9 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version EndByteOffset = endOffset }; - // Embedded sub-frames, with the tag's frame header and flags. Only the title is read. - frame.Title = Id3v2Tag.ReadEmbeddedTitle (data.Slice (offset), version); + // Embedded sub-frames, with the tag's frame header and flags: the title is read, and every frame is kept. + frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version); + frame.Title = frame._embedded.Title; return ChapterFrameReadResult.Success (frame, data.Length); } @@ -152,17 +156,10 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// internal BinaryData RenderContent (Id3v2Version version) { - // Render embedded TIT2 if title is set - BinaryData? titleFrameData = null; - if (!string.IsNullOrEmpty (Title)) - titleFrameData = new TextFrame ("TIT2", Title!).RenderContent (version); - var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); var baseSize = elementIdBytes.Length + 1 + 16; // +1 for null, +16 for times/offsets var totalSize = baseSize; - if (titleFrameData.HasValue) - totalSize += 10 + titleFrameData.Value.Length; // 10 for frame header using var builder = new BinaryDataBuilder (totalSize); @@ -182,11 +179,8 @@ internal BinaryData RenderContent (Id3v2Version version) // End byte offset (4 bytes, big-endian) AddUInt32BE (builder, EndByteOffset); - // Embedded TIT2 frame, with the tag's frame header - if (titleFrameData.HasValue) { - Id3v2Tag.AddFrameHeader (builder, "TIT2", titleFrameData.Value.Length, version); - builder.Add (titleFrameData.Value); - } + // Embedded frames, with the tag's frame header: the title, and every other frame read (#265) + Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version); return builder.ToBinaryData (); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs index c307f2bc..2344de37 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs @@ -63,6 +63,9 @@ public sealed class TableOfContentsFrame /// public string? Title { get; set; } + // The frames embedded when this frame was read, written back by a save (#265); null for a frame built here. + EmbeddedFrames? _embedded; + /// /// Gets the list of child element IDs (references to CHAP or other CTOC frames). /// @@ -157,8 +160,9 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v offset += childNullIndex + 1; } - // Embedded sub-frames, with the tag's frame header and flags. Only the title is read. - frame.Title = Id3v2Tag.ReadEmbeddedTitle (data.Slice (offset), version); + // Embedded sub-frames, with the tag's frame header and flags: the title is read, and every frame is kept. + frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version); + frame.Title = frame._embedded.Title; return TableOfContentsFrameReadResult.Success (frame, data.Length); } @@ -175,11 +179,6 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v /// internal BinaryData RenderContent (Id3v2Version version) { - // Render embedded TIT2 if title is set - BinaryData? titleFrameData = null; - if (!string.IsNullOrEmpty (Title)) - titleFrameData = new TextFrame ("TIT2", Title!).RenderContent (version); - var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); // Calculate child IDs size @@ -190,8 +189,6 @@ internal BinaryData RenderContent (Id3v2Version version) var baseSize = elementIdBytes.Length + 1 + 1 + 1 + childIdsSize; // +1 null, +1 flags, +1 count var totalSize = baseSize; - if (titleFrameData.HasValue) - totalSize += 10 + titleFrameData.Value.Length; // 10 for frame header using var builder = new BinaryDataBuilder (totalSize); @@ -216,11 +213,8 @@ internal BinaryData RenderContent (Id3v2Version version) builder.Add ((byte)0x00); } - // Embedded TIT2 frame, with the tag's frame header - if (titleFrameData.HasValue) { - Id3v2Tag.AddFrameHeader (builder, "TIT2", titleFrameData.Value.Length, version); - builder.Add (titleFrameData.Value); - } + // Embedded frames, with the tag's frame header: the title, and every other frame read (#265) + Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version); return builder.ToBinaryData (); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs index b1f02b65..15d0d363 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs @@ -116,25 +116,29 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt } /// - /// The title among the frames a CHAP or CTOC embeds, which use "the same frame header format as the tag" (ID3v2 - /// Chapter Frame Addendum §3.1, §3.2): each header is read by and each frame's format flags - /// by , as a top-level frame of is. The last TIT2 that - /// reads wins; null when none does. + /// The frames a CHAP or CTOC embeds, which use "the same frame header format as the tag" (ID3v2 Chapter Frame + /// Addendum §3.1, §3.2): each header is read by and each frame's format flags by + /// , as a top-level frame of is. Every frame is kept as + /// stored, so a save writes it back (#265); the title is the last TIT2 that reads, or null. /// - internal static string? ReadEmbeddedTitle (ReadOnlySpan subFrames, Id3v2Version version) + internal static EmbeddedFrames ReadEmbeddedFrames (ReadOnlySpan subFrames, Id3v2Version version) { var major = (byte)version; var headerSize = FrameHeaderLength (major); string? title = null; + var frames = new List (); while (true) { var step = NextFrame (subFrames, subFrames.Length, major); if (step.Kind == FrameStepKind.Stop) break; + var status = major == 2 ? (byte)0 : subFrames[8]; + var format = major == 2 ? (byte)0 : subFrames[9]; + var body = subFrames.Slice (headerSize, step.Size); + if (step.Id.Length == 4) + frames.Add (new UnreadFrame (step.Id, status, format, body.ToArray (), major)); if (step.Kind == FrameStepKind.Frame && step.Id == "TIT2") { - var format = major == 2 ? (byte)0 : subFrames[9]; - var content = ProcessFrameFlags (subFrames.Slice (headerSize, step.Size), format, major); - var read = TextFrame.Read (step.Id, content, version); + var read = TextFrame.Read (step.Id, ProcessFrameFlags (body, format, major), version); if (read.IsSuccess) title = read.Frame!.Text; } @@ -142,7 +146,126 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt subFrames = subFrames.Slice (headerSize + step.Size); } - return title; + return new EmbeddedFrames (title, frames); + } + + /// + /// Adds the frames a CHAP or CTOC embeds, for a tag written as (#265). While + /// is the one read, every frame read is written as stored, in order. A changed title is + /// written as a new TIT2 where the first TIT2 was, or first, and the frames read are written without their TIT2s. + /// A frame read from a tag of another version (a CHAP moved between tags) is written as + /// says. + /// + internal static void AddEmbeddedFrames (BinaryDataBuilder builder, string? title, EmbeddedFrames? read, Id3v2Version version) + { + var written = (int)version; + var stored = read?.Frames ?? []; + var keepTitle = read is not null && title == read.Title; + var titlePending = !keepTitle && !string.IsNullOrEmpty (title); + if (titlePending && !stored.Any (f => f.Id == "TIT2")) + titlePending = AddTitle (builder, title!, version); + + foreach (var frame in stored) { + if (frame.Id == "TIT2" && !keepTitle) { + if (titlePending) + titlePending = AddTitle (builder, title!, version); + continue; + } + + if (frame.FitsVersion (written) && !InUndefinedEncoding (frame, version)) { + var same = frame.Version == written; + AddFrameHeader (builder, frame.Id, frame.Body.Length, version, same ? frame.Status : (byte)0, same ? frame.Format : (byte)0); + builder.Add (frame.Body); + } else { + AddConverted (builder, frame, version); + } + } + } + + static bool AddTitle (BinaryDataBuilder builder, string title, Id3v2Version version) + { + var content = new TextFrame ("TIT2", title).RenderContent (version); + AddFrameHeader (builder, "TIT2", content.Length, version); + builder.Add (content); + return false; + } + + /// + /// Adds an embedded frame that cannot be written as stored: one read from a tag of another version than + /// , or one whose text encoding does not define + /// (). A frame this library reads is written as a tag of + /// writes it, in an encoding that version defines; one re-encoded in its own version keeps its status flags and group + /// byte, but not its compression, encryption or data length indicator. Any other frame is written with no format flags and its content + /// as its flags give it: decompressed, re-synchronised, and without a group byte. An encrypted frame, or one that + /// does not decompress, has no content to carry and is left out. A CHAP or CTOC inside one is not read here, so a + /// file cannot make this recurse; it is kept as bytes, and its own embedded headers stay in the size form of the + /// version it was read from. + /// + static void AddConverted (BinaryDataBuilder builder, UnreadFrame frame, Id3v2Version version) + { + var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version); + if (frame.Id is not ("CHAP" or "CTOC")) { + var tag = new Id3v2Tag (version); + if (tag.ReadFrame (frame.Id, content, (Id3v2Version)frame.Version)) { + var rendered = tag.Render (0, withFooter: false).Span.Slice (Id3v2Header.HeaderSize); + if (frame.Version != (int)version) { + builder.Add (rendered); + return; + } + + // Re-encoded in its own version: the status flags and the group byte stay. The frame is written again, + // so its compression, encryption and data length indicator do not. + var body = rendered.Slice (FrameHeaderSizeV23); + var group = GroupByte (frame); + var grouping = version == Id3v2Version.V24 ? (byte)0x40 : (byte)0x20; + AddFrameHeader (builder, frame.Id, body.Length + (group < 0 ? 0 : 1), version, frame.Status, group < 0 ? (byte)0 : grouping); + if (group >= 0) + builder.Add ((byte)group); + builder.Add (body); + return; + } + } + + // A frame of the tag's own version that cannot be converted is written as stored, never dropped. + if (frame.Version == (int)version) { + AddFrameHeader (builder, frame.Id, frame.Body.Length, version, frame.Status, frame.Format); + builder.Add (frame.Body); + return; + } + + if (content.IsEmpty && frame.Body.Length > 0) + return; + AddFrameHeader (builder, frame.Id, content.Length, version); + builder.Add (content); + } + + /// + /// The group byte of a grouped frame, or -1: in ID3v2.4 it comes first (§4.1.2); in ID3v2.3 after the 4-byte + /// decompressed size of a compressed frame (§3.3.1), as reads it (#272). + /// + static int GroupByte (UnreadFrame frame) + { + int at; + if (frame.Version == 4) + at = (frame.Format & 0x40) != 0 ? 0 : -1; + else + at = (frame.Format & 0x20) != 0 ? ((frame.Format & 0x80) != 0 ? 4 : 0) : -1; + return at >= 0 && at < frame.Body.Length ? frame.Body[at] : -1; + } + + /// + /// True when starts with a text encoding byte that a tag of does + /// not define: 2 or 3 in ID3v2.3, which defines only 0 and 1 (https://id3.org/id3v2.3.0 §3.3). Every frame written + /// into a v2.3 tag uses an encoding v2.3 defines (#255), so such a frame, as 0.6 and earlier wrote a chapter title, + /// is written again rather than as stored. + /// + static bool InUndefinedEncoding (UnreadFrame frame, Id3v2Version version) + { + if (version == Id3v2Version.V24 || !(frame.Id[0] == 'T' || frame.Id is "COMM" or "USLT" or "APIC" or "WXXX" or "GEOB" or "SYLT" or "IPLS")) + return false; + // The encoding byte is the first: a compressed frame is inflated that far only. + var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version, inflateAtMost: 1); + return !content.IsEmpty && content[0] is 2 or 3; } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 0c598cb9..a0d97b5c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -2884,7 +2884,7 @@ static byte[] RemoveUnsynchronization (ReadOnlySpan data) /// grouping identity (1 byte), then data length indicator (4 bytes). /// /// - static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte formatFlags, int majorVersion) + static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte formatFlags, int majorVersion, int inflateAtMost = int.MaxValue) { if (content.Length == 0 || formatFlags == 0) return content; @@ -2952,7 +2952,7 @@ static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte fo if (decompressedSize <= 0) return ReadOnlySpan.Empty; - var decompressed = DecompressZlib (data, decompressedSize); + var decompressed = DecompressZlib (data, decompressedSize, inflateAtMost); if (decompressed is null) return ReadOnlySpan.Empty; @@ -3150,7 +3150,10 @@ static int ReadSyncsafeInt32 (ReadOnlySpan data) /// /// Decompresses zlib-compressed data. /// - static byte[]? DecompressZlib (ReadOnlySpan data, int expectedSize) + /// The zlib data. + /// The decompressed size the frame declares; the bounds are checked against it. + /// Inflate only this many bytes from the start, for a caller that needs only those. + static byte[]? DecompressZlib (ReadOnlySpan data, int expectedSize, int atMost = int.MaxValue) { const int MaxDecompressedBytes = 16 * 1024 * 1024; // A repeated byte passes 1000:1 (about 1001:1 at 800 KB) and stays under 16 MiB. @@ -3174,7 +3177,8 @@ static int ReadSyncsafeInt32 (ReadOnlySpan data) using var deflate = new System.IO.Compression.DeflateStream (input, System.IO.Compression.CompressionMode.Decompress); // expectedSize is already within the cap. A full read returns this buffer. - var buffer = new byte[expectedSize]; + var prefix = atMost < expectedSize; + var buffer = new byte[prefix ? atMost : expectedSize]; var total = 0; while (total < buffer.Length) { var read = deflate.Read (buffer, total, buffer.Length - total); @@ -3186,6 +3190,19 @@ static int ReadSyncsafeInt32 (ReadOnlySpan data) if (total == 0) return null; + // A prefix read accepts what a full read accepts: the rest is inflated through a small buffer and counted, + // so a stream that inflates past the declared size is refused here too, with no more allocated. + if (prefix && total == buffer.Length) { + var counted = total; + var scratch = new byte[Math.Min (4096, expectedSize)]; + while (counted < expectedSize) { + var read = deflate.Read (scratch, 0, Math.Min (scratch.Length, expectedSize - counted)); + if (read == 0) + break; + counted += read; + } + } + var extra = new byte[1]; if (deflate.Read (extra, 0, 1) > 0) return null; diff --git a/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs b/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs index 7d9a5311..78980647 100644 --- a/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/UnreadFrame.cs @@ -20,3 +20,9 @@ internal sealed record UnreadFrame (string Id, byte Status, byte Format, byte[] public bool FitsVersion (int writtenVersion) => Version == writtenVersion || (Version == 2 && writtenVersion == 3 && Id is not ("LINK" or "APIC")); } + +/// +/// The frames a CHAP or CTOC embedded when it was read, each as stored, and the title its TIT2 read as +/// (). +/// +internal sealed record EmbeddedFrames (string? Title, IReadOnlyList Frames); diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs index 622327db..96cd689f 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2EmbeddedFrameTests.cs @@ -207,6 +207,346 @@ .. SubFrameHeader ("TIT2", TitleBody.Length, version, 0), .. TitleBody, Assert.AreEqual ("Outro", Title (Id3v2Tag.Read (data).Tag!, holder)); } + /// A sub-frame with its header in , its status byte and its format byte. + static byte[] SubFrame (string id, byte version, byte[] body, byte status = 0, byte format = 0) + { + var header = SubFrameHeader (id, body.Length, version, format); + header[8] = status; + return [.. header, .. body]; + } + + /// One embedded frame as stored: its ID, status and format flags, and body. + public sealed record Stored (string Id, byte[] Body, byte Status = 0, byte Format = 0) + { + public byte[] Bytes (byte version) => SubFrame (Id, version, Body, Status, Format); + } + + /// The sub-frames each kind of CHAP or CTOC under test holds, in a tag of . + static Stored[] SubFrames (string set, byte version) => set switch { + // The frames chapter writers embed (ID3v2 Chapter Frame Addendum §3.1 example): a subtitle in UTF-16, the + // title after it, a link and an image with a status flag, and a second TIT2, which the last-read rule makes the + // title. + "subtitle-title-url-picture-title" => [ + new ("TIT3", [1, 0xFF, 0xFE, (byte)'s', 0, (byte)'u', 0, (byte)'b', 0]), + new ("TIT2", [0, .. "Intro"u8]), + new ("WXXX", [0, .. "link"u8, 0, .. "http://a.b/c"u8], Status: version == 4 ? (byte)0x20 : (byte)0x40), + new ("APIC", [0, .. "image/jpeg"u8, 0, 3, .. "img"u8, 0, 0xFF, 0xD8, 0xFF, 0xD9]), + new ("TIT2", [0, .. "Again"u8])], + // A frame of an ID this library does not know, grouped (v2.3 0x20, v2.4 0x40), and an empty one. + _ => [ + new ("TIT2", [0, .. "Intro"u8]), + new ("ZZZ1", [0x07, 1, 2, 3, 0, 255], Format: version == 4 ? (byte)0x40 : (byte)0x20), + new ("ZZZ2", [])], + }; + + static readonly string[] Sets = ["subtitle-title-url-picture-title", "unknown"]; + static readonly string[] Edits = ["none", "title", "other-field"]; + static readonly byte[] VersionBytes = [3, 4]; + + public static IEnumerable KeepMatrix => + from format in Id3v22CarrierBuilder.Formats + from holder in Enum.GetValues () + from version in VersionBytes + from set in Sets + from edit in Edits + from save in Id3v2WrittenEncodingCarrierTests.Saves + where Id3v2WrittenEncodingCarrierTests.HasSave (format.Format, save) + select new object[] { format.Format, format.Extension, holder, version, set, edit, save }; + + // Every frame a CHAP or CTOC embeds is written back on every save, in every carrier (#265). A save that does not + // change the title writes the CHAP or CTOC as it was read; one that does writes the new TIT2 where the first TIT2 + // was, drops any other TIT2, and writes every other sub-frame as it was stored, flags and all. + [TestMethod] + [DynamicData (nameof (KeepMatrix))] + public async Task Save_EmbeddedSubFrames_AreWrittenBack (string format, string extension, Holder holder, byte version, string set, string edit, string save) + { + var stored = SubFrames (set, version); + byte[] subFrames = [.. stored.SelectMany (f => f.Bytes (version))]; + var tag = TagWith (holder, version, subFrames); + var id = holder == Holder.Chapter ? "CHAP" : "CTOC"; + var originalBody = Id3v2WrittenEncodingTests.WrittenFrames (tag).First (f => f.Id == id).Body; + var original = Id3v22CarrierBuilder.Build (format, tag); + + var saved = Id3v2WrittenEncodingCarrierTests.WrittenTag (await Id3v2WrittenEncodingCarrierTests.ReadEditAndSaveAsync (original, extension, save, t => { + if (edit == "title") { + if (holder == Holder.Chapter) + t.GetChapter ("ch1")!.Title = "Changed"; + else + t.GetTableOfContents ()!.Title = "Changed"; + } else if (edit == "other-field") + t.Title = "Song"; + })); + + var savedBody = Id3v2WrittenEncodingTests.WrittenFrames (saved).First (f => f.Id == id).Body; + if (edit != "title") { + CollectionAssert.AreEqual (originalBody, savedBody, "an unchanged " + id + " is written as read"); + return; + } + var fixedLength = originalBody.Length - subFrames.Length; + CollectionAssert.AreEqual (originalBody[..fixedLength], savedBody[..fixedLength], "the fields before the sub-frames"); + // A new title is UTF-8 in v2.4 and ISO-8859-1 in v2.3 (#255), where the first TIT2 was; a later TIT2 goes. + var newTitle = new Stored ("TIT2", [version == 4 ? (byte)3 : (byte)0, .. "Changed"u8]); + var firstTitle = Array.FindIndex (stored, f => f.Id == "TIT2"); + var expected = stored.Where ((f, i) => f.Id != "TIT2" || i == firstTitle).Select ((f, i) => f.Id == "TIT2" ? newTitle : f); + CollectionAssert.AreEqual (expected.SelectMany (f => f.Bytes (version)).ToArray (), savedBody[fixedLength..], "the sub-frames"); + Assert.AreEqual ("Changed", Title (Id3v2Tag.Read (saved).Tag!, holder)); + } + + // ID3v2.3 defines only encodings 0 and 1 (#255), and embedded frames count: a CHAP or CTOC read from a v2.3 tag with + // a text frame in UTF-8 or UTF-16BE, as 0.6 and earlier wrote a chapter title, writes it in ISO-8859-1 or UTF-16 with + // a BOM on any save, with the same text. An embedded frame in 0 or 1 keeps its bytes. + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.Chapter, (byte)2)] + [DataRow (Holder.TableOfContents, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)2)] + public void Render_V23EmbeddedTextInUndefinedEncoding_IsRewrittenInV23 (Holder holder, byte encoding) + { + byte[] Text (string text) => encoding == 3 + ? [3, .. System.Text.Encoding.UTF8.GetBytes (text)] + : [2, .. System.Text.Encoding.BigEndianUnicode.GetBytes (text)]; + var kept = new Stored ("TIT1", [1, 0xFF, 0xFE, (byte)'k', 0]); + byte[] subFrames = [ + .. SubFrame ("TIT2", 3, Text ("Caf\u00E9")), + .. SubFrame ("TIT3", 3, Text ("\u65E5\u672C")), + .. kept.Bytes (3)]; + var tag = Id3v2Tag.Read (TagWith (holder, 3, subFrames)).Tag!; + tag.Album = "edited"; + + var written = tag.Render ().ToArray (); + + var frames = Id3v2WrittenEncodingTests.WrittenFrames (written); + var holderAt = frames.FindIndex (f => f.Id == (holder == Holder.Chapter ? "CHAP" : "CTOC")); + var sub = frames.Skip (holderAt + 1).Take (3).ToList (); + Assert.AreEqual ("TIT2,TIT3,TIT1", string.Join (",", sub.Select (f => f.Id))); + byte[] title = [0, .. System.Text.Encoding.Latin1.GetBytes ("Caf\u00E9")]; + byte[] subtitle = [1, 0xFF, 0xFE, .. System.Text.Encoding.Unicode.GetBytes ("\u65E5\u672C")]; + CollectionAssert.AreEqual (title, sub[0].Body); + CollectionAssert.AreEqual (subtitle, sub[1].Body); + CollectionAssert.AreEqual (kept.Body, sub[2].Body); + Assert.AreEqual ("Caf\u00E9", Title (Id3v2Tag.Read (written).Tag!, holder)); + } + + /// + /// A body in UTF-8 of each frame ID whose first byte is a text encoding, built by the frame's own render (#255's + /// rule for embedded frames). + /// + public static IEnumerable EncodedIds => new (string Id, byte[] Body)[] { + ("TIT3", new TextFrame ("TIT3", "\u00E9t\u00E9", TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("TXXX", new UserTextFrame ("d\u00E9", "v", TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("COMM", new CommentFrame ("t\u00E9", "eng", "d", TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("USLT", new LyricsFrame ("t\u00E9", "eng", "d", TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("APIC", new PictureFrame ("image/jpeg", TagLibSharp2.Core.PictureType.FrontCover, "d\u00E9", [0xFF, 0xD8], TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("WXXX", new UserUrlFrame ("http://a.b/", "d\u00E9", TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("GEOB", new GeneralObjectFrame ("x/y", "f\u00E9", "d", new TagLibSharp2.Core.BinaryData ([1]), TextEncodingType.Utf8).RenderContent ().ToArray ()), + ("SYLT", SyltBody ()), + ("IPLS", IplsBody ()), + }.Select (r => new object[] { r.Id, r.Body }); + + static byte[] SyltBody () + { + var frame = new SyncLyricsFrame { Description = "d\u00E9", Encoding = TextEncodingType.Utf8 }; + frame.AddSyncItem ("l\u00E9", 1000); + return frame.RenderContent ().ToArray (); + } + + static byte[] IplsBody () + { + var frame = new InvolvedPeopleFrame (InvolvedPeopleFrameType.InvolvedPeople) { Encoding = TextEncodingType.Utf8 }; + frame.Add ("r\u00E9", "p"); + return frame.RenderContent ().ToArray (); + } + + // Every frame ID whose first byte is a text encoding is held to it when embedded in a v2.3 CHAP: one in UTF-8 is + // written in ISO-8859-1 on a save (#255), whichever frame it is. + [TestMethod] + [DynamicData (nameof (EncodedIds))] + public void Render_V23EmbeddedFrameOfEachEncodedIdInUtf8_IsRewrittenInV23 (string id, byte[] body) + { + Assert.AreEqual (3, body[0], id); + var tag = Id3v2Tag.Read (TagWith (Holder.Chapter, 3, SubFrame (id, 3, body))).Tag!; + tag.Album = "edited"; + + var written = Id3v2WrittenEncodingTests.WrittenFrames (tag.Render ().ToArray ()); + + var sub = written.Single (f => f.Id == id); + Assert.AreEqual (0, sub.Body[0], id + " encoding byte"); + } + + // A frame re-encoded for its tag's version keeps its status flags and group byte (v2.3: status 0x20 read-only, + // format 0x20 grouping). Its compression does not carry: the frame is written again, uncompressed. + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Render_V23GroupedEmbeddedFrameReEncoded_KeepsStatusAndGroupByte (bool compressed) + { + byte[] text = [3, .. "Sub"u8]; + byte[] body = compressed ? [0, 0, 0, (byte)text.Length, 0x07, .. Deflate (text)] : [0x07, .. text]; + var tag = Id3v2Tag.Read (TagWith (Holder.Chapter, 3, SubFrame ("TIT3", 3, body, status: 0x20, format: compressed ? (byte)0xA0 : (byte)0x20))).Tag!; + tag.Album = "edited"; + + var rendered = tag.Render ().ToArray (); + + var at = rendered.AsSpan ().IndexOf ("TIT3"u8); + byte[] expected = [.. "TIT3"u8, 0, 0, 0, 5, 0x20, 0x20, 0x07, 0, .. "Sub"u8]; + CollectionAssert.AreEqual (expected, rendered[at..(at + expected.Length)]); + } + + // Deciding whether a compressed embedded text frame needs a new encoding inflates its first byte only: a save's + // allocation does not grow with how far the frame inflates. + [TestMethod] + public void Render_V23CompressedEmbeddedText_DoesNotInflateTheWholeFrame () + { + static Id3v2Tag TagInflatingTo (int size) + { + byte[] text = [0, .. Enumerable.Repeat ((byte)'a', size)]; + byte[] body = [(byte)(text.Length >> 24), (byte)(text.Length >> 16), (byte)(text.Length >> 8), (byte)text.Length, .. Deflate (text)]; + return Id3v2Tag.Read (TagWith (Holder.Chapter, 3, SubFrame ("TIT3", 3, body, format: 0x80))).Tag!; + } + + var small = TagInflatingTo (1 << 20); + var large = TagInflatingTo (4 << 20); + small.Render (); + large.Render (); + + var smallBytes = Bounds.AllocatedBytes (() => small.Render ()); + var largeBytes = Bounds.AllocatedBytes (() => large.Render ()); + + Assert.IsLessThan (512 * 1024, largeBytes - smallBytes, $"N: {smallBytes} bytes, 4N: {largeBytes} bytes"); + } + + // A compressed v2.3 text frame in UTF-8 whose stream inflates past its declared size cannot be read or re-encoded; + // it is written as stored, never dropped, on a save with no edit and on one that changes the title. + [TestMethod] + [DataRow ("TIT2", false)] + [DataRow ("TIT2", true)] + [DataRow ("TIT3", false)] + [DataRow ("TIT3", true)] + public void Render_V23CompressedTextLongerThanDeclared_IsKeptAsStored (string id, bool editTitle) + { + byte[] text = [3, .. Enumerable.Repeat ((byte)'a', 5000)]; + var refused = SubFrame (id, 3, [0, 0, 0, 100, .. Deflate (text)], format: 0x80); + byte[] subFrames = [.. SubFrame ("XAAA", 3, [1, 2]), .. refused, .. SubFrame ("XZZZ", 3, [3, 4])]; + var tag = TagWith (Holder.Chapter, 3, subFrames); + var originalBody = Id3v2WrittenEncodingTests.WrittenFrames (tag).First (f => f.Id == "CHAP").Body; + var read = Id3v2Tag.Read (tag).Tag!; + if (editTitle) + read.GetChapter ("ch1")!.Title = "Changed"; + + var body = Id3v2WrittenEncodingTests.WrittenFrames (read.Render ().ToArray ()).First (f => f.Id == "CHAP").Body; + + var fixedLength = originalBody.Length - subFrames.Length; + if (!editTitle) { + CollectionAssert.AreEqual (originalBody, body); + return; + } + // The refused TIT2 is the title being replaced, in its place; a refused TIT3 stays as stored, and the new title, + // with no TIT2 to take the place of, comes first. + var title = SubFrame ("TIT2", 3, [0, .. "Changed"u8]); + byte[] expected = id == "TIT2" + ? [.. SubFrame ("XAAA", 3, [1, 2]), .. title, .. SubFrame ("XZZZ", 3, [3, 4])] + : [.. title, .. SubFrame ("XAAA", 3, [1, 2]), .. refused, .. SubFrame ("XZZZ", 3, [3, 4])]; + CollectionAssert.AreEqual (expected, body[fixedLength..]); + } + + // An embedded frame in UTF-8 in a v2.3 tag that this library cannot read (a COMM too short for its language) cannot + // be re-encoded; it is written as stored, its status flag too, never dropped. + [TestMethod] + public void Render_V23UnreadableEmbeddedFrameInUtf8_IsKeptAsStored () + { + byte[] subFrames = [.. SubFrame ("TIT2", 3, [0, .. "Intro"u8]), .. SubFrame ("COMM", 3, [3, (byte)'e'], status: 0x20)]; + var tag = TagWith (Holder.Chapter, 3, subFrames); + var read = Id3v2Tag.Read (tag).Tag!; + read.Album = "edited"; + + var body = Id3v2WrittenEncodingTests.WrittenFrames (read.Render ().ToArray ()).First (f => f.Id == "CHAP").Body; + + CollectionAssert.AreEqual (Id3v2WrittenEncodingTests.WrittenFrames (tag).First (f => f.Id == "CHAP").Body, body); + } + + // ID3v2.4 defines UTF-16BE and UTF-8, so an embedded frame in either keeps its bytes there. + [TestMethod] + [DataRow (Holder.Chapter)] + [DataRow (Holder.TableOfContents)] + public void Render_V24EmbeddedTextInUtf8OrUtf16BE_KeepsItsBytes (Holder holder) + { + byte[] subFrames = [ + .. SubFrame ("TIT2", 4, [3, .. "Caf\u00E9"u8]), + .. SubFrame ("TIT3", 4, [2, 0, (byte)'s'])]; + var tag = TagWith (holder, 4, subFrames); + var id = holder == Holder.Chapter ? "CHAP" : "CTOC"; + var read = Id3v2Tag.Read (tag).Tag!; + read.Album = "edited"; + + var body = Id3v2WrittenEncodingTests.WrittenFrames (read.Render ().ToArray ()).First (f => f.Id == id).Body; + + CollectionAssert.AreEqual (Id3v2WrittenEncodingTests.WrittenFrames (tag).First (f => f.Id == id).Body, body); + } + + // A CHAP moved between versions keeps a frame this library does not read that has format flags: its content is + // carried without them, the decompressed bytes of a compressed frame and the bytes after a group byte (#265). + [TestMethod] + [DataRow (Holder.Chapter, (byte)3)] + [DataRow (Holder.Chapter, (byte)4)] + [DataRow (Holder.TableOfContents, (byte)3)] + [DataRow (Holder.TableOfContents, (byte)4)] + public void Render_FlaggedUnknownEmbeddedFrameMovedAcrossVersions_KeepsItsContent (Holder holder, byte from) + { + byte grouped = from == 4 ? (byte)0x40 : (byte)0x20; + byte[] subFrames = [ + .. SubFrame ("TIT2", from, [0, .. "Intro"u8]), + .. SubFrame ("ZZZ1", from, [0x07, 1, 2, 3], format: grouped), + // An encrypted frame (v2.3 0x40, v2.4 0x04) has no content to carry, and is left out. + .. SubFrame ("ZZZ3", from, [0x80, 9, 9], format: from == 4 ? (byte)0x04 : (byte)0x40)]; + var source = Id3v2Tag.Read (TagWith (holder, from, subFrames)).Tag!; + var target = new Id3v2Tag (from == 4 ? Id3v2Version.V23 : Id3v2Version.V24); + if (holder == Holder.Chapter) + target.AddChapter (source.GetChapter ("ch1")!); + else + target.AddTableOfContents (source.GetTableOfContents ()!); + + var written = target.Render ().ToArray (); + + var frames = Id3v2WrittenEncodingTests.WrittenFrames (written); + Assert.IsFalse (frames.Any (f => f.Id == "ZZZ3"), "the encrypted frame"); + var unknown = frames.Single (f => f.Id == "ZZZ1"); + byte[] content = [1, 2, 3]; + CollectionAssert.AreEqual (content, unknown.Body); + Assert.AreEqual ("Intro", Title (Id3v2Tag.Read (written).Tag!, holder)); + } + + // A CHAP read from a v2.4 tag and added to a v2.3 one: each sub-frame this library reads is written as that version + // writes it (#255's encodings), and a frame it does not read with no format flags is kept as stored. + [TestMethod] + [DataRow (Holder.Chapter)] + [DataRow (Holder.TableOfContents)] + public void Render_EmbeddedSubFramesFromV24InV23Tag_AreWrittenInV23 (Holder holder) + { + byte[] subFrames = [ + .. SubFrame ("TIT2", 4, [3, .. "Intro"u8]), + .. SubFrame ("TIT3", 4, [3, .. "Sub \u00E9"u8]), + .. SubFrame ("ZZZ1", 4, [9, 8, 7])]; + var source = Id3v2Tag.Read (TagWith (holder, 4, subFrames)).Tag!; + var target = new Id3v2Tag (Id3v2Version.V23); + if (holder == Holder.Chapter) + target.AddChapter (source.GetChapter ("ch1")!); + else + target.AddTableOfContents (source.GetTableOfContents ()!); + + var written = target.Render ().ToArray (); + + var frames = Id3v2WrittenEncodingTests.WrittenFrames (written); + var sub = frames.Skip (1).ToList (); + byte[] intro = [0, .. "Intro"u8]; + byte[] subtitle = [0, .. System.Text.Encoding.Latin1.GetBytes ("Sub \u00E9")]; + byte[] unknown = [9, 8, 7]; + Assert.AreEqual ("TIT2,TIT3,ZZZ1", string.Join (",", sub.Select (f => f.Id))); + CollectionAssert.AreEqual (intro, sub[0].Body); + CollectionAssert.AreEqual (subtitle, sub[1].Body); + CollectionAssert.AreEqual (unknown, sub[2].Body); + Assert.AreEqual ("Intro", Title (Id3v2Tag.Read (written).Tag!, holder)); + } + // The embedded walk takes sizes and flags from the file: no cut or changed byte makes a read or a save throw. [TestMethod] [DataRow (Holder.Chapter, (byte)3)] diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs index 751c546d..1e482be1 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs @@ -24,7 +24,28 @@ public class Id3v2WrittenEncodingCarrierTests static readonly byte[] Front = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 0xFF, 0xD9]; static readonly byte[] Back = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 2, 0xFF, 0xD9]; - static readonly string[] Saves = ["render", "path-with-data", "async-path-with-data", "path", "async-path", "in-place", "async-in-place"]; + /// Every save entry point the carriers have. + internal static readonly string[] Saves = ["render", "path-with-data", "async-path-with-data", "path", "async-path", "in-place", "async-in-place"]; + + /// Whether has the save : WAV and AIFF have none that takes the original bytes. + internal static bool HasSave (string format, string save) => + !(format is "wav" or "aiff" && save.EndsWith ("with-data", StringComparison.Ordinal)); + + /// + /// Reads as a file named for (from data for the span render, + /// from a path otherwise), edits its ID3v2 tag, saves it through and returns the bytes saved. + /// + internal static async Task ReadEditAndSaveAsync (byte[] original, string extension, string save, Action edit) + { + var files = new MockFileSystem (); + var name = "/file" + extension; + files.AddFile (name, original); + var read = save == "render" ? MediaFile.ReadFromData (original, name) : MediaFile.Read (name, files); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + edit (Id3v22CarrierBuilder.Id3 (file)!); + return await SaveAsync (file, original, files, name, save); + } static readonly byte[] Versions = [3, 4]; static readonly string[] Texts = ["Cover", "日本語"]; @@ -33,8 +54,7 @@ from format in Id3v22CarrierBuilder.Formats from version in Versions from text in Texts from save in Saves - // WAV and AIFF have no save that takes the original bytes. - where !(format.Format is "wav" or "aiff" && save.EndsWith ("with-data", StringComparison.Ordinal)) + where HasSave (format.Format, save) select new object[] { format.Format, format.Extension, version, text, save }; [TestMethod] @@ -112,7 +132,7 @@ static async Task SaveAsync (IMediaFile file, byte[] original, MockFileS } /// The ID3v2.3 or ID3v2.4 tag in a saved carrier. - static byte[] WrittenTag (byte[] file) + internal static byte[] WrittenTag (byte[] file) { for (var at = file.AsSpan ().IndexOf ("ID3"u8); at >= 0;) { if (file[at + 3] is 3 or 4 && file[at + 4] == 0) { From d6fe68e88658bc2b85df8456608492be18996be6 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 10:36:43 -0700 Subject: [PATCH 5/7] fix: Percent-encode the characters of an ID3v2 URL that ISO-8859-1 cannot hold (#266) --- CHANGELOG.md | 1 + src/TagLibSharp2/Id3/Id3v2/Frames/UrlFrame.cs | 15 ++- .../Id3/Id3v2/Frames/UserUrlFrame.cs | 6 +- src/TagLibSharp2/Id3/Id3v2/Id3Text.cs | 33 +++++++ src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 8 +- .../Id3/Id3v2/Id3v2UrlTextTests.cs | 95 +++++++++++++++++++ 6 files changed, 150 insertions(+), 8 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UrlTextTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 22271d70..6df406e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- An ID3v2 URL frame (W*** and the URL of WXXX) whose URL has characters outside ISO-8859-1 writes each of them percent-encoded as UTF-8, as an IRI maps to a URI (RFC 3987 §3.1), where each was written as `?` (#266). A URL that ISO-8859-1 holds is written as given, and a character from U+0080 to U+00FF stays one ISO-8859-1 byte; a read gives back the text written, in its encoded form. The frame's `Url` keeps what was set until the file is read again - A save keeps every frame an ID3v2 CHAP or CTOC embeds, such as a chapter's subtitle (TIT3), link (WXXX) or image (APIC), and frames this library does not know (#265). Only the embedded title (TIT2) was kept, and every other embedded frame was dropped on any save. A save that does not change the chapter's title writes the CHAP or CTOC as it was read; a new title is written as a new TIT2 where the old one was, and the other frames as they were stored, with their flags. An embedded frame read from a v2.3 tag in a text encoding v2.3 does not define, such as a chapter title 0.6 and earlier wrote in UTF-8, is written again in ISO-8859-1 or UTF-16 with a BOM, as the tag's other frames are (#255), keeping its status flags and group byte but not its compression; deciding this inflates a compressed frame's first byte only, and a frame that cannot be re-encoded is kept as stored. A chapter moved to a tag of another version writes each embedded frame this library reads as that version writes it, and any other frame with its content as its format flags give it and no flags; an encrypted one is left out - 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 diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UrlFrame.cs index be475ffd..27d1f9de 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UrlFrame.cs @@ -13,6 +13,10 @@ namespace TagLibSharp2.Id3.Id3v2.Frames; /// /// /// URL frames contain a single URL encoded in Latin-1 (ISO-8859-1). +/// A URL is stored as ISO-8859-1 (https://id3.org/id3v2.4.0-frames §4.3). Characters U+0000 to U+00FF are written as +/// those bytes; every other character is written as its UTF-8 bytes, percent-encoded (RFC 3987 §3.1), so +/// http://example.com/日 is written http://example.com/%E6%97%A5, and a read of the file returns that +/// encoded form. A character from U+0080 to U+00FF stays one ISO-8859-1 byte and is not percent-encoded. /// Standard frame IDs: /// /// WCOM: Commercial information @@ -41,6 +45,10 @@ public sealed class UrlFrame /// /// Gets or sets the URL. /// + /// + /// Characters outside ISO-8859-1 are written percent-encoded as UTF-8, and a read of the file returns that encoded + /// form; this property keeps what was set until the file is read again. + /// public string Url { get; set; } /// @@ -91,11 +99,8 @@ public static UrlFrameReadResult Read (string frameId, ReadOnlySpan data, /// /// Renders the frame content to binary data. /// - /// The frame content (URL in Latin-1). - public BinaryData RenderContent () - { - return BinaryData.FromStringLatin1 (Url); - } + /// The frame content (URL in Latin-1, other characters percent-encoded as UTF-8). + public BinaryData RenderContent () => new (Id3Text.EncodeUrl (Url)); } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs index bb8b1837..9a7376f7 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/UserUrlFrame.cs @@ -36,6 +36,10 @@ public sealed class UserUrlFrame /// /// Gets or sets the URL. /// + /// + /// Characters outside ISO-8859-1 are written percent-encoded as UTF-8, and a read of the file returns that encoded + /// form; this property keeps what was set until the file is read again. + /// public string Url { get; set; } /// @@ -103,7 +107,7 @@ internal BinaryData RenderContent (Id3v2Version version) => BinaryData Render (TextEncodingType encoding) { var descriptionBytes = EncodeDescription (Description, encoding); - var urlBytes = Polyfills.Latin1.GetBytes (Url); + var urlBytes = Id3Text.EncodeUrl (Url); var terminatorSize = GetTerminatorSize (encoding); var totalSize = 1 + descriptionBytes.Length + terminatorSize + urlBytes.Length; diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs index 65917589..f69f1d9f 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3Text.cs @@ -71,6 +71,39 @@ internal static TextEncodingType WrittenEncoding (TextEncodingType encoding, Id3 return FitLatin1 (texts) ? TextEncodingType.Latin1 : TextEncodingType.Utf16WithBom; } + /// + /// The bytes of a URL frame's URL, which ID3v2 stores as ISO-8859-1 (https://id3.org/id3v2.4.0-frames §4.3): each + /// character ISO-8859-1 holds as that byte, and each other character as its UTF-8 bytes percent-encoded, as an IRI + /// maps to a URI (RFC 3987 §3.1), never as '?' (#266). A URL that fits is written as given. + /// + internal static byte[] EncodeUrl (string url) + { + if (FitLatin1 ([url])) + return Core.Polyfills.Latin1.GetBytes (url); + + var bytes = new List (url.Length + 16); + for (var i = 0; i < url.Length; i++) { + var c = url[i]; + if (c <= '\u00FF') { + bytes.Add ((byte)c); + continue; + } + + // A surrogate pair is one character; a lone surrogate is encoded as U+FFFD, as UTF-8 cannot hold it. + var length = char.IsHighSurrogate (c) && i + 1 < url.Length && char.IsLowSurrogate (url[i + 1]) ? 2 : 1; + foreach (var b in Encoding.UTF8.GetBytes (url.Substring (i, length))) { + bytes.Add ((byte)'%'); + bytes.Add ((byte)HexDigits[b >> 4]); + bytes.Add ((byte)HexDigits[b & 0x0F]); + } + i += length - 1; + } + + return [.. bytes]; + } + + const string HexDigits = "0123456789ABCDEF"; + /// True when ISO-8859-1 holds every character of every one of . static bool FitLatin1 (string[] texts) { diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index a0d97b5c..62320dfc 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -414,7 +414,9 @@ public void SetPopularimeter (string email, byte rating, ulong playCount = 0) /// Sets or adds a URL frame. /// /// The frame ID (e.g., "WOAR", "WPUB"). - /// The URL, or null to remove the frame. + /// The URL, or null to remove the frame. Characters outside ISO-8859-1 are written + /// percent-encoded as UTF-8 (RFC 3987 §3.1); characters U+0080 to U+00FF stay ISO-8859-1 bytes. A read of the file + /// returns the encoded form. #pragma warning disable CA1054 // URI parameter - ID3v2 URLs may be malformed public void SetUrl (string frameId, string? url) #pragma warning restore CA1054 @@ -453,7 +455,9 @@ public void SetUrl (string frameId, string? url) /// Sets or adds a user-defined URL. /// /// The URL description. - /// The URL, or null to remove the frame. + /// The URL, or null to remove the frame. Characters outside ISO-8859-1 are written + /// percent-encoded as UTF-8 (RFC 3987 §3.1); characters U+0080 to U+00FF stay ISO-8859-1 bytes. A read of the file + /// returns the encoded form. #pragma warning disable CA1054 // URI parameter - ID3v2 URLs may be malformed public void SetUserUrl (string description, string? url) #pragma warning restore CA1054 diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UrlTextTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UrlTextTests.cs new file mode 100644 index 00000000..97067d21 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2UrlTextTests.cs @@ -0,0 +1,95 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Mpeg; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// A URL frame holds ISO-8859-1 text (https://id3.org/id3v2.4.0-frames §4.3; https://id3.org/id3v2.3.0 §4.3). A URL +/// with characters outside it is written with each of those characters percent-encoded as UTF-8, as an IRI maps to a +/// URI (RFC 3987 §3.1), where each was written as '?' (issue #266). A URL that fits is written as given, and a read +/// gives back exactly the text written. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2UrlTextTests +{ + // Each URL and the text written for it. + static readonly (string Url, string Written)[] Urls = [ + ("http://a.example/path?q=1", "http://a.example/path?q=1"), + ("http://café.example/ü", "http://café.example/ü"), + ("http://a.example/%41%2F", "http://a.example/%41%2F"), + ("http://例え.jp/パス", "http://%E4%BE%8B%E3%81%88.jp/%E3%83%91%E3%82%B9"), + ("http://a.example/\U0001F3B5?x=éÿ", "http://a.example/%F0%9F%8E%B5?x=éÿ"), + ]; + + static readonly Id3v2Version[] Versions = [Id3v2Version.V23, Id3v2Version.V24]; + static readonly string[] Frames = ["WOAR", "WXXX"]; + static readonly bool[] ViaFile = [false, true]; + + public static IEnumerable Rows => + from frame in Frames + from version in Versions + from url in Urls + from viaFile in ViaFile + select new object[] { frame, version, url.Url, url.Written, viaFile }; + + [TestMethod] + [DynamicData (nameof (Rows))] + public void Save_Url_WritesIso88591WithOtherCharactersPercentEncoded (string frameId, Id3v2Version version, string url, string written, bool viaFile) + { + void Set (Id3v2Tag tag) + { + if (frameId == "WXXX") + tag.SetUserUrl ("site", url); + else + tag.SetUrl (frameId, url); + } + + byte[] saved; + if (viaFile) { + byte[] mp3 = [.. TestBuilders.Id3v2.CreateHeader ((byte)version, 16), .. new byte[16], .. new byte[256]]; + var file = Mp3File.Read (mp3).File!; + Set (file.Id3v2Tag!); + saved = file.Render (mp3).ToArray (); + } else { + var tag = new Id3v2Tag (version); + Set (tag); + saved = tag.Render ().ToArray (); + } + + var body = Id3v2WrittenEncodingTests.WrittenFrames (saved).Single (f => f.Id == frameId).Body; + // WXXX: encoding $00, the description "site", its terminator, then the URL. + var urlBytes = frameId == "WXXX" ? body[6..] : body; + CollectionAssert.AreEqual (System.Text.Encoding.Latin1.GetBytes (written), urlBytes); + var reread = Mp3File.Read ([.. saved.AsSpan (0, (int)Id3v2Header.Read (saved).Header.TotalSize), .. new byte[256]]).File!.Id3v2Tag!; + Assert.AreEqual (written, frameId == "WXXX" ? reread.GetUserUrl ("site") : reread.GetUrl (frameId)); + } + + // A lone surrogate is one character UTF-8 cannot hold, written as U+FFFD; the character after it is its own. + [TestMethod] + public void RenderContent_UrlWithLoneSurrogate_EncodesItAloneAsReplacementCharacter () + { + var frame = new UrlFrame ("WOAR", "http://a/\uD800b\uDC00"); + + CollectionAssert.AreEqual ("http://a/%EF%BF%BDb%EF%BF%BD"u8.ToArray (), frame.RenderContent ().ToArray ()); + } + + // A frame's own RenderContent () writes the same text, and its Url keeps what the caller set. + [TestMethod] + public void RenderContent_UrlOutsideLatin1_PercentEncodes () + { + var url = new UrlFrame ("WOAR", "http://a/日"); + var userUrl = new UserUrlFrame ("http://a/日", "d", TextEncodingType.Latin1); + + CollectionAssert.AreEqual ("http://a/%E6%97%A5"u8.ToArray (), url.RenderContent ().ToArray ()); + byte[] expected = [0, .. "d"u8, 0, .. "http://a/%E6%97%A5"u8]; + CollectionAssert.AreEqual (expected, userUrl.RenderContent ().ToArray ()); + Assert.AreEqual ("http://a/日", url.Url); + } +} From 7c6cd009c74f74a6eb9a0f61d263382105dc67c4 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 11:19:46 -0700 Subject: [PATCH 6/7] fix: Read an ID3v2.3 frame's decompressed size before its group byte (#272) --- CHANGELOG.md | 1 + src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 18 ++++- .../Id3/Id3v2/Id3v2FrameFlagOrderTests.cs | 74 +++++++++++++++++++ 3 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameFlagOrderTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df406e1..a88b621c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- An ID3v2.3 frame that is both compressed and grouped reads (#272). ID3v2.3 §3.3.1 puts the extra bytes in the flags' order, the decompressed size before the group byte, and the group byte was read first, so the size was read from the wrong bytes and a frame that compresses well was rejected. ID3v2.4, which puts the group byte first, is unchanged. This reaches the frames CHAP and CTOC embed too - An ID3v2 URL frame (W*** and the URL of WXXX) whose URL has characters outside ISO-8859-1 writes each of them percent-encoded as UTF-8, as an IRI maps to a URI (RFC 3987 §3.1), where each was written as `?` (#266). A URL that ISO-8859-1 holds is written as given, and a character from U+0080 to U+00FF stays one ISO-8859-1 byte; a read gives back the text written, in its encoded form. The frame's `Url` keeps what was set until the file is read again - A save keeps every frame an ID3v2 CHAP or CTOC embeds, such as a chapter's subtitle (TIT3), link (WXXX) or image (APIC), and frames this library does not know (#265). Only the embedded title (TIT2) was kept, and every other embedded frame was dropped on any save. A save that does not change the chapter's title writes the CHAP or CTOC as it was read; a new title is written as a new TIT2 where the old one was, and the other frames as they were stored, with their flags. An embedded frame read from a v2.3 tag in a text encoding v2.3 does not define, such as a chapter title 0.6 and earlier wrote in UTF-8, is written again in ISO-8859-1 or UTF-16 with a BOM, as the tag's other frames are (#255), keeping its status flags and group byte but not its compression; deciding this inflates a compressed frame's first byte only, and a frame that cannot be re-encoded is kept as stored. A chapter moved to a tag of another version writes each embedded frame this library reads as that version writes it, and any other frame with its content as its format flags give it and no flags; an encrypted one is left out - 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 diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index 62320dfc..a3fca021 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -2884,8 +2884,9 @@ static byte[] RemoveUnsynchronization (ReadOnlySpan data) /// bit 0 (0x01): data length indicator /// /// - /// When multiple flags are set, the order of extra data is: - /// grouping identity (1 byte), then data length indicator (4 bytes). + /// When multiple flags are set, the extra data follows the flags' order: in ID3v2.3 the decompressed size (4 bytes), + /// then the group identity (1 byte) (https://id3.org/id3v2.3.0 §3.3.1); in ID3v2.4 the group identity (1 byte), then + /// the data length indicator (4 bytes) (https://id3.org/id3v2.4.0-structure §4.1.2). /// /// static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte formatFlags, int majorVersion, int inflateAtMost = int.MaxValue) @@ -2917,8 +2918,10 @@ static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte fo if (hasEncryption) return ReadOnlySpan.Empty; - // Skip grouping identity byte if present (1 byte) - if (hasGrouping) { + // The extra bytes follow the flags' order (#272). v2.3 §3.3.1: the decompressed size (compression), then the + // group byte. v2.4 §4.1.2: the group byte, then the data length indicator. + var groupFirst = majorVersion == 4; + if (hasGrouping && groupFirst) { if (content.Length <= offset) return content; offset += 1; @@ -2942,6 +2945,13 @@ static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte fo offset += 4; } + if (hasGrouping && !groupFirst) { + // A compressed frame with nothing to inflate is not text. + if (content.Length <= offset) + return hasCompression ? ReadOnlySpan.Empty : content; + offset += 1; + } + var data = content.Slice (offset); // Apply per-frame unsynchronization if set (v2.4 only) diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameFlagOrderTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameFlagOrderTests.cs new file mode 100644 index 00000000..354fe00b --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2FrameFlagOrderTests.cs @@ -0,0 +1,74 @@ +// 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.IO.Compression; + +using TagLibSharp2.Id3.Id3v2; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// The bytes a frame's format flags add after its header come in the flags' order (issue #272). ID3v2.3 §3.3.1 +/// (https://id3.org/id3v2.3.0): compression (a 4-byte decompressed size), then encryption (a method byte), then grouping +/// (a group byte). ID3v2.4 §4.1.2 (https://id3.org/id3v2.4.0-structure): grouping (a group byte), then encryption, then +/// the data length indicator. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2FrameFlagOrderTests +{ + // A long, repetitive title compresses well: a size read from the wrong bytes is then far past what the compressed + // bytes can hold, and the frame is rejected as a decompression bomb, as it was before #272. + static readonly string Title = new ('a', 4000); + static readonly byte[] TitleBody = [0, .. System.Text.Encoding.ASCII.GetBytes (Title)]; + + static byte[] Size (int size, bool syncSafe) => syncSafe + ? [(byte)((size >> 21) & 0x7F), (byte)((size >> 14) & 0x7F), (byte)((size >> 7) & 0x7F), (byte)(size & 0x7F)] + : [(byte)(size >> 24), (byte)(size >> 16), (byte)(size >> 8), (byte)size]; + + static byte[] Deflate (byte[] data) + { + using var output = new MemoryStream (); + using (var zlib = new ZLibStream (output, CompressionLevel.Optimal)) + zlib.Write (data); + return output.ToArray (); + } + + static byte[] Tag (byte version, byte format, byte[] body) + { + var frame = TestBuilders.Id3v2.CreateFrame ("TIT2", body, version); + frame[9] = format; + return [.. TestBuilders.Id3v2.CreateHeader (version, (uint)frame.Length), .. frame]; + } + + [TestMethod] + public void Read_V23CompressedAndGroupedFrame_ReadsSizeThenGroupByte () + { + byte[] body = [.. Size (TitleBody.Length, false), 0x07, .. Deflate (TitleBody)]; + + Assert.AreEqual (Title, Id3v2Tag.Read (Tag (3, 0xA0, body)).Tag!.Title); + } + + [TestMethod] + public void Read_V24CompressedAndGroupedFrame_ReadsGroupByteThenSize () + { + byte[] body = [0x07, .. Size (TitleBody.Length, true), .. Deflate (TitleBody)]; + + Assert.AreEqual (Title, Id3v2Tag.Read (Tag (4, 0x49, body)).Tag!.Title); + } + + // A compressed frame with nothing to inflate after its size is not text, grouped or not. + [TestMethod] + public void Read_V23CompressedAndGroupedFrameWithOnlyItsSize_ReadsNothing () + { + Assert.IsNull (Id3v2Tag.Read (Tag (3, 0xA0, [0, 0, 0, 0x70])).Tag!.Title); + } + + [TestMethod] + public void Read_V23GroupedFrame_SkipsTheGroupByte () + { + Assert.AreEqual (Title, Id3v2Tag.Read (Tag (3, 0x20, [0x07, .. TitleBody])).Tag!.Title); + } +} From 4f6639e3dfaba73bce6d86a16634322cb65a1028 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 12:59:49 -0700 Subject: [PATCH 7/7] fix: Bound the inflation of compressed ID3v2 frames by one budget per read or save, and fail a save whose tag is too large for its size (#275) --- CHANGELOG.md | 1 + src/TagLibSharp2/Aac/AacFile.cs | 164 +++-- src/TagLibSharp2/Aiff/AiffFile.cs | 94 ++- src/TagLibSharp2/Core/PictureSkip.cs | 9 + src/TagLibSharp2/Core/TrailingTagChunk.cs | 6 +- src/TagLibSharp2/Dff/DffFile.cs | 142 ++-- src/TagLibSharp2/Dsf/DsfFile.cs | 164 +++-- .../Id3/Id3v2/Frames/ChapterFrame.cs | 17 +- .../Id3/Id3v2/Frames/TableOfContentsFrame.cs | 17 +- .../Id3/Id3v2/Id3v2Tag.FrameWalk.cs | 32 +- src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs | 142 +++- .../Id3/Id3v2/Id3v2TagTooLargeException.cs | 51 ++ src/TagLibSharp2/Id3/Id3v2/InflateBudget.cs | 50 ++ src/TagLibSharp2/Mpeg/Mp3File.cs | 164 +++-- src/TagLibSharp2/Mpeg/MpegPsFile.cs | 191 +++-- src/TagLibSharp2/Riff/AviFile.cs | 106 ++- src/TagLibSharp2/Riff/AviRewrite.cs | 11 +- src/TagLibSharp2/Riff/WavFile.cs | 77 +- .../Id3/Id3v2/Id3v2InflateBudgetTests.cs | 661 ++++++++++++++++++ .../Id3/Id3v2/Id3v2SaveSizeGuardTests.cs | 239 +++++++ .../Id3v2/Id3v2WrittenEncodingCarrierTests.cs | 14 +- 21 files changed, 1884 insertions(+), 468 deletions(-) create mode 100644 src/TagLibSharp2/Id3/Id3v2/Id3v2TagTooLargeException.cs create mode 100644 src/TagLibSharp2/Id3/Id3v2/InflateBudget.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2InflateBudgetTests.cs create mode 100644 tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2SaveSizeGuardTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index a88b621c..a62c0c54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A crafted ID3v2 tag of many small compressed frames that each declare a large decompressed size no longer makes a read or a save allocate without bound (#275). One read of a file now inflates at most 64 MiB in all, shared by every compressed frame of every ID3v2 tag it parses: top-level frames, those CHAP and CTOC embed, and every ID3 chunk of an AIFF and the tag chunks after a WAV or AIFF, which are recognised as tags without inflating anything; a save re-encodes embedded frames within 16 MiB. The per-frame limits stay 16 MiB and 1,100:1; there was no limit across the tag or the file, so 50 frames of 16 MiB allocated about 800 MB to read, 40 ID3 chunks in an AIFF about 1.9 GB, and a save of an 819 KB tag rendered 839 MB; that save now allocates about 165 MB. A frame past the budget is not decoded and is written back as stored, byte for byte. A save whose ID3v2 tag, or one of its frames, would be larger than an ID3v2 size can hold (0x0FFFFFFF) now fails with a result that says so and writes nothing, in MP3, raw AAC, MPEG-PS, WAV, AIFF, DSF, DFF and AVI, where it threw `ArgumentOutOfRangeException` from the size writer; the check renders the tag, with the padding the carrier writes it with, only when a bound on its size, taken from the frames without rendering them, could pass the limit. A save that renders the tag as it was read, to see whether the caller changed it (MPEG-PS, AVI, and WAV or AIFF with a tag chunk after the form), takes a tag as read that is too large to render as changed, so an edit that makes the tag smaller saves. `Id3v2Tag.Render` and a carrier's `Render` throw an `InvalidOperationException` with that message - An ID3v2.3 frame that is both compressed and grouped reads (#272). ID3v2.3 §3.3.1 puts the extra bytes in the flags' order, the decompressed size before the group byte, and the group byte was read first, so the size was read from the wrong bytes and a frame that compresses well was rejected. ID3v2.4, which puts the group byte first, is unchanged. This reaches the frames CHAP and CTOC embed too - An ID3v2 URL frame (W*** and the URL of WXXX) whose URL has characters outside ISO-8859-1 writes each of them percent-encoded as UTF-8, as an IRI maps to a URI (RFC 3987 §3.1), where each was written as `?` (#266). A URL that ISO-8859-1 holds is written as given, and a character from U+0080 to U+00FF stays one ISO-8859-1 byte; a read gives back the text written, in its encoded form. The frame's `Url` keeps what was set until the file is read again - A save keeps every frame an ID3v2 CHAP or CTOC embeds, such as a chapter's subtitle (TIT3), link (WXXX) or image (APIC), and frames this library does not know (#265). Only the embedded title (TIT2) was kept, and every other embedded frame was dropped on any save. A save that does not change the chapter's title writes the CHAP or CTOC as it was read; a new title is written as a new TIT2 where the old one was, and the other frames as they were stored, with their flags. An embedded frame read from a v2.3 tag in a text encoding v2.3 does not define, such as a chapter title 0.6 and earlier wrote in UTF-8, is written again in ISO-8859-1 or UTF-16 with a BOM, as the tag's other frames are (#255), keeping its status flags and group byte but not its compression; deciding this inflates a compressed frame's first byte only, and a frame that cannot be re-encoded is kept as stored. A chapter moved to a tag of another version writes each embedded frame this library reads as that version writes it, and any other frame with its content as its format flags give it and no flags; an encrypted one is left out diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs index 9c567298..6d9ccb5e 100644 --- a/src/TagLibSharp2/Aac/AacFile.cs +++ b/src/TagLibSharp2/Aac/AacFile.cs @@ -495,22 +495,27 @@ async Task Adopt (Task save, Written written, /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - - if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) - return mismatch; - - var written = Plan (new AacTailSource (originalData)); - var rendered = Assemble (originalData, written); - if (rendered.IsEmpty) - return FileWriteResult.Failure ("Failed to render AAC file"); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + + if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) + return mismatch; + + var written = Plan (new AacTailSource (originalData)); + var rendered = Assemble (originalData, written); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("Failed to render AAC file"); - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -529,22 +534,27 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - - if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); - - var written = Plan (new AacTailSource (originalData.Span)); - var rendered = Assemble (originalData.Span, written); - if (rendered.IsEmpty) - return Task.FromResult (FileWriteResult.Failure ("Failed to render AAC file")); - - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + + if (Source.Refuse ("AAC", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); + + var written = Plan (new AacTailSource (originalData.Span)); + var rendered = Assemble (originalData.Span, written); + if (rendered.IsEmpty) + return Task.FromResult (FileWriteResult.Failure ("Failed to render AAC file")); + + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -559,15 +569,20 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -577,15 +592,20 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveToFile (SourcePath!, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -604,15 +624,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } // Same bytes as Render. The audio and any Lyrics3 block are copied; the tags are rendered. @@ -673,15 +698,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// diff --git a/src/TagLibSharp2/Aiff/AiffFile.cs b/src/TagLibSharp2/Aiff/AiffFile.cs index 3472d54a..6ac72bbc 100644 --- a/src/TagLibSharp2/Aiff/AiffFile.cs +++ b/src/TagLibSharp2/Aiff/AiffFile.cs @@ -627,6 +627,10 @@ void ProcessChunk (AiffChunk chunk) // Marker id 0 is the file comment and ranks above ANNO. Other marker ids stay out of Comment. void FinishNative () { + if (_keptId3Chunk is { } kept && Id3v2Tag.Read (kept.Data.Span, new InflateBudget ()) is { IsSuccess: true } decoded) + Id3v2Tag = decoded.Tag; + _keptId3Chunk = null; + if (_markerComments.Count > 0) _commentKind = NativeCommentKind.MarkerComment; else if (_annotations.Count > 0) @@ -791,12 +795,19 @@ void ParseCommChunk (AiffChunk chunk) Properties = props; } + // The ID3 chunk a read keeps: the last that reads. Each chunk is read first without inflating anything, and the one + // kept is read again with the read's budget when the read finishes (FinishNative), so chunks it supersedes cannot + // spend that budget first (#275). + AiffChunk? _keptId3Chunk; + void ParseId3Chunk (AiffChunk chunk) { // The ID3 chunk contains a complete ID3v2 tag. Native text is not copied into it. - var result = Id3v2Tag.Read (chunk.Data.Span); - if (result.IsSuccess) + var result = Id3v2Tag.Read (chunk.Data.Span, InflateBudget.None); + if (result.IsSuccess) { Id3v2Tag = result.Tag; + _keptId3Chunk = chunk; + } } /// @@ -875,13 +886,21 @@ bool TagRewritten () if (_tagPicturesDropped) return true; - Id3v2Tag? readTag = null; + // The last ID3 chunk that reads, found without inflating anything, then read with the save's budget (#275). + AiffChunk? kept = null; foreach (var chunk in _chunks) { - if (IsId3Chunk (chunk.FourCC) && Id3v2Tag.Read (chunk.Data.Span) is { IsSuccess: true } result) - readTag = result.Tag; + if (IsId3Chunk (chunk.FourCC) && Id3v2Tag.Read (chunk.Data.Span, InflateBudget.None).IsSuccess) + kept = chunk; } + var readTag = kept is null ? null : Id3v2Tag.Read (kept.Data.Span, new InflateBudget ()).Tag; - byte[]? read = readTag is { IsEmpty: false } ? readTag.Render ().ToArray () : null; + byte[]? read = null; + if (readTag is { IsEmpty: false }) { + // A tag as read that cannot render, too large for its size field, is a changed one (#275). + if (readTag.TryRender () is not { } rendered) + return true; + read = rendered.ToArray (); + } byte[]? written = Id3v2Tag is { IsEmpty: false } tag ? tag.Render ().ToArray () : null; return read is null ? written is not null : written is null || !read.AsSpan ().SequenceEqual (written); } @@ -957,14 +976,19 @@ static BinaryData RenderComments (List notes, int start, int count) /// The write result. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (SaveRefusal () is { } refused) - return refused; - if (_skipped.Count == 0) - return SaveLoaded (path, fileSystem); - - return SaveFromSource (path, fileSystem, default); + // 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 (SaveRefusal () is { } refused) + return refused; + if (_skipped.Count == 0) + return SaveLoaded (path, fileSystem); + + return SaveFromSource (path, fileSystem, default); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } FileWriteResult SaveLoaded (string path, IFileSystem? fileSystem) @@ -1061,15 +1085,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (SaveRefusal () is { } refused) - return Task.FromResult (refused); - if (_skipped.Count == 0) - return SaveLoadedAsync (path, fileSystem, cancellationToken); - - // "Was not loaded" and a short source are decided before the token, matching the sync save. - return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + // 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 Task.FromResult (denied); + if (SaveRefusal () is { } refused) + return Task.FromResult (refused); + if (_skipped.Count == 0) + return SaveLoadedAsync (path, fileSystem, cancellationToken); + + // "Was not loaded" and a short source are decided before the token, matching the sync save. + return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } Task SaveLoadedAsync (string path, IFileSystem? fileSystem, CancellationToken cancellationToken) @@ -1307,13 +1336,18 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - var fs = fileSystem ?? _sourceFileSystem; - return SaveToFileAsync (SourcePath!, fs, cancellationToken); + // 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 Task.FromResult (denied); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + var fs = fileSystem ?? _sourceFileSystem; + return SaveToFileAsync (SourcePath!, fs, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } } diff --git a/src/TagLibSharp2/Core/PictureSkip.cs b/src/TagLibSharp2/Core/PictureSkip.cs index a775072c..29600060 100644 --- a/src/TagLibSharp2/Core/PictureSkip.cs +++ b/src/TagLibSharp2/Core/PictureSkip.cs @@ -90,6 +90,15 @@ public static void Forget (Tag? tag) /// A failure when is false. Null when a save may proceed. public static FileWriteResult? Refuse (IMediaFile file) => file.PicturesLoaded ? null : FileWriteResult.Failure (SaveRefused); + + /// + /// The save gate of a file that carries an ID3v2 tag: , then a failure when the tag would render + /// larger than an ID3v2 size can hold (#275), so the save writes nothing and does not throw. Null when a save may + /// proceed. + /// + public static FileWriteResult? Refuse (IMediaFile file, Id3.Id3v2.Id3v2Tag? id3v2, + int paddingSize = Id3.Id3v2.Id3v2Tag.DefaultPaddingSize) => + Refuse (file) ?? Id3.Id3v2.Id3v2Tag.SizeRefusal (id3v2, paddingSize); } /// A file type whose read can leave its pictures out. diff --git a/src/TagLibSharp2/Core/TrailingTagChunk.cs b/src/TagLibSharp2/Core/TrailingTagChunk.cs index 24a15ba7..2c762ec9 100644 --- a/src/TagLibSharp2/Core/TrailingTagChunk.cs +++ b/src/TagLibSharp2/Core/TrailingTagChunk.cs @@ -103,9 +103,11 @@ public static long Superseded (Stream stream, long at, long length, bool bigEndi return superseded; } - // An ID3v2.2, v2.3 or v2.4 tag that reads and holds a field: a picture its copy left out is one. + // An ID3v2.2, v2.3 or v2.4 tag that reads and holds a field: a picture its copy left out is one. Deciding that + // inflates no compressed frame (#275): one kept as stored is a field all the same. static bool IsTag (ReadOnlySpan body, bool droppedPictures) => - body.Length > 3 && body[3] is 2 or 3 or 4 && Id3v2Tag.Read (body) is { IsSuccess: true, Tag: { } tag } && (droppedPictures || !tag.IsEmpty); + body.Length > 3 && body[3] is 2 or 3 or 4 && Id3v2Tag.Read (body, InflateBudget.None) is { IsSuccess: true, Tag: { } tag } + && (droppedPictures || !tag.IsEmpty); // The chunk's identifier is one of the format's tag chunk identifiers, in either case. static bool TryHeader (ReadOnlySpan header, bool bigEndian, string[] tagIds, out long size) diff --git a/src/TagLibSharp2/Dff/DffFile.cs b/src/TagLibSharp2/Dff/DffFile.cs index 53160b15..71aab370 100644 --- a/src/TagLibSharp2/Dff/DffFile.cs +++ b/src/TagLibSharp2/Dff/DffFile.cs @@ -748,21 +748,26 @@ public BinaryData Render () /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; - if (_originalData is null && Source.Refuse ("DFF", originalData.Length) is { } mismatch) - return mismatch; + if (_originalData is null && Source.Refuse ("DFF", originalData.Length) is { } mismatch) + return mismatch; - var fs = fileSystem ?? _sourceFileSystem; - try { - var rendered = _originalData is null ? RenderFrom (originalData.ToArray ()) : Render (); - return Source.Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); - } catch (Exception ex) { - return FileWriteResult.Failure ($"Failed to save file: {ex.Message}"); + var fs = fileSystem ?? _sourceFileSystem; + try { + var rendered = _originalData is null ? RenderFrom (originalData.ToArray ()) : Render (); + return Source.Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); + } catch (Exception ex) { + return FileWriteResult.Failure ($"Failed to save file: {ex.Message}"); + } + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); } } @@ -780,21 +785,26 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); - if (_originalData is null && Source.Refuse ("DFF", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); + if (_originalData is null && Source.Refuse ("DFF", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); - var fs = fileSystem ?? _sourceFileSystem; - try { - var rendered = _originalData is null ? RenderFrom (originalData.ToArray ()) : Render (); - return Source.Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); - } catch (Exception ex) { - return Task.FromResult (FileWriteResult.Failure ($"Failed to save file: {ex.Message}")); + var fs = fileSystem ?? _sourceFileSystem; + try { + var rendered = _originalData is null ? RenderFrom (originalData.ToArray ()) : Render (); + return Source.Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); + } catch (Exception ex) { + return Task.FromResult (FileWriteResult.Failure ($"Failed to save file: {ex.Message}")); + } + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); } } @@ -810,13 +820,18 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; - return Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, default)); + return Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, default)); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -826,17 +841,22 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + 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."); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); - fileSystem ??= _sourceFileSystem; - return SaveToFile (SourcePath!, fileSystem); + fileSystem ??= _sourceFileSystem; + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -847,13 +867,18 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); - return Task.FromResult (Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + return Task.FromResult (Source.Saved (SaveStreaming (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -866,17 +891,22 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DffFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DffFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - fileSystem ??= _sourceFileSystem; - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + fileSystem ??= _sourceFileSystem; + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } // Same bytes as Render. Sound is copied in chunks. The destination is seekable, so the form diff --git a/src/TagLibSharp2/Dsf/DsfFile.cs b/src/TagLibSharp2/Dsf/DsfFile.cs index 50729141..0be04b38 100644 --- a/src/TagLibSharp2/Dsf/DsfFile.cs +++ b/src/TagLibSharp2/Dsf/DsfFile.cs @@ -632,22 +632,27 @@ bool TryRenderFrom (ReadOnlySpan original, out BinaryData rendered, out st /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; - if (_originalData is null && Source.Refuse ("DSF", originalData.Length) is { } mismatch) - return mismatch; + if (_originalData is null && Source.Refuse ("DSF", originalData.Length) is { } mismatch) + return mismatch; - var fs = fileSystem ?? _sourceFileSystem; - if (!TryRenderWith (originalData, out var rendered, out var error)) - return FileWriteResult.Failure (error); - if (rendered.IsEmpty) - return FileWriteResult.Failure ("Failed to render DSF file"); + var fs = fileSystem ?? _sourceFileSystem; + if (!TryRenderWith (originalData, out var rendered, out var error)) + return FileWriteResult.Failure (error); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("Failed to render DSF file"); - return Source.Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); + return Source.Saved (AtomicFileWriter.Write (path, rendered.Span, fs)); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } const string NoSound = "Cannot render this DSF file: the source no longer holds the sound it was read with."; @@ -679,23 +684,28 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - - if (_originalData is null && Source.Refuse ("DSF", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); - - var fs = fileSystem ?? _sourceFileSystem; - if (!TryRenderWith (originalData.Span, out var rendered, out var error)) - return Task.FromResult (FileWriteResult.Failure (error)); - if (rendered.IsEmpty) - return Task.FromResult (FileWriteResult.Failure ("Failed to render DSF file")); - - cancellationToken.ThrowIfCancellationRequested (); - return Source.Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + + if (_originalData is null && Source.Refuse ("DSF", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); + + var fs = fileSystem ?? _sourceFileSystem; + if (!TryRenderWith (originalData.Span, out var rendered, out var error)) + return Task.FromResult (FileWriteResult.Failure (error)); + if (rendered.IsEmpty) + return Task.FromResult (FileWriteResult.Failure ("Failed to render DSF file")); + + cancellationToken.ThrowIfCancellationRequested (); + return Source.Saved (AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -711,20 +721,25 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + 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."); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); - var fs = fileSystem ?? _sourceFileSystem; - if (_originalData is not null) - return Source.Saved (WriteHeld (path, fs)); + var fs = fileSystem ?? _sourceFileSystem; + if (_originalData is not null) + return Source.Saved (WriteHeld (path, fs)); - return Source.Saved (SaveFromSource (path, fs)); + return Source.Saved (SaveFromSource (path, fs)); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } // Same bytes as Render. The audio slice is the held sample bytes, written in chunks. @@ -823,16 +838,21 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + 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."); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); - return SaveToFile (SourcePath!, fileSystem); + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -854,19 +874,24 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - if (_originalData is not null) - return Task.FromResult (Source.Saved (WriteHeld (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + if (_originalData is not null) + return Task.FromResult (Source.Saved (WriteHeld (path, fileSystem ?? _sourceFileSystem, cancellationToken))); - return Task.FromResult (Source.Saved (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + return Task.FromResult (Source.Saved (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken))); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -879,16 +904,21 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag]); - if (_disposed) - throw new ObjectDisposedException (nameof (DsfFile)); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag]); + if (_disposed) + throw new ObjectDisposedException (nameof (DsfFile)); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs index b0e26bc6..eb7ca02d 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/ChapterFrame.cs @@ -77,6 +77,9 @@ public sealed class ChapterFrame // The frames embedded when this frame was read, written back by a save (#265); null for a frame built here. EmbeddedFrames? _embedded; + /// The bytes of the embedded frames read, headers included, as stored (). + internal long EmbeddedStoredBytes => _embedded?.Frames.Sum (f => 10L + f.Body.Length) ?? 0; + /// /// Initializes a new instance of the class. /// @@ -98,7 +101,11 @@ public ChapterFrame (string elementId, uint startTimeMs, uint endTimeMs) /// The frame content data (excluding frame header). /// The ID3v2 version. /// A result indicating success or failure. - public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version version) + public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version version) => + Read (data, version, new InflateBudget ()); + + /// Reads the frame, inflating its compressed embedded frames within (#275). + internal static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version version, InflateBudget budget) { // Minimum size: element ID (1 + null) + times (16) = 18 bytes minimum if (data.Length < 18) @@ -138,7 +145,7 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version }; // Embedded sub-frames, with the tag's frame header and flags: the title is read, and every frame is kept. - frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version); + frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version, budget); frame.Title = frame._embedded.Title; return ChapterFrameReadResult.Success (frame, data.Length); @@ -148,13 +155,13 @@ public static ChapterFrameReadResult Read (ReadOnlySpan data, Id3v2Version /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24, new InflateBudget (InflateBudget.PerSave)); /// /// Renders the frame content for a tag of : the embedded TIT2 is in an encoding that /// version defines (). /// - internal BinaryData RenderContent (Id3v2Version version) + internal BinaryData RenderContent (Id3v2Version version, InflateBudget budget) { var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); var baseSize = elementIdBytes.Length + 1 + 16; // +1 for null, +16 for times/offsets @@ -180,7 +187,7 @@ internal BinaryData RenderContent (Id3v2Version version) AddUInt32BE (builder, EndByteOffset); // Embedded frames, with the tag's frame header: the title, and every other frame read (#265) - Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version); + Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version, budget); return builder.ToBinaryData (); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs index 2344de37..7fcbda9a 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Frames/TableOfContentsFrame.cs @@ -66,6 +66,9 @@ public sealed class TableOfContentsFrame // The frames embedded when this frame was read, written back by a save (#265); null for a frame built here. EmbeddedFrames? _embedded; + /// The bytes of the embedded frames read, headers included, as stored (). + internal long EmbeddedStoredBytes => _embedded?.Frames.Sum (f => 10L + f.Body.Length) ?? 0; + /// /// Gets the list of child element IDs (references to CHAP or other CTOC frames). /// @@ -113,7 +116,11 @@ public void ClearChildElements () /// The frame content data (excluding frame header). /// The ID3v2 version. /// A result indicating success or failure. - public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v2Version version) + public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v2Version version) => + Read (data, version, new InflateBudget ()); + + /// Reads the frame, inflating its compressed embedded frames within (#275). + internal static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v2Version version, InflateBudget budget) { // Minimum size: element ID (1 + null) + flags (1) + entry count (1) = 4 bytes minimum if (data.Length < 4) @@ -161,7 +168,7 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v } // Embedded sub-frames, with the tag's frame header and flags: the title is read, and every frame is kept. - frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version); + frame._embedded = Id3v2Tag.ReadEmbeddedFrames (data.Slice (offset), version, budget); frame.Title = frame._embedded.Title; return TableOfContentsFrameReadResult.Success (frame, data.Length); @@ -171,13 +178,13 @@ public static TableOfContentsFrameReadResult Read (ReadOnlySpan data, Id3v /// Renders the frame content to binary data. /// /// The frame content. - public BinaryData RenderContent () => RenderContent (Id3v2Version.V24); + public BinaryData RenderContent () => RenderContent (Id3v2Version.V24, new InflateBudget (InflateBudget.PerSave)); /// /// Renders the frame content for a tag of : the embedded TIT2 is in an encoding that /// version defines (). /// - internal BinaryData RenderContent (Id3v2Version version) + internal BinaryData RenderContent (Id3v2Version version, InflateBudget budget) { var elementIdBytes = Polyfills.Latin1.GetBytes (ElementId); @@ -214,7 +221,7 @@ internal BinaryData RenderContent (Id3v2Version version) } // Embedded frames, with the tag's frame header: the title, and every other frame read (#265) - Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version); + Id3v2Tag.AddEmbeddedFrames (builder, Title, _embedded, version, budget); return builder.ToBinaryData (); } diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs index 15d0d363..dd2a1f06 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.FrameWalk.cs @@ -121,7 +121,7 @@ internal static FrameStep NextFrame (ReadOnlySpan head, int remaining, byt /// , as a top-level frame of is. Every frame is kept as /// stored, so a save writes it back (#265); the title is the last TIT2 that reads, or null. /// - internal static EmbeddedFrames ReadEmbeddedFrames (ReadOnlySpan subFrames, Id3v2Version version) + internal static EmbeddedFrames ReadEmbeddedFrames (ReadOnlySpan subFrames, Id3v2Version version, InflateBudget budget) { var major = (byte)version; var headerSize = FrameHeaderLength (major); @@ -138,7 +138,7 @@ internal static EmbeddedFrames ReadEmbeddedFrames (ReadOnlySpan subFrames, if (step.Id.Length == 4) frames.Add (new UnreadFrame (step.Id, status, format, body.ToArray (), major)); if (step.Kind == FrameStepKind.Frame && step.Id == "TIT2") { - var read = TextFrame.Read (step.Id, ProcessFrameFlags (body, format, major), version); + var read = TextFrame.Read (step.Id, ProcessFrameFlags (body, format, major, budget), version); if (read.IsSuccess) title = read.Frame!.Text; } @@ -156,7 +156,7 @@ internal static EmbeddedFrames ReadEmbeddedFrames (ReadOnlySpan subFrames, /// A frame read from a tag of another version (a CHAP moved between tags) is written as /// says. /// - internal static void AddEmbeddedFrames (BinaryDataBuilder builder, string? title, EmbeddedFrames? read, Id3v2Version version) + internal static void AddEmbeddedFrames (BinaryDataBuilder builder, string? title, EmbeddedFrames? read, Id3v2Version version, InflateBudget budget) { var written = (int)version; var stored = read?.Frames ?? []; @@ -172,12 +172,15 @@ internal static void AddEmbeddedFrames (BinaryDataBuilder builder, string? title continue; } - if (frame.FitsVersion (written) && !InUndefinedEncoding (frame, version)) { + // The encoding peek charges a compressed frame's declared size once; the conversion it leads to reuses that + // charge rather than taking it again. + var undefined = frame.FitsVersion (written) && InUndefinedEncoding (frame, version, budget); + if (frame.FitsVersion (written) && !undefined) { var same = frame.Version == written; AddFrameHeader (builder, frame.Id, frame.Body.Length, version, same ? frame.Status : (byte)0, same ? frame.Format : (byte)0); builder.Add (frame.Body); } else { - AddConverted (builder, frame, version); + AddConverted (builder, frame, version, undefined ? InflateBudget.Charged : budget); } } } @@ -201,12 +204,13 @@ static bool AddTitle (BinaryDataBuilder builder, string title, Id3v2Version vers /// file cannot make this recurse; it is kept as bytes, and its own embedded headers stay in the size form of the /// version it was read from. /// - static void AddConverted (BinaryDataBuilder builder, UnreadFrame frame, Id3v2Version version) + static void AddConverted (BinaryDataBuilder builder, UnreadFrame frame, Id3v2Version version, InflateBudget budget) { - var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version); - if (frame.Id is not ("CHAP" or "CTOC")) { + var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version, budget); + var undecoded = content.IsEmpty && frame.Body.Length > 0; + if (!undecoded && frame.Id is not ("CHAP" or "CTOC")) { var tag = new Id3v2Tag (version); - if (tag.ReadFrame (frame.Id, content, (Id3v2Version)frame.Version)) { + if (tag.ReadFrame (frame.Id, content, (Id3v2Version)frame.Version, budget)) { var rendered = tag.Render (0, withFooter: false).Span.Slice (Id3v2Header.HeaderSize); if (frame.Version != (int)version) { builder.Add (rendered); @@ -233,7 +237,7 @@ static void AddConverted (BinaryDataBuilder builder, UnreadFrame frame, Id3v2Ver return; } - if (content.IsEmpty && frame.Body.Length > 0) + if (undecoded) return; AddFrameHeader (builder, frame.Id, content.Length, version); builder.Add (content); @@ -259,12 +263,12 @@ static int GroupByte (UnreadFrame frame) /// into a v2.3 tag uses an encoding v2.3 defines (#255), so such a frame, as 0.6 and earlier wrote a chapter title, /// is written again rather than as stored. /// - static bool InUndefinedEncoding (UnreadFrame frame, Id3v2Version version) + static bool InUndefinedEncoding (UnreadFrame frame, Id3v2Version version, InflateBudget budget) { if (version == Id3v2Version.V24 || !(frame.Id[0] == 'T' || frame.Id is "COMM" or "USLT" or "APIC" or "WXXX" or "GEOB" or "SYLT" or "IPLS")) return false; // The encoding byte is the first: a compressed frame is inflated that far only. - var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version, inflateAtMost: 1); + var content = ProcessFrameFlags (frame.Body, frame.Format, frame.Version, budget, inflateAtMost: 1); return !content.IsEmpty && content[0] is 2 or 3; } @@ -276,6 +280,10 @@ static bool InUndefinedEncoding (UnreadFrame frame, Id3v2Version version) internal static void AddFrameHeader (BinaryDataBuilder builder, string frameId, int contentSize, Id3v2Version version, byte status = 0, byte format = 0) { + // A v2.4 size is syncsafe (28 bits); the tag's own size, also syncsafe, bounds a v2.3 frame (#275). A lower limit + // is the tag's to check, once per render (Id3v2Tag.Render). + if (contentSize > Id3v2TagTooLargeException.MaxSyncSafe) + throw new Id3v2TagTooLargeException (frameId + " frame", contentSize); var idBytes = System.Text.Encoding.ASCII.GetBytes (frameId); builder.Add (idBytes.AsSpan ().Slice (0, 4)); if (version == Id3v2Version.V24) diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs index a3fca021..a542dd8c 100644 --- a/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2Tag.cs @@ -73,7 +73,7 @@ public sealed partial class Id3v2Tag : Tag { const int FrameHeaderSizeV23 = 10; // v2.3 and v2.4: 4-byte ID + 4-byte size + 2-byte flags const int FrameHeaderSizeV22 = 6; // v2.2: 3-byte ID + 3-byte size (no flags) - const int DefaultPaddingSize = 1024; + internal const int DefaultPaddingSize = 1024; readonly List _frames = new (16); readonly List _pictures = new (2); @@ -1224,7 +1224,7 @@ public Id3v2Tag (Id3v2Version version = Id3v2Version.V24) /// reads, and for a frame its branch rejects (a 1-byte APIC, a POPM with no terminator, an empty TPE1, a TALB with /// an invalid encoding byte). The caller keeps either as stored (). /// - bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version) + bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version, InflateBudget budget) { // Handle text frames (T***) - exclude TXXX (user text) and TIPL/TMCL (involved people) // Also handle Apple proprietary text frames: MVNM (movement name), MVIN (movement index/total) @@ -1334,7 +1334,7 @@ bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version // Handle chapter frames (CHAP) if (frameId == "CHAP") { - var chapResult = ChapterFrame.Read (content, version); + var chapResult = ChapterFrame.Read (content, version, budget); if (chapResult.IsSuccess) _chapterFrames.Add (chapResult.Frame!); return chapResult.IsSuccess; @@ -1342,7 +1342,7 @@ bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version // Handle table of contents frames (CTOC) if (frameId == "CTOC") { - var ctocResult = TableOfContentsFrame.Read (content, version); + var ctocResult = TableOfContentsFrame.Read (content, version, budget); if (ctocResult.IsSuccess) _tableOfContentsFrames.Add (ctocResult.Frame!); return ctocResult.IsSuccess; @@ -1356,7 +1356,13 @@ bool ReadFrame (string frameId, ReadOnlySpan content, Id3v2Version version /// /// The data to parse. /// A result indicating success, failure, or not found. - public static TagReadResult Read (ReadOnlySpan data) + public static TagReadResult Read (ReadOnlySpan data) => Read (data, new InflateBudget ()); + + /// + /// Reads a tag, inflating its compressed frames within , which a file read that parses more + /// than one tag shares among them (#275). + /// + internal static TagReadResult Read (ReadOnlySpan data, InflateBudget budget) { var headerResult = Id3v2Header.Read (data); @@ -1431,12 +1437,14 @@ public static TagReadResult Read (ReadOnlySpan data) // Process frame flags (v2.3/v2.4 only) if (!isV22 && formatFlags != 0) { - frameContent = ProcessFrameFlags (frameContent, formatFlags, header.MajorVersion); + frameContent = ProcessFrameFlags (frameContent, formatFlags, header.MajorVersion, budget); } // A frame no branch reads, or one its branch rejects, is kept as stored, flags and all, so a save writes it // back. A rejected frame goes when the tag writes or removes every frame of its ID (DropUnread). - if (!tag.ReadFrame (frameId, frameContent, (Id3v2Version)header.MajorVersion)) { + // A frame whose flags leave no content (encrypted, not inflating, or past the inflation budget) is rejected by + // its branch, as every branch rejects empty content, and kept as stored. + if (!tag.ReadFrame (frameId, frameContent, (Id3v2Version)header.MajorVersion, budget)) { tag._unreadFrames.Add (new UnreadFrame (frameId, isV22 ? (byte)0 : frameData[8], formatFlags, frameData.Slice (frameHeaderSize, frameSize).ToArray (), header.MajorVersion)); } @@ -1877,8 +1885,105 @@ public void RemoveAllPictures () } /// + /// + /// The tag, or one of its frames, would be larger than an ID3v2 size can hold (268,435,455 bytes). The message says + /// which; a file save reports this as a failure result instead. + /// public override BinaryData Render () => Render (DefaultPaddingSize, withFooter: false); + /// + /// The tag rendered, or null when it, or one of its frames, would be larger than an ID3v2 size can hold (#275): for a + /// save that renders a tag only to compare it, where a tag that cannot render is a changed one. + /// + internal BinaryData? TryRender (int paddingSize = DefaultPaddingSize, bool withFooter = false) + { + try { + return Render (paddingSize, withFooter); + } catch (Id3v2TagTooLargeException) { + return null; + } + } + + /// + /// A failure when would render larger than an ID3v2 size can hold (#275), so a save can + /// refuse before it writes anything. Null when the tag fits, or there is none. + /// + /// The tag the save writes, or null. + /// The padding the carrier renders the tag with, so the check refuses exactly the tags its + /// render would. + internal static FileWriteResult? SizeRefusal (Id3v2Tag? tag, int paddingSize = DefaultPaddingSize) + { + // The render, which copies the whole tag, runs only when a cheap bound on its size could pass the limit. + if (tag is null || tag.SizeBound () <= Id3v2TagTooLargeException.Limit) + return null; + try { + tag.Render (paddingSize, withFooter: false); + return null; + } catch (Id3v2TagTooLargeException error) { + return FileWriteResult.Failure (error.Message); + } + } + + /// + /// A bound on the bytes writes, from each frame's payload without rendering it: the binary + /// bytes as they are, bytes for each UTF-16 unit of text, for each frame, + /// and the header, footer, padding and, with a CHAP or CTOC, four times what its embedded frames hold and the save's + /// inflation budget, the most a re-encode of them can write. + /// + internal long SizeBound () + { + static long Text (string? text) => PerChar * (long)(text?.Length ?? 0); + + // The default padding is the most any carrier renders the tag with, so the bound holds for all of them. + long size = 2 * Id3v2Header.HeaderSize + DefaultPaddingSize; + // A compressed embedded frame inflates within the save budget, and is then re-encoded as above. + if (_chapterFrames.Count + _tableOfContentsFrames.Count > 0) + size += 4L * InflateBudget.PerSave; + foreach (var f in _frames) + size += PerFrame + Text (f.Text); + foreach (var f in _pictures) + size += PerFrame + f.MimeType.Length + Text (f.Description) + f.PictureData.Length; + foreach (var f in _comments) + size += PerFrame + Text (f.Description) + Text (f.Text); + foreach (var f in _lyricsFrames) + size += PerFrame + Text (f.Description) + Text (f.Text); + foreach (var f in _userTextFrames) + size += PerFrame + Text (f.Description) + Text (f.Value); + foreach (var f in _uniqueFileIdFrames) + size += PerFrame + Text (f.Owner) + f.Identifier.Length; + foreach (var f in _involvedPeopleFrames) + size += PerFrame + f.Pairs.Sum (p => PerFrame + Text (p.Role) + Text (p.Person)); + foreach (var f in _popularimeterFrames) + size += PerFrame + Text (f.Email); + foreach (var f in _urlFrames) + size += PerFrame + Text (f.Url); + foreach (var f in _userUrlFrames) + size += PerFrame + Text (f.Description) + Text (f.Url); + foreach (var f in _syncLyricsFrames) + size += PerFrame + Text (f.Description) + f.SyncItems.Sum (i => PerFrame + Text (i.Text)); + foreach (var f in _generalObjectFrames) + size += PerFrame + f.MimeType.Length + Text (f.FileName) + Text (f.Description) + f.Data.Length; + foreach (var f in _privateFrames) + size += PerFrame + Text (f.OwnerId) + f.Data.Length; + // A frame a CHAP or CTOC embeds is written as stored, or re-encoded: UTF-8 to UTF-16 doubles it, and a string of NULs + // gains a BOM and a terminator a value, so four times what is stored bounds it (#275). + foreach (var f in _chapterFrames) + size += 2 * PerFrame + Text (f.ElementId) + Text (f.Title) + 4 * f.EmbeddedStoredBytes; + foreach (var f in _tableOfContentsFrames) + size += 2 * PerFrame + Text (f.ElementId) + Text (f.Title) + f.ChildElementIds.Sum (id => PerFrame + Text (id)) + 4 * f.EmbeddedStoredBytes; + foreach (var f in _unreadFrames) + size += PerFrame + f.Body.Length; + return size; + } + + // A UTF-16 unit is at most 3 UTF-8 bytes, 2 UTF-16 bytes with a BOM and a terminator per string, or a URL's 9 bytes + // of %XX%XX%XX (#266). + const int PerChar = 9; + + // A frame header, its fixed fields (encoding, language, terminators, BOMs, counts, times) and up to 255 kept UTF-16 + // terminators. + const int PerFrame = 10 + 32 + 2 * 255; + /// /// Renders the tag to binary data with specified padding. /// @@ -1889,14 +1994,19 @@ public void RemoveAllPictures () /// The amount of padding to include. /// If true and version is 2.4, includes a footer. /// The rendered tag data. + /// + /// The tag, or one of its frames, would be larger than an ID3v2 size can hold (268,435,455 bytes). + /// public BinaryData Render (int paddingSize, bool withFooter = false) { // Every frame with a text encoding is written in one this version defines (Id3Text.WrittenEncoding). var version = (Id3v2Version)WrittenVersion; + // One inflation budget for the embedded frames a render re-encodes (#275). + var budget = new InflateBudget (InflateBudget.PerSave); // Render all frames and calculate size in single pass var frameDataList = new List ((_frames.Count + _pictures.Count + _comments.Count) * 2); - var framesSize = 0; + long framesSize = 0; for (var i = 0; i < _frames.Count; i++) { var content = _frames[i].RenderContent (version); @@ -2016,7 +2126,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render chapter frames (CHAP) for (var i = 0; i < _chapterFrames.Count; i++) { - var content = _chapterFrames[i].RenderContent (version); + var content = _chapterFrames[i].RenderContent (version, budget); var frameHeader = RenderFrameHeader ("CHAP", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -2025,7 +2135,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) // Render table of contents frames (CTOC) for (var i = 0; i < _tableOfContentsFrames.Count; i++) { - var content = _tableOfContentsFrames[i].RenderContent (version); + var content = _tableOfContentsFrames[i].RenderContent (version, budget); var frameHeader = RenderFrameHeader ("CTOC", content.Length); frameDataList.Add (frameHeader); frameDataList.Add (content); @@ -2045,6 +2155,9 @@ public BinaryData Render (int paddingSize, bool withFooter = false) } var totalSize = framesSize + paddingSize; + var limit = Id3v2TagTooLargeException.Limit; + if (totalSize > limit) + throw new Id3v2TagTooLargeException ("tag", totalSize, limit); // Footer is only valid for ID3v2.4 var includeFooter = withFooter && Version == 4; @@ -2060,7 +2173,7 @@ public BinaryData Render (int paddingSize, bool withFooter = false) var outputSize = Id3v2Header.HeaderSize + totalSize + (includeFooter ? Id3v2Header.FooterSize : 0); - using var builder = new BinaryDataBuilder (outputSize); + using var builder = new BinaryDataBuilder ((int)outputSize); builder.Add (header.Render ()); foreach (var frameData in frameDataList) @@ -2889,7 +3002,7 @@ static byte[] RemoveUnsynchronization (ReadOnlySpan data) /// the data length indicator (4 bytes) (https://id3.org/id3v2.4.0-structure §4.1.2). /// /// - static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte formatFlags, int majorVersion, int inflateAtMost = int.MaxValue) + static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte formatFlags, int majorVersion, InflateBudget budget, int inflateAtMost = int.MaxValue) { if (content.Length == 0 || formatFlags == 0) return content; @@ -2961,9 +3074,10 @@ static ReadOnlySpan ProcessFrameFlags (ReadOnlySpan content, byte fo data = unsyncBuffer; } - // A compressed frame that does not inflate is not text. Skip it. + // A compressed frame that does not inflate is not text. Skip it. Nor is one whose inflation the tag's budget + // cannot hold (#275): the caller keeps it as stored. if (hasCompression) { - if (decompressedSize <= 0) + if (decompressedSize <= 0 || !budget.TryTake (decompressedSize)) return ReadOnlySpan.Empty; var decompressed = DecompressZlib (data, decompressedSize, inflateAtMost); diff --git a/src/TagLibSharp2/Id3/Id3v2/Id3v2TagTooLargeException.cs b/src/TagLibSharp2/Id3/Id3v2/Id3v2TagTooLargeException.cs new file mode 100644 index 00000000..86b70028 --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/Id3v2TagTooLargeException.cs @@ -0,0 +1,51 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Id3.Id3v2; + +/// +/// Thrown when an ID3v2 tag, or one of its frames, would be larger than its size field can hold (#275): a syncsafe +/// size holds at most (https://id3.org/id3v2.4.0-structure §3.1, §4). +/// +internal sealed class Id3v2TagTooLargeException : InvalidOperationException +{ + /// The largest value a 28-bit syncsafe size holds. + public const long MaxSyncSafe = 0x0FFFFFFF; + + static readonly AsyncLocal s_limit = new (); + + /// The largest tag or frame size allowed: , or a test's lower limit. + public static long Limit => s_limit.Value ?? MaxSyncSafe; + + /// + /// A test seam: lowers for the calling flow until disposed, so a test needs no 256 MiB tag. + /// + public static IDisposable LowerLimit (long limit) + { + var previous = s_limit.Value; + s_limit.Value = limit; + return new Restore (previous); + } + + sealed class Restore (long? previous) : IDisposable + { + public void Dispose () => s_limit.Value = previous; + } + + public Id3v2TagTooLargeException (string what, long size, long limit = MaxSyncSafe) + : base ($"The ID3v2 {what} would be {size} bytes, more than an ID3v2 size can hold ({limit}).") + { + } + + public Id3v2TagTooLargeException () + { + } + + public Id3v2TagTooLargeException (string message) : base (message) + { + } + + public Id3v2TagTooLargeException (string message, Exception innerException) : base (message, innerException) + { + } +} diff --git a/src/TagLibSharp2/Id3/Id3v2/InflateBudget.cs b/src/TagLibSharp2/Id3/Id3v2/InflateBudget.cs new file mode 100644 index 00000000..741462a2 --- /dev/null +++ b/src/TagLibSharp2/Id3/Id3v2/InflateBudget.cs @@ -0,0 +1,50 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Id3.Id3v2; + +/// +/// The bytes one read of a file, or one save, may inflate from compressed ID3v2 frames, shared by every frame of every +/// tag the read or save parses, top-level and embedded in CHAP or CTOC (#275). A frame whose declared decompressed size +/// would pass what is left is not decoded: it is kept as stored and written back byte for byte. So the work and memory of +/// a read or a save are bounded by this budget and the input, whatever the file declares. +/// +/// +/// is four times the per-frame cap (16 MiB, with a 1,100:1 ratio, in the decompression): a tag with a +/// few large compressed frames, a comment and two pictures say, reads whole, and a file of many compressed frames, which +/// no tagger writes, cannot multiply it. +/// +internal sealed class InflateBudget +{ + /// The bytes one read of a file may inflate. + public const int PerTag = 64 * 1024 * 1024; + + /// + /// The bytes one render may inflate to re-encode or convert the frames a CHAP or CTOC embeds. Smaller than a read's: + /// each byte a save re-encodes is copied several times (inflated, decoded, encoded and written), and a save only + /// re-encodes what an earlier version wrote in an encoding v2.3 does not define, or a chapter moved between versions. + /// + public const int PerSave = 16 * 1024 * 1024; + + /// A budget that allows nothing: a read that only decides whether bytes are a tag decodes no frame. + public static InflateBudget None => new (0); + + /// + /// For a frame whose declared size was already taken from the budget: a second inflation of the same frame, bounded + /// by that size, takes nothing more. + /// + public static InflateBudget Charged => new (long.MaxValue); + + long _left; + + public InflateBudget (long size = PerTag) => _left = size; + + /// Takes from the budget, or returns false and takes nothing when they do not fit. + public bool TryTake (int bytes) + { + if (bytes < 0 || bytes > _left) + return false; + _left -= bytes; + return true; + } +} diff --git a/src/TagLibSharp2/Mpeg/Mp3File.cs b/src/TagLibSharp2/Mpeg/Mp3File.cs index 36e3ebbb..767648c8 100644 --- a/src/TagLibSharp2/Mpeg/Mp3File.cs +++ b/src/TagLibSharp2/Mpeg/Mp3File.cs @@ -833,22 +833,27 @@ async Task Adopt (Task save, Written written, /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - - if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) - return mismatch; - - var written = Plan (originalData.Length); - var rendered = Assemble (originalData, written); - if (rendered.IsEmpty) - return FileWriteResult.Failure ("Failed to render MP3 file"); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + + if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) + return mismatch; + + var written = Plan (originalData.Length); + var rendered = Assemble (originalData, written); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("Failed to render MP3 file"); - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -867,22 +872,27 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - - if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); - - var written = Plan (originalData.Length); - var rendered = Assemble (originalData.Span, written); - if (rendered.IsEmpty) - return Task.FromResult (FileWriteResult.Failure ("Failed to render MP3 file")); - - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + + if (Source.Refuse ("MP3", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); + + var written = Plan (originalData.Length); + var rendered = Assemble (originalData.Span, written); + if (rendered.IsEmpty) + return Task.FromResult (FileWriteResult.Failure ("Failed to render MP3 file")); + + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -903,15 +913,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -929,15 +944,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -952,15 +972,20 @@ public Task SaveToFileAsync ( /// A result indicating success or failure. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } // Same bytes as Render: new ID3v2, the original audio, new ID3v1. @@ -1023,15 +1048,20 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, /// A result indicating success or failure. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - _creation?.Settle ([Id3v2Tag, Id3v1Tag]); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveToFile (SourcePath!, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle ([Id3v2Tag, Id3v1Tag]); + if (PictureSkip.Refuse (this, Id3v2Tag) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// diff --git a/src/TagLibSharp2/Mpeg/MpegPsFile.cs b/src/TagLibSharp2/Mpeg/MpegPsFile.cs index 520bd9d2..77a18e28 100644 --- a/src/TagLibSharp2/Mpeg/MpegPsFile.cs +++ b/src/TagLibSharp2/Mpeg/MpegPsFile.cs @@ -705,8 +705,10 @@ static MpegPsFileReadResult Build ( }; file.Source.Record (length); + // One inflation budget for both tags this read parses (#275). + var budget = new InflateBudget (); if (tag.Length > 0) { - var parsed = Id3v2Tag.Read (tag); + var parsed = Id3v2Tag.Read (tag, budget); if (parsed.IsSuccess) file.Id3v2Tag = file._readId3v2 = parsed.Tag; } @@ -715,7 +717,7 @@ static MpegPsFileReadResult Build ( // unless the update flag in the extended header (section 3.2) is set." The appended tag // is found after the prepended one, so it replaces it, or updates it. if (!appended.IsEmpty) { - var parsed = Id3v2Tag.Read (appended); + var parsed = Id3v2Tag.Read (appended, budget); if (parsed.IsSuccess) { file._readAppended = parsed.Tag; if (IsUpdate (appended)) @@ -891,6 +893,10 @@ ReadOnlySpan Id3v1Original (ReadOnlySpan originalData) => /// bool WritesAppended => _readAppended is not null && Id3v2Tag is { Version: 4 }; + // The padding the tag a save writes is rendered with (#275): none for an appended tag, whose update form adds a + // 7-byte extended header (RenderForEnd), and the default for a prepended one. + internal int Id3PaddingSize => WritesAppended ? (EarlierTag is null ? 0 : 7) : Id3v2Tag.DefaultPaddingSize; + // The tag that was read and still renders as it did keeps its original bytes, padding included. // A prepended tag whose bytes did not parse stays until a tag is written in front in its place. ReadOnlySpan RenderPrependedId3v2 (ReadOnlySpan original, bool appendedUnchanged) @@ -900,7 +906,7 @@ ReadOnlySpan RenderPrependedId3v2 (ReadOnlySpan original, bool appen if (unparsed) return original; if (EarlierTag is { } earlier) - return KeepIfUnchanged (earlier, _readId3v2, original, earlier.Render (), static tag => tag.Render ()); + return KeepIfUnchanged (earlier, _readId3v2, original, earlier.Render (), static tag => tag.TryRender ()); // The appended tag replaced this one (section 5). An unchanged save keeps the file as it was. return appendedUnchanged ? original : []; @@ -908,7 +914,7 @@ ReadOnlySpan RenderPrependedId3v2 (ReadOnlySpan original, bool appen if (Id3v2Tag is null) return unparsed ? original : []; - return KeepIfUnchanged (Id3v2Tag, _readId3v2, original, Id3v2Tag.Render (), static tag => tag.Render ()); + return KeepIfUnchanged (Id3v2Tag, _readId3v2, original, Id3v2Tag.Render (), static tag => tag.TryRender ()); } ReadOnlySpan RenderAppendedId3v2 (ReadOnlySpan original, out bool unchanged) @@ -923,7 +929,7 @@ ReadOnlySpan RenderAppendedId3v2 (ReadOnlySpan original, out bool un var update = EarlierTag is not null; var rendered = RenderForEnd (Id3v2Tag!, update); - var kept = KeepIfUnchanged (Id3v2Tag!, _readAppended, original, rendered, tag => RenderForEnd (tag, update)); + var kept = KeepIfUnchanged (Id3v2Tag!, _readAppended, original, rendered, tag => TryRenderForEnd (tag, update)); unchanged = kept == original; return kept; } @@ -933,11 +939,12 @@ static ReadOnlySpan KeepIfUnchanged ( Id3v2Tag? read, ReadOnlySpan original, BinaryData rendered, - Func render) + Func render) { + // The tag as read, rendered again; one that cannot render, too large for its size field, is a changed one (#275). if (ReferenceEquals (tag, read)) { var reread = Id3v2Tag.Read (original); - if (reread.IsSuccess && render (reread.Tag!).Span.SequenceEqual (rendered.Span)) + if (reread.IsSuccess && render (reread.Tag!) is { } again && again.Span.SequenceEqual (rendered.Span)) return original; } @@ -948,6 +955,16 @@ static ReadOnlySpan KeepIfUnchanged ( /// An appended tag: v2.4 with a footer and no padding. An update tag keeps the extended /// header that says so (3.2): size 7, one flag byte with flag b set, and that flag's empty data. /// + // RenderForEnd, or null when the tag is too large for its size field (#275). + static BinaryData? TryRenderForEnd (Id3v2Tag tag, bool update) + { + try { + return RenderForEnd (tag, update); + } catch (Id3v2TagTooLargeException) { + return null; + } + } + static BinaryData RenderForEnd (Id3v2Tag tag, bool update) { var rendered = tag.Render (0, withFooter: true); @@ -958,6 +975,8 @@ static BinaryData RenderForEnd (Id3v2Tag tag, bool update) var bytes = rendered.Span; var body = bytes.Slice (Id3v2Header.HeaderSize, bytes.Length - Id3v2Header.HeaderSize - Id3v2Header.FooterSize); var size = body.Length + extended.Length; + if (size > Id3v2TagTooLargeException.Limit) + throw new Id3v2TagTooLargeException ("tag", size, Id3v2TagTooLargeException.Limit); Span header = stackalloc byte[Id3v2Header.HeaderSize]; bytes.Slice (0, Id3v2Header.HeaderSize).CopyTo (header); header[5] |= 0x40; @@ -1002,20 +1021,25 @@ ReadOnlySpan RenderId3v1 (ReadOnlySpan original) /// Whether the write succeeded. public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - - if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) - return mismatch; - var rendered = Assemble (originalData, out var written); - if (rendered.IsEmpty) - return FileWriteResult.Failure ("The original data is not the MPEG stream that was read"); - - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, rendered.Memory, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + + if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) + return mismatch; + var rendered = Assemble (originalData, out var written); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("The original data is not the MPEG stream that was read"); + + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, rendered.Memory, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -1027,15 +1051,20 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// Whether the write succeeded. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveFromSource (path, fileSystem ?? _sourceFileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -1045,15 +1074,20 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// Whether the write succeeded. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (Id3v1Refusal () is string refusal) - return FileWriteResult.Failure (refusal); - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveToFile (SourcePath!, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return denied; + if (Id3v1Refusal () is string refusal) + return FileWriteResult.Failure (refusal); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -1072,20 +1106,25 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - - if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); - var rendered = Assemble (originalData.Span, out var written); - if (rendered.IsEmpty) - return Task.FromResult (FileWriteResult.Failure ("The original data is not the MPEG stream that was read")); - - fileSystem ??= _sourceFileSystem; - return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, rendered.Memory, fileSystem); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + + if (Source.Refuse ("MPEG-PS", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); + var rendered = Assemble (originalData.Span, out var written); + if (rendered.IsEmpty) + return Task.FromResult (FileWriteResult.Failure ("The original data is not the MPEG stream that was read")); + + fileSystem ??= _sourceFileSystem; + return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, rendered.Memory, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// @@ -1104,15 +1143,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return Task.FromResult (SaveFromSource (path, fileSystem ?? _sourceFileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } const string NotTheReadStream = "The original data is not the MPEG stream that was read"; @@ -1209,15 +1253,20 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - _creation?.Settle (TagSources ()); - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (Id3v1Refusal () is string refusal) - return Task.FromResult (FileWriteResult.Failure (refusal)); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + // A tag a save renders that is too large for its size field fails the save, never throws (#275). + try { + _creation?.Settle (TagSources ()); + if (PictureSkip.Refuse (this, Id3v2Tag, Id3PaddingSize) is { } denied) + return Task.FromResult (denied); + if (Id3v1Refusal () is string refusal) + return Task.FromResult (FileWriteResult.Failure (refusal)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// diff --git a/src/TagLibSharp2/Riff/AviFile.cs b/src/TagLibSharp2/Riff/AviFile.cs index 294d9b54..dd960395 100644 --- a/src/TagLibSharp2/Riff/AviFile.cs +++ b/src/TagLibSharp2/Riff/AviFile.cs @@ -464,16 +464,21 @@ public BinaryData Render (ReadOnlySpan originalData) => /// public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) { - if (PictureSkip.Refuse (this) is { } denied) - return denied; + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return denied; - if (Source.Refuse ("AVI", originalData.Length) is { } mismatch) - return mismatch; + if (Source.Refuse ("AVI", originalData.Length) is { } mismatch) + return mismatch; - if (!AviRewrite.TryRewrite (originalData, InfoTag, Id3v2Tag, out var rewritten, out var error)) - return FileWriteResult.Failure (error); + 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 Source.Saved (AtomicFileWriter.Write (path, rewritten, fileSystem ?? _sourceFileSystem)); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// Saves the tags into , copying the container from . @@ -483,12 +488,17 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, /// Sample bytes are copied in chunks. and the span overloads still build one buffer. public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - if (PictureSkip.Refuse (this) is { } denied) - return denied; - 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)); + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return denied; + 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)); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// Saves the tags back to . @@ -496,12 +506,17 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) /// The write result. public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) { - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (string.IsNullOrEmpty (SourcePath)) - return FileWriteResult.Failure ("No source path available. File was not read from disk."); - - return SaveToFile (SourcePath!, fileSystem); + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return denied; + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + return SaveToFile (SourcePath!, fileSystem); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// Saves the tags into using as the container. @@ -517,16 +532,21 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return Task.FromResult (denied); - if (Source.Refuse ("AVI", originalData.Length) is { } mismatch) - return Task.FromResult (mismatch); + if (Source.Refuse ("AVI", originalData.Length) is { } mismatch) + return Task.FromResult (mismatch); - if (!AviRewrite.TryRewrite (originalData.Span, InfoTag, Id3v2Tag, out var rewritten, out var error)) - return Task.FromResult (FileWriteResult.Failure (error)); + 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 Source.Saved (AtomicFileWriter.WriteAsync (path, rewritten, fileSystem ?? _sourceFileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// Saves the tags into , copying the container from . @@ -540,12 +560,17 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - 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))); + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return Task.FromResult (denied); + 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))); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } // Copies the file in chunks. movi payload is not read into one buffer. Indexes are patched @@ -593,12 +618,17 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + // 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, AviRewrite.Id3PaddingSize) is { } denied) + return Task.FromResult (denied); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } /// Releases the tags held by this instance. diff --git a/src/TagLibSharp2/Riff/AviRewrite.cs b/src/TagLibSharp2/Riff/AviRewrite.cs index edfc8c7b..1acd5f71 100644 --- a/src/TagLibSharp2/Riff/AviRewrite.cs +++ b/src/TagLibSharp2/Riff/AviRewrite.cs @@ -233,11 +233,14 @@ static bool Id3Changed (bool present, Id3v2Tag? original, Id3v2Tag? current) return current is { IsEmpty: false }; if (original is null) return current is not null; - return current is null || !RenderId3 (current).Equals (RenderId3 (original)); + // A tag as read that cannot render, too large for its size field, is a changed one (#275). + return current is null || original.TryRender (0) is not { } read || !RenderId3 (current).Equals (read); } /// An ID3v2 tag in a RIFF chunk needs no padding of its own; JUNK holds the spare room. - static BinaryData RenderId3 (Id3v2Tag tag) => tag.Render (0); + internal const int Id3PaddingSize = 0; + + static BinaryData RenderId3 (Id3v2Tag tag) => tag.Render (Id3PaddingSize); static byte[] Blob (BinaryData list, byte[]? characterSet, Id3v2Tag? id3, bool id3Changed, string id3FourCC) { @@ -665,13 +668,15 @@ internal static bool TryPlanStream ( AviTopChunk id3Chunk = default; Id3v2Tag? originalId3 = null; walk.Reset (); + // One inflation budget for every ID3 chunk this save parses (#275). + var budget = new InflateBudget (); while (walk.MoveNext ()) { var item = walk.Current; if (!item.IsId3 || !AviChunks.IsReadable (item)) continue; id3Present = true; id3Chunk = item; - var result = Id3v2Tag.Read (ReadBody (source, item, length, chunk)); + var result = Id3v2Tag.Read (ReadBody (source, item, length, chunk), budget); if (result.IsSuccess) originalId3 = result.Tag; break; diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs index ab1d765a..5e74ef96 100644 --- a/src/TagLibSharp2/Riff/WavFile.cs +++ b/src/TagLibSharp2/Riff/WavFile.cs @@ -174,7 +174,7 @@ internal void MarkPicturesSkipped () public MediaFormat Format => MediaFormat.Wav; /// - /// True when an id3 chunk was present and did not accept it. + /// True when an id3 chunk was present and did not accept it. /// A parsed tag that the caller later clears is not this case. /// bool _keepUnparsedId3; @@ -698,15 +698,20 @@ bool TryLoadSkippedSamples (out string? error) /// public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) { - if (PictureSkip.Refuse (this) is { } denied) - return denied; - if (SaveRefusal () is { } failure) - return failure; + // 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 (SaveRefusal () is { } failure) + return failure; - if (_skippedChunks.Count == 0) - return SaveLoaded (path, fileSystem); + if (_skippedChunks.Count == 0) + return SaveLoaded (path, fileSystem); - return SaveFromSource (path, fileSystem, default); + return SaveFromSource (path, fileSystem, default); + } catch (Id3v2TagTooLargeException tooLarge) { + return FileWriteResult.Failure (tooLarge.Message); + } } /// @@ -723,16 +728,21 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (SaveRefusal () is { } failure) - return Task.FromResult (failure); - - if (_skippedChunks.Count == 0) - return SaveLoadedAsync (path, fileSystem, cancellationToken); - - // Length and "was not loaded" are decided before the token, matching the sync save. - return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + // 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 Task.FromResult (denied); + if (SaveRefusal () is { } failure) + return Task.FromResult (failure); + + if (_skippedChunks.Count == 0) + return SaveLoadedAsync (path, fileSystem, cancellationToken); + + // Length and "was not loaded" are decided before the token, matching the sync save. + return Task.FromResult (SaveFromSource (path, fileSystem, cancellationToken)); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } FileWriteResult SaveLoaded (string path, IFileSystem? fileSystem) @@ -769,10 +779,14 @@ bool TagRewritten () return true; var chunk = _riff.GetChunk (Id3ChunkId); - byte[]? read = chunk is { } found && found.Data.Length > 0 - && Id3v2Tag.Read (found.Data.Span) is { IsSuccess: true, Tag: { IsEmpty: false } readTag } - ? readTag.Render ().ToArray () - : null; + byte[]? read = null; + if (chunk is { } found && found.Data.Length > 0 + && Id3v2Tag.Read (found.Data.Span) is { IsSuccess: true, Tag: { IsEmpty: false } readTag }) { + // A tag as read that cannot render, too large for its size field, is a changed one (#275). + if (readTag.TryRender () is not { } rendered) + return true; + read = rendered.ToArray (); + } byte[]? written = Id3v2Tag is { IsEmpty: false } tag ? tag.Render ().ToArray () : null; return read is null ? written is not null : written is null || !read.AsSpan ().SequenceEqual (written); } @@ -1113,13 +1127,18 @@ public Task SaveToFileAsync ( IFileSystem? fileSystem = null, CancellationToken cancellationToken = default) { - if (PictureSkip.Refuse (this) is { } denied) - return Task.FromResult (denied); - if (string.IsNullOrEmpty (SourcePath)) - return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - - var fs = fileSystem ?? _sourceFileSystem; - return SaveToFileAsync (SourcePath!, fs, cancellationToken); + // 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 Task.FromResult (denied); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + + var fs = fileSystem ?? _sourceFileSystem; + return SaveToFileAsync (SourcePath!, fs, cancellationToken); + } catch (Id3v2TagTooLargeException tooLarge) { + return Task.FromResult (FileWriteResult.Failure (tooLarge.Message)); + } } } diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2InflateBudgetTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2InflateBudgetTests.cs new file mode 100644 index 00000000..b73fbc53 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2InflateBudgetTests.cs @@ -0,0 +1,661 @@ +// 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.IO.Compression; + +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Tests.Kit; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// One inflation budget per read and per render of an ID3v2 tag, shared by every compressed frame, top-level and +/// embedded (issue #275). A frame past the budget is kept as stored and written back byte for byte, so a crafted tag of +/// many small compressed frames that each declare a large size cannot make a read or a save allocate without bound, and +/// a save never throws on a size the format cannot hold. +/// +// Allocation bounds: parallel tests share the array pools, so a pool miss caused by another test would count here. +[TestClass] +[DoNotParallelize] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2InflateBudgetTests +{ + const int MiB = 1024 * 1024; + + static byte[] Deflate (byte[] data) + { + using var output = new MemoryStream (); + using (var zlib = new ZLibStream (output, CompressionLevel.Optimal)) + zlib.Write (data); + return output.ToArray (); + } + + /// A v2.3 compressed frame body: the 4-byte decompressed size, then the zlib stream. + static byte[] Compressed (byte[] content) => + [(byte)(content.Length >> 24), (byte)(content.Length >> 16), (byte)(content.Length >> 8), (byte)content.Length, .. Deflate (content)]; + + static byte[] Frame (string id, byte[] body, byte format = 0) + { + var frame = TestBuilders.Id3v2.CreateFrame (id, body, 3); + frame[9] = format; + return frame; + } + + static byte[] Tag (byte[] frames) => [.. TestBuilders.Id3v2.CreateHeader (3, (uint)frames.Length), .. frames]; + + /// compressed top-level TXXX frames, each inflating to bytes. + static byte[] TopLevel (int count, int size) + { + var frames = new List (); + for (var i = 0; i < count; i++) { + byte[] content = [0, .. System.Text.Encoding.ASCII.GetBytes ("d" + i), 0, .. Enumerable.Repeat ((byte)'a', size)]; + frames.AddRange (Frame ("TXXX", Compressed (content), 0x80)); + } + return Tag ([.. frames]); + } + + /// A CHAP holding compressed text frames of in UTF-8. + static byte[] Embedded (int count, int size, string id) + { + var body = Compressed ([3, .. Enumerable.Repeat ((byte)'a', size)]); + var sub = new List (); + for (var i = 0; i < count; i++) + sub.AddRange (Frame (id, body, 0x80)); + byte[] chap = [.. "ch1"u8, 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, .. sub]; + return Tag (Frame ("CHAP", chap)); + } + + /// CHAPs, each holding one compressed text frame of in UTF-8. + static byte[] Chapters (int count, int size, string id) + { + var sub = Frame (id, Compressed ([3, .. Enumerable.Repeat ((byte)'a', size)]), 0x80); + var frames = new List (); + for (var i = 0; i < count; i++) { + byte[] chap = [.. System.Text.Encoding.ASCII.GetBytes ("c" + i), 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, .. sub]; + frames.AddRange (Frame ("CHAP", chap)); + } + return Tag ([.. frames]); + } + + // The budget is the tag's, not each CHAP's: many CHAPs each holding one compressed title, or one compressed text + // frame to re-encode, share it on a read and on a save. + [TestMethod] + public void ReadAndRender_ManyChaptersWithACompressedFrameEach_ShareOneBudget () + { + foreach (var id in new[] { "TIT2", "TIT3" }) { + var n = Chapters (16, 4 * MiB, id); + var fourN = Chapters (64, 4 * MiB, id); + Id3v2Tag.Read (n); + var nTag = Id3v2Tag.Read (n).Tag!; + var fourNTag = Id3v2Tag.Read (fourN).Tag!; + nTag.Render (); + + var readN = Bounds.LeastAllocated (() => Id3v2Tag.Read (n)); + var readFourN = Bounds.LeastAllocated (() => Id3v2Tag.Read (fourN)); + var renderN = Bounds.LeastAllocated (() => nTag.Render ()); + var renderFourN = Bounds.LeastAllocated (() => fourNTag.Render ()); + + Assert.IsLessThan ((long)InflateBudget.PerTag, readFourN - readN, $"{id} read: N {readN} bytes, 4N {readFourN} bytes"); + Assert.IsLessThan ((long)InflateBudget.PerTag, renderFourN - renderN, $"{id} render: N {renderN} bytes, 4N {renderFourN} bytes"); + } + } + + // A compressed URL frame past the budget is kept as stored, not written back empty. + [TestMethod] + public void Save_CompressedUrlFramePastTheBudget_IsWrittenAsStored () + { + var big = Compressed ([0, .. Enumerable.Repeat ((byte)'b', 16 * MiB - 1)]); + var url = Compressed ("http://a.example/"u8.ToArray ()); + var tag = Tag ([.. Frame ("TIT2", big, 0x80), .. Frame ("TPE1", big, 0x80), .. Frame ("TALB", big, 0x80), + .. Frame ("TCOM", big, 0x80), .. Frame ("WOAR", url, 0x80)]); + + var written = Id3v2WrittenEncodingTests.WrittenFrames (Id3v2Tag.Read (tag).Tag!.Render ().ToArray ()); + + CollectionAssert.AreEqual (url, written.Single (f => f.Id == "WOAR").Body); + } + + // A read inflates at most the budget, however many compressed frames the tag holds: 4N frames allocate less than one + // budget more than N frames that already fill it, where inflating the 3N more would take several budgets. + [TestMethod] + public void Read_ManyCompressedFrames_InflatesWithinOneBudget () + { + var n = TopLevel (16, 4 * MiB); + var fourN = TopLevel (64, 4 * MiB); + Id3v2Tag.Read (n); + + var nBytes = Bounds.LeastAllocated (() => Id3v2Tag.Read (n)); + var fourNBytes = Bounds.LeastAllocated (() => Id3v2Tag.Read (fourN)); + + Assert.IsLessThan ((long)InflateBudget.PerTag, fourNBytes - nBytes, $"N: {nBytes} bytes, 4N: {fourNBytes} bytes"); + } + + // The embedded titles a read inflates share the tag's budget. + [TestMethod] + public void Read_ManyCompressedEmbeddedTitles_InflatesWithinOneBudget () + { + var n = Embedded (16, 4 * MiB, "TIT2"); + var fourN = Embedded (64, 4 * MiB, "TIT2"); + Id3v2Tag.Read (n); + + var nBytes = Bounds.LeastAllocated (() => Id3v2Tag.Read (n)); + var fourNBytes = Bounds.LeastAllocated (() => Id3v2Tag.Read (fourN)); + + Assert.IsLessThan ((long)InflateBudget.PerTag, fourNBytes - nBytes, $"N: {nBytes} bytes, 4N: {fourNBytes} bytes"); + } + + // A v2.3 save re-encodes embedded UTF-8 text within one budget; the frames past it are written as stored. + [TestMethod] + public void Render_ManyCompressedEmbeddedTextFrames_ReEncodesWithinOneBudget () + { + var n = Id3v2Tag.Read (Embedded (16, 4 * MiB, "TIT3")).Tag!; + var fourN = Id3v2Tag.Read (Embedded (64, 4 * MiB, "TIT3")).Tag!; + n.Render (); + + var nBytes = Bounds.LeastAllocated (() => n.Render ()); + var fourNBytes = Bounds.LeastAllocated (() => fourN.Render ()); + + Assert.IsLessThan ((long)InflateBudget.PerTag, fourNBytes - nBytes, $"N: {nBytes} bytes, 4N: {fourNBytes} bytes"); + } + + // The reviewer's file: 50 compressed embedded text frames in UTF-8, each declaring 16 MiB, in an 819 KB tag. A read and + // a save do not throw and write every frame, those past the budget as stored. A read inflates no TIT3 (only titles are + // decoded); a save re-encodes within the save budget, one frame here. What they allocate is a small multiple of the + // save budget plus the read budget, and the same for 200 such frames as for 50. + [TestMethod] + public void ReadAndSave_FiftyEmbeddedFramesOf16MiB_StayWithinTheBudget () + { + (long Read, long Saved, byte[] Bytes) ReadEditSave (int count) + { + // [3] and 16 MiB - 1 characters: exactly the per-frame cap, so each frame alone would inflate. + byte[] mp3 = [.. Embedded (count, 16 * MiB - 1, "TIT3"), .. new byte[256]]; + byte[] saved = []; + var read = Bounds.LeastAllocated (() => Mp3File.Read (mp3)); + var all = Bounds.LeastAllocated (() => { + var file = Mp3File.Read (mp3).File!; + file.Id3v2Tag!.Album = "edited"; + saved = file.Render (mp3).ToArray (); + }); + return (read, all, saved); + } + + var (fiftyRead, fifty, saved) = ReadEditSave (50); + var (_, twoHundred, _) = ReadEditSave (200); + Console.WriteLine ($"50 frames: read {fiftyRead} bytes, read+edit+save {fifty} bytes; 200 frames: {twoHundred} bytes"); + + // Each byte the save re-encodes is copied about eight times: inflated, decoded to UTF-16 (two bytes a byte), + // encoded to ISO-8859-1, rendered into its frame, into the temporary tag, into the CHAP and, with the builders' + // doubling, into the tag and the file. So k = 10. + const long k = 10; + Assert.IsLessThan (k * InflateBudget.PerSave + InflateBudget.PerTag, fifty, $"read+edit+save {fifty} bytes"); + // 150 more frames add their input's copies, not their inflation: one more frame re-encoded would add k × 16 MiB. + Assert.IsLessThan (InflateBudget.PerTag, twoHundred - fifty, $"50 frames: {fifty} bytes, 200 frames: {twoHundred} bytes"); + Assert.IsLessThan (InflateBudget.PerSave + 2L * MiB, saved.Length, $"{saved.Length} bytes saved"); + Assert.AreEqual ("edited", Id3v2Tag.Read (saved).Tag!.Album); + Assert.AreEqual (50, Id3v2WrittenEncodingTests.WrittenFrames (saved).Count (f => f.Id == "TIT3"), "every embedded frame is written"); + } + + + + // A compressed top-level frame past the budget is not decoded: it is kept and written back byte for byte. + [TestMethod] + public void Save_CompressedFramePastTheBudget_IsWrittenAsStored () + { + var big = Compressed ([0, .. Enumerable.Repeat ((byte)'b', 16 * MiB - 1)]); + var past = Compressed ([0, .. "x"u8, 0, .. Enumerable.Repeat ((byte)'c', 8)]); + var tag = Tag ([.. Frame ("TIT2", big, 0x80), .. Frame ("TPE1", big, 0x80), .. Frame ("TALB", big, 0x80), + .. Frame ("TCOM", big, 0x80), .. Frame ("TXXX", past, 0x80)]); + + var read = Id3v2Tag.Read (tag).Tag!; + var written = Id3v2WrittenEncodingTests.WrittenFrames (read.Render ().ToArray ()); + + Assert.AreEqual (16 * MiB - 1, read.Title?.Length, "the first four frames fill the budget and are read"); + var txxx = written.Single (f => f.Id == "TXXX"); + CollectionAssert.AreEqual (past, txxx.Body, "the frame past the budget is written as stored"); + } + + // Ordinary compressed frames read, and re-encode for v2.3 as before (#255, #265). + [TestMethod] + public void ReadAndRender_OrdinaryCompressedFrames_RoundTrip () + { + var tag = Tag ([ + .. Frame ("TIT2", Compressed ([0, .. "Song"u8]), 0x80), + .. Frame ("TPE1", Compressed ([0, .. "Band"u8]), 0x80)]); + + var read = Id3v2Tag.Read (tag).Tag!; + var again = Id3v2Tag.Read (read.Render ().ToArray ()).Tag!; + + Assert.AreEqual ("Song", again.Title); + Assert.AreEqual ("Band", again.Performers.Single ()); + } + + // A frame or tag larger than an ID3v2 size can hold is refused with its own message, never written with a + // wrapped size or an ArgumentOutOfRangeException from the syncsafe writer. + [TestMethod] + public void AddFrameHeader_SizePastSyncSafe_ThrowsTooLarge () + { + using var builder = new BinaryDataBuilder (10); + + var error = Assert.ThrowsExactly (() => + Id3v2Tag.AddFrameHeader (builder, "APIC", 0x10000000, Id3v2Version.V24)); + + StringAssert.Contains (error.Message, "more than an ID3v2 size can hold"); + } + + // The tag's own size is checked too, before anything is allocated for it: padding that would carry the tag past + // what its size can hold is refused with the same message. + [TestMethod] + public void Render_TagPastSyncSafe_ThrowsTooLarge () + { + var tag = new Id3v2Tag (Id3v2Version.V24) { Title = "t" }; + + var error = Assert.ThrowsExactly (() => tag.Render (0x0FFFFFFF, withFooter: false)); + + StringAssert.Contains (error.Message, "ID3v2 tag would be"); + } + + public static IEnumerable CarrierSaves => + from format in Id3v22CarrierBuilder.Formats + from save in Id3v2WrittenEncodingCarrierTests.Saves + where save != "render" && Id3v2WrittenEncodingCarrierTests.HasSave (format.Format, save) + select new object[] { format.Format, format.Extension, save }; + + // A save whose ID3v2 tag would be larger than its size can hold fails with the reason, writes nothing, and leaves + // the object as it was: with the limit back, the same object saves (#275). The limit is lowered for the test. + [TestMethod] + [DynamicData (nameof (CarrierSaves))] + public async Task Save_TagTooLarge_FailsAndWritesNothing (string format, string extension, string save) + { + var original = Id3v22CarrierBuilder.Build (format, [.. TestBuilders.Id3v2.CreateHeader (3, 16), .. new byte[16]]); + var files = new TagLibSharp2.Tests.Core.MockFileSystem (); + var name = "/file" + extension; + files.AddFile (name, original); + var file = (IMediaFile)MediaFile.Read (name, files).File!; + Id3v22CarrierBuilder.Id3 (file)!.Title = new string ('x', 3000); + + FileWriteResult result; + using (Id3v2TagTooLargeException.LowerLimit (2000)) + result = await Id3v2WrittenEncodingCarrierTests.SaveResultAsync (file, original, files, name, save); + + Assert.IsFalse (result.IsSuccess, "the save"); + StringAssert.Contains (result.Error!, "more than an ID3v2 size can hold"); + Assert.IsFalse (files.FileExists ("/out"), "nothing written to the destination"); + CollectionAssert.AreEqual (original, files.ReadAllBytes (name), "the source is byte-identical"); + + var again = await Id3v2WrittenEncodingCarrierTests.SaveResultAsync (file, original, files, name, save); + Assert.IsTrue (again.IsSuccess, again.Error); + var saved = files.ReadAllBytes (save.EndsWith ("in-place", StringComparison.Ordinal) ? name : "/out"); + Assert.AreEqual (3000, Id3v22CarrierBuilder.Id3 (MediaFile.ReadFromData (saved, name).File!)!.Title!.Length); + } + + // A render of a carrier's bytes cannot return a failure, so it throws the documented InvalidOperationException. + [TestMethod] + public void Render_Mp3WithTagTooLarge_ThrowsInvalidOperation () + { + byte[] mp3 = [.. TestBuilders.Id3v2.CreateHeader (3, 16), .. new byte[16], .. new byte[256]]; + var file = Mp3File.Read (mp3).File!; + file.Id3v2Tag!.Title = new string ('x', 3000); + + using (Id3v2TagTooLargeException.LowerLimit (2000)) { + var error = Assert.Throws (() => file.Render (mp3)); + StringAssert.Contains (error.Message, "more than an ID3v2 size can hold"); + } + } + + /// A v2.3 tag whose one compressed TIT2 declares 16 MiB, about 16 KB stored. + static byte[] BombTag () => Tag (Frame ("TIT2", Compressed ([0, .. Enumerable.Repeat ((byte)'a', 16 * MiB - 1)]), 0x80)); + + static byte[] Chunk (string id, byte[] body, bool bigEndian) + { + var size = body.Length; + byte[] header = [.. System.Text.Encoding.ASCII.GetBytes (id), + .. bigEndian + ? new[] { (byte)(size >> 24), (byte)(size >> 16), (byte)(size >> 8), (byte)size } + : new[] { (byte)size, (byte)(size >> 8), (byte)(size >> 16), (byte)(size >> 24) }]; + return (size & 1) == 1 ? [.. header, .. body, 0] : [.. header, .. body]; + } + + /// An AIFF with ID3 chunks in its FORM and after it. + static byte[] Aiff (int inForm, int trailing) + { + var form = TestBuilders.Aiff.CreateMinimal ().ToList (); + var tag = BombTag (); + for (var i = 0; i < inForm; i++) + form.AddRange (Chunk ("ID3 ", tag, bigEndian: true)); + var size = form.Count - 8; + form[4] = (byte)(size >> 24); form[5] = (byte)(size >> 16); form[6] = (byte)(size >> 8); form[7] = (byte)size; + for (var i = 0; i < trailing; i++) + form.AddRange (Chunk ("ID3 ", tag, bigEndian: true)); + return [.. form]; + } + + /// A WAV with one id3 chunk in its RIFF and after it. + static byte[] Wav (int trailing) + { + var riff = TestBuilders.Wav.CreateMinimal ().ToList (); + var tag = BombTag (); + riff.AddRange (Chunk ("id3 ", tag, bigEndian: false)); + var size = riff.Count - 8; + riff[4] = (byte)size; riff[5] = (byte)(size >> 8); riff[6] = (byte)(size >> 16); riff[7] = (byte)(size >> 24); + for (var i = 0; i < trailing; i++) + riff.AddRange (Chunk ("id3 ", tag, bigEndian: false)); + return [.. riff]; + } + + public static IEnumerable ManyTagFiles => [ + ["AIFF ID3 chunks in the form", ".aif", (Func)(n => Aiff (n, 0))], + ["AIFF tag chunks after the form", ".aif", (Func)(n => Aiff (1, n))], + ["WAV tag chunks after the RIFF", ".wav", (Func)Wav], + ]; + + // One budget per file read, shared by every tag chunk it parses (#275): N and 4N chunks whose tags each declare + // 16 MiB, read from data and from a path, differ by at most the budget, not by 3N tags' worth. + [TestMethod] + [DynamicData (nameof (ManyTagFiles))] + public void Read_FileWithManyTagChunks_InflatesWithinOneBudget (string name, string extension, Func build) + { + var n = build (4); + var fourN = build (16); + var files = new TagLibSharp2.Tests.Core.MockFileSystem (); + files.AddFile ("/n" + extension, n); + files.AddFile ("/4n" + extension, fourN); + MediaFile.ReadFromData (n, "n" + extension); + + var nData = Bounds.LeastAllocated (() => MediaFile.ReadFromData (n, "n" + extension)); + var fourNData = Bounds.LeastAllocated (() => MediaFile.ReadFromData (fourN, "4n" + extension)); + var nPath = Bounds.LeastAllocated (() => MediaFile.Read ("/n" + extension, files)); + var fourNPath = Bounds.LeastAllocated (() => MediaFile.Read ("/4n" + extension, files)); + + Assert.IsLessThan ((long)InflateBudget.PerTag, fourNData - nData, $"{name}, data: N {nData} bytes, 4N {fourNData} bytes"); + Assert.IsLessThan ((long)InflateBudget.PerTag, fourNPath - nPath, $"{name}, path: N {nPath} bytes, 4N {fourNPath} bytes"); + } + + // A legitimate tag with a few large compressed frames reads whole within the 64 MiB budget, whatever their order. + [TestMethod] + [DataRow ((byte)3)] + [DataRow ((byte)4)] + public void Read_FewLargeCompressedFrames_ReadWhole (byte version) + { + byte[] Big (int size) => [0, .. "eng"u8, 0, .. Enumerable.Repeat ((byte)'c', size)]; + byte[] Pack (byte[] content) => version == 4 + ? [(byte)((content.Length >> 21) & 0x7F), (byte)((content.Length >> 14) & 0x7F), (byte)((content.Length >> 7) & 0x7F), (byte)(content.Length & 0x7F), .. Deflate (content)] + : Compressed (content); + byte flags = version == 4 ? (byte)0x09 : (byte)0x80; + byte[] F (string id, byte[] content) + { + var frame = TestBuilders.Id3v2.CreateFrame (id, Pack (content), version); + frame[9] = flags; + return frame; + } + byte[] T (byte[] frames) => [.. TestBuilders.Id3v2.CreateHeader (version, (uint)frames.Length), .. frames]; + byte[] Picture (byte kind) => [0, .. "image/png"u8, 0, kind, 0, .. Enumerable.Repeat ((byte)'p', 10 * MiB)]; + + var commentFirst = Id3v2Tag.Read (T ([.. F ("COMM", Big (16 * MiB - 10)), .. F ("TIT2", [0, .. "Song"u8])])).Tag!; + var twoLarge = Id3v2Tag.Read (T ([.. F ("TXXX", [0, .. "d"u8, 0, .. Enumerable.Repeat ((byte)'x', 9 * MiB)]), + .. F ("COMM", Big (9 * MiB)), .. F ("TIT2", [0, .. "Song"u8])])).Tag!; + var pictures = Id3v2Tag.Read (T ([.. F ("APIC", Picture (3)), .. F ("APIC", Picture (4))])).Tag!; + + Assert.AreEqual ("Song", commentFirst.Title, "16 MiB comment, then the title"); + Assert.AreEqual (16 * MiB - 10, commentFirst.Comment?.Length); + Assert.AreEqual ("Song", twoLarge.Title, "9 MiB TXXX, 9 MiB comment, then the title"); + Assert.AreEqual (9 * MiB, twoLarge.Comment?.Length); + Assert.HasCount (2, pictures.Pictures, "two 10 MiB pictures"); + } + + // Past 64 MiB in all, the later compressed frames are kept as stored and written back byte for byte. + [TestMethod] + public void ReadAndSave_CompressedFramesPastTheBudget_KeepTheRestAsStored () + { + var frames = new List (); + var bodies = new List (); + for (var i = 0; i < 5; i++) { + var body = Compressed ([0, .. System.Text.Encoding.ASCII.GetBytes ("d" + i), 0, .. Enumerable.Repeat ((byte)'v', 16 * MiB - 16)]); + bodies.Add (body); + frames.AddRange (Frame ("TXXX", body, 0x80)); + } + + var tag = Id3v2Tag.Read (Tag ([.. frames])).Tag!; + var written = Id3v2WrittenEncodingTests.WrittenFrames (tag.Render ().ToArray ()).Where (f => f.Id == "TXXX").ToList (); + + Assert.HasCount (4, tag.UserTextFrames, "four frames fit the budget"); + Assert.HasCount (5, written); + CollectionAssert.AreEqual (bodies[4], written[4].Body, "the fifth is written as stored"); + } + + // The v2.3 encoding peek charges a compressed embedded frame once; its conversion takes nothing more, so 12 frames of + // 1 MiB, 12 MiB in all, are all re-encoded within the 16 MiB save budget (charged twice, 7 would be). + [TestMethod] + public void Render_EmbeddedFramesPeekedAndConverted_AreChargedOnce () + { + var tag = Id3v2Tag.Read (Embedded (12, MiB, "TIT3")).Tag!; + + var written = Id3v2WrittenEncodingTests.WrittenFrames (tag.Render ().ToArray ()).Where (f => f.Id == "TIT3").ToList (); + + Assert.HasCount (12, written); + // Re-encoded: uncompressed, encoding 0 and the text; one kept as stored would be its small compressed body. + Assert.AreEqual (12, written.Count (f => f.Body.Length == 1 + MiB && f.Body[0] == 0), "frames re-encoded in ISO-8859-1"); + } + + // The save's size check renders the tag only when a bound on its size could pass the limit (#275): the check itself + // allocates next to nothing for a tag with a 10 MB cover, and a save allocates one render of the tag and the copy of + // the audio, as main does, not a second render. + [TestMethod] + [DataRow ((byte)3)] + [DataRow ((byte)4)] + public void Save_LargeCover_DoesNotRenderTheTagTwice (byte version) + { + var cover = new byte[10 * MiB]; + cover[0] = 0xFF; cover[1] = 0xD8; + var tag = new Id3v2Tag ((Id3v2Version)version); + tag.AddPicture (new TagLibSharp2.Id3.Id3v2.Frames.PictureFrame ("image/jpeg", PictureType.FrontCover, "", cover)); + var directory = Directory.CreateTempSubdirectory ("tls2-275-"); + try { + var path = Path.Combine (directory.FullName, "in.mp3"); + File.WriteAllBytes (path, [.. tag.Render ().ToArray (), .. new byte[4096]]); + var file = Mp3File.ReadFromFile (path).File!; + file.Title = "warm"; + Assert.IsTrue (file.SaveToFile (Path.Combine (directory.FullName, "warm.mp3")).IsSuccess); + file.Title = "edited"; + var render = Bounds.LeastAllocated (() => file.Id3v2Tag!.Render ()); + + var check = Bounds.LeastAllocated (() => Assert.IsNull (Id3v2Tag.SizeRefusal (file.Id3v2Tag))); + var save = Bounds.LeastAllocated (() => Assert.IsTrue (file.SaveToFile (Path.Combine (directory.FullName, "out.mp3")).IsSuccess)); + + Assert.IsLessThan (64 * 1024, check, $"the size check allocated {check} bytes"); + Assert.IsLessThan (render + 2 * MiB, save, $"render {render} bytes, save {save} bytes"); + } finally { + directory.Delete (recursive: true); + } + } + + const int Large = 100_000; + // Wide text: three UTF-8 bytes a character, and nine in a URL's percent-encoding (#266). + static readonly string LongText = new ('\u65E5', Large); + + /// Each kind of frame the save's size bound counts, holding about bytes or characters. + public static IEnumerable LargeFrames => new (string Name, Action Add)[] { + ("text frame", t => t.Title = LongText), + ("picture", t => t.AddPicture (new TagLibSharp2.Id3.Id3v2.Frames.PictureFrame ("image/jpeg", PictureType.FrontCover, "", new byte[Large]))), + ("picture description", t => t.AddPicture (new TagLibSharp2.Id3.Id3v2.Frames.PictureFrame ("image/jpeg", PictureType.FrontCover, LongText, new byte[1]))), + ("comment", t => t.Comment = LongText), + ("comment description", t => t.AddComment (new TagLibSharp2.Id3.Id3v2.Frames.CommentFrame ("c", "eng", LongText))), + ("lyrics", t => t.Lyrics = LongText), + ("lyrics description", t => t.AddLyrics (new TagLibSharp2.Id3.Id3v2.Frames.LyricsFrame ("l", "eng", LongText))), + ("user text", t => t.SetUserText ("d", LongText)), + ("user text description", t => t.SetUserText (LongText, "v")), + ("unique file ID owner", t => t.AddUniqueFileId (new TagLibSharp2.Id3.Id3v2.Frames.UniqueFileIdFrame (LongText, [1]))), + ("involved people", t => { var f = new TagLibSharp2.Id3.Id3v2.Frames.InvolvedPeopleFrame (TagLibSharp2.Id3.Id3v2.Frames.InvolvedPeopleFrameType.InvolvedPeople); f.Add (LongText, "p"); t.AddInvolvedPeopleFrame (f); }), + ("involved person", t => { var f = new TagLibSharp2.Id3.Id3v2.Frames.InvolvedPeopleFrame (TagLibSharp2.Id3.Id3v2.Frames.InvolvedPeopleFrameType.InvolvedPeople); f.Add ("r", LongText); t.AddInvolvedPeopleFrame (f); }), + ("rating email", t => t.SetPopularimeter (LongText, 5)), + ("URL", t => t.SetUrl ("WOAR", LongText)), + ("user URL", t => t.SetUserUrl ("d", LongText)), + ("user URL description", t => t.SetUserUrl (LongText, "http://a/")), + ("synchronised lyrics description", t => t.AddSyncLyrics (new TagLibSharp2.Id3.Id3v2.Frames.SyncLyricsFrame { Description = LongText })), + ("synchronised lyrics item", t => { var f = new TagLibSharp2.Id3.Id3v2.Frames.SyncLyricsFrame (); f.AddSyncItem (LongText, 1); t.AddSyncLyrics (f); }), + ("object", t => t.AddGeneralObject (new TagLibSharp2.Id3.Id3v2.Frames.GeneralObjectFrame ("x/y", "f", "d", new BinaryData (new byte[Large])))), + ("object file name", t => t.AddGeneralObject (new TagLibSharp2.Id3.Id3v2.Frames.GeneralObjectFrame ("x/y", LongText, "d", new BinaryData ([1])))), + ("object description", t => t.AddGeneralObject (new TagLibSharp2.Id3.Id3v2.Frames.GeneralObjectFrame ("x/y", "f", LongText, new BinaryData ([1])))), + ("private data", t => t.AddPrivateFrame (new TagLibSharp2.Id3.Id3v2.Frames.PrivateFrame ("o", new BinaryData (new byte[Large])))), + ("private owner", t => t.AddPrivateFrame (new TagLibSharp2.Id3.Id3v2.Frames.PrivateFrame (LongText, new BinaryData ([1])))), + ("chapter title", t => t.AddChapter (new TagLibSharp2.Id3.Id3v2.Frames.ChapterFrame ("c", 0, 1) { Title = LongText })), + ("chapter element ID", t => t.AddChapter (new TagLibSharp2.Id3.Id3v2.Frames.ChapterFrame (LongText, 0, 1))), + ("contents title", t => t.AddTableOfContents (new TagLibSharp2.Id3.Id3v2.Frames.TableOfContentsFrame ("t") { Title = LongText })), + ("contents element ID", t => t.AddTableOfContents (new TagLibSharp2.Id3.Id3v2.Frames.TableOfContentsFrame (LongText))), + ("contents child", t => { var f = new TagLibSharp2.Id3.Id3v2.Frames.TableOfContentsFrame ("t"); f.AddChildElement (LongText); t.AddTableOfContents (f); }), + }.Select (r => new object[] { r.Name, r.Add }); + + // The save's size bound counts every kind of frame: it is at least what a tag holding one large frame of the kind + // renders to, and with the limit below that the check refuses the tag, where a bound that left the frame out would + // let the save throw (#275). With a CHAP or CTOC the bound also holds the inflation budget its re-encoding may add. + [TestMethod] + [DynamicData (nameof (LargeFrames))] + public void SizeRefusal_LargeFrameOfEachKind_IsRefusedBelowItsSize (string name, Action add) + { + var tag = new Id3v2Tag (Id3v2Version.V24); + add (tag); + var chapters = tag.ChapterFrames.Count + tag.TableOfContentsFrames.Count > 0; + var rendered = tag.Render ().Length; + Assert.IsGreaterThan (Large / 2, rendered, name); + + Assert.IsGreaterThanOrEqualTo ((long)rendered + (chapters ? InflateBudget.PerSave : 0), tag.SizeBound (), name + ": the bound"); + if (chapters) + return; + using (Id3v2TagTooLargeException.LowerLimit (rendered - Id3v2Header.HeaderSize - 1)) + Assert.IsNotNull (Id3v2Tag.SizeRefusal (tag), name); + } + + // An unread frame, kept as stored, counts too. + [TestMethod] + public void SizeRefusal_LargeUnreadFrame_IsRefusedBelowItsSize () + { + var tag = Id3v2Tag.Read (Tag (Frame ("ZZZZ", new byte[Large]))).Tag!; + var rendered = tag.Render ().Length; + + using (Id3v2TagTooLargeException.LowerLimit (rendered - Id3v2Header.HeaderSize - 1)) + Assert.IsNotNull (Id3v2Tag.SizeRefusal (tag)); + } + + // A CHAP embedding a large UTF-8 frame that a v2.3 save re-encodes in UTF-16, twice its size (#275 review 7): the + // save's size bound counts what the re-encode can write, so with the limit between the stored and the re-encoded + // size the save fails with a result, and does not throw. + [TestMethod] + public void Save_ChapterEmbeddingLargeUtf8Frame_BoundsTheReEncodeAndFails () + { + var stored = 80 * MiB; + byte[] text = [3, .. Enumerable.Repeat ((byte)'a', stored - 4), 0xE6, 0x97, 0xA5]; + byte[] chap = [.. "ch1"u8, 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, .. Frame ("TIT3", text)]; + byte[] mp3 = [.. Tag (Frame ("CHAP", chap)), .. new byte[256]]; + var files = new TagLibSharp2.Tests.Core.MockFileSystem (); + files.AddFile ("/in.mp3", mp3); + var file = Mp3File.ReadFromFile ("/in.mp3", files).File!; + file.Title = "edited"; + var rendered = file.Id3v2Tag!.Render ().Length; + Assert.IsGreaterThan (2L * stored - MiB, rendered, "the re-encode doubles the frame"); + + Assert.IsGreaterThanOrEqualTo ((long)rendered, file.Id3v2Tag.SizeBound (), "the bound"); + FileWriteResult result; + using (Id3v2TagTooLargeException.LowerLimit (150L * MiB)) + result = file.SaveToFile ("/out.mp3", files); + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error!, $"({150L * MiB})", "the message quotes the limit in force"); + Assert.IsFalse (files.FileExists ("/out.mp3")); + } + + // An AIFF keeps the last ID3 chunk that reads. The chunks it supersedes are read without inflating anything, so the + // one kept is decoded with the whole budget however many came before (#275 review 7). + [TestMethod] + public void Read_AiffWithManyId3Chunks_DecodesTheKeptOneWithTheBudget () + { + var aiff = Aiff (40, 0); + var files = new TagLibSharp2.Tests.Core.MockFileSystem (); + files.AddFile ("/f.aif", aiff); + + var fromData = (TagLibSharp2.Aiff.AiffFile)MediaFile.ReadFromData (aiff, "f.aif").File!; + var fromPath = (TagLibSharp2.Aiff.AiffFile)MediaFile.Read ("/f.aif", files).File!; + + Assert.AreEqual (16 * MiB - 1, fromData.Id3v2Tag!.Title?.Length, "data"); + Assert.AreEqual (16 * MiB - 1, fromPath.Id3v2Tag!.Title?.Length, "path"); + } + + /// A v2.4 tag of compressed TXXX frames of , with a footer when appended. + static byte[] V24Tag (int count, int size, bool footer) + { + var frames = new List (); + for (var i = 0; i < count; i++) { + byte[] content = [0, .. System.Text.Encoding.ASCII.GetBytes ("d" + i), 0, .. Enumerable.Repeat ((byte)'a', size)]; + byte[] body = [(byte)((content.Length >> 21) & 0x7F), (byte)((content.Length >> 14) & 0x7F), (byte)((content.Length >> 7) & 0x7F), (byte)(content.Length & 0x7F), .. Deflate (content)]; + var frame = TestBuilders.Id3v2.CreateFrame ("TXXX", body, 4); + frame[9] = 0x09; + frames.AddRange (frame); + } + var length = frames.Count; + byte[] size4 = [(byte)((length >> 21) & 0x7F), (byte)((length >> 14) & 0x7F), (byte)((length >> 7) & 0x7F), (byte)(length & 0x7F)]; + byte flags = footer ? (byte)0x10 : (byte)0; + byte[] header = [.. "ID3"u8, 4, 0, flags, .. size4]; + return footer ? [.. header, .. frames, .. "3DI"u8, 4, 0, flags, .. size4] : [.. header, .. frames]; + } + + // An MPEG program stream's front tag and appended tag share one read's budget (#275 review 7): a front tag that fills + // it leaves the appended tag's compressed frames undecoded, so adding them costs less than one budget more. + [TestMethod] + public void Read_MpegPsFrontAndAppendedTags_ShareOneBudget () + { + var stream = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.ProgramStream (new TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Audio.None }); + var front = V24Tag (4, 16 * MiB - 16, footer: false); + byte[] small = [.. front, .. stream, .. V24Tag (1, 16, footer: true)]; + byte[] large = [.. front, .. stream, .. V24Tag (4, 16 * MiB - 16, footer: true)]; + Assert.IsTrue (TagLibSharp2.Mpeg.MpegPsFile.Read (large).IsSuccess); + + var smallBytes = Bounds.LeastAllocated (() => TagLibSharp2.Mpeg.MpegPsFile.Read (small)); + var largeBytes = Bounds.LeastAllocated (() => TagLibSharp2.Mpeg.MpegPsFile.Read (large)); + + Assert.IsLessThan ((long)InflateBudget.PerTag, largeBytes - smallBytes, $"small {smallBytes} bytes, large {largeBytes} bytes"); + } + + // With the limit lowered, the failure names the limit in force. + [TestMethod] + public void Render_TagPastLoweredLimit_QuotesTheLimit () + { + var tag = new Id3v2Tag (Id3v2Version.V24) { Title = new string ('x', 3000) }; + + using (Id3v2TagTooLargeException.LowerLimit (2000)) { + var error = Assert.ThrowsExactly (() => tag.Render ()); + StringAssert.Contains (error.Message, "(2000)"); + } + } + + // The bound's CTOC term counts its embedded frames four times over, as the CHAP term does: a CTOC embedding an 80 MiB + // UTF-8 frame that a v2.3 render writes in UTF-16 is bounded (#275 review 8). + [TestMethod] + public void SizeBound_ContentsEmbeddingLargeUtf8Frame_CoversTheReEncode () + { + var stored = 80 * MiB; + byte[] text = [3, .. Enumerable.Repeat ((byte)'a', stored - 4), 0xE6, 0x97, 0xA5]; + byte[] ctoc = [.. "toc"u8, 0, 0x03, 1, .. "ch1"u8, 0, .. Frame ("TIT3", text)]; + var tag = Id3v2Tag.Read (Tag (Frame ("CTOC", ctoc))).Tag!; + + var rendered = tag.Render ().Length; + + Assert.IsGreaterThan (2L * stored - MiB, rendered, "the re-encode doubles the frame"); + Assert.IsGreaterThanOrEqualTo ((long)rendered, tag.SizeBound ()); + } + + // A compressed embedded frame inflates within the 16 MiB save budget and is then re-encoded, up to four times over: a + // CHAP whose compressed UTF-8 frame declares 16 MiB renders to about 32 MiB in UTF-16, and the bound covers it with + // the 4 × 16 MiB allowance, as the frame's few stored bytes alone could not (#275 review 8). + [TestMethod] + public void SizeBound_CompressedEmbeddedFrame_CoversTheInflatedReEncode () + { + byte[] text = [3, .. Enumerable.Repeat ((byte)'a', 16 * MiB - 4), 0xE6, 0x97, 0xA5]; + byte[] chap = [.. "ch1"u8, 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, .. Frame ("TIT3", Compressed (text), 0x80)]; + var tag = Id3v2Tag.Read (Tag (Frame ("CHAP", chap))).Tag!; + + var rendered = tag.Render ().Length; + + Assert.IsGreaterThan (31L * MiB, rendered, "inflated and written in UTF-16"); + Assert.IsGreaterThanOrEqualTo ((long)rendered, tag.SizeBound ()); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2SaveSizeGuardTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2SaveSizeGuardTests.cs new file mode 100644 index 00000000..3408dd38 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2SaveSizeGuardTests.cs @@ -0,0 +1,239 @@ +// 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.IO.Compression; + +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Id3.Id3v2; + +/// +/// No save throws on an ID3v2 size (#275). Some saves render the tag as it was read to see whether the caller changed it +/// (MPEG-PS, AVI, WAV and AIFF), and a tag as read can render larger than it is stored: v2.3 text in UTF-8 is written in +/// UTF-16, and a compressed frame is written inflated. With the size limit lowered below that re-render, and the +/// caller's tag made small, every save of every carrier returns a result and never throws: a save whose own tag fits +/// succeeds, one whose tag does not fails and writes nothing. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Id3")] +[TestCategory ("Id3v2")] +public class Id3v2SaveSizeGuardTests +{ + static readonly string Text = new string ('a', 3000) + "日"; + + static byte[] Frame (string id, byte[] body, byte version, byte format = 0) + { + var frame = TestBuilders.Id3v2.CreateFrame (id, body, version); + frame[9] = format; + return frame; + } + + static byte[] Deflate (byte[] data) + { + using var output = new MemoryStream (); + using (var zlib = new ZLibStream (output, CompressionLevel.Optimal)) + zlib.Write (data); + return output.ToArray (); + } + + /// Tags that re-render larger than they are stored. + static byte[] OriginalTag (string kind) + { + var utf8 = System.Text.Encoding.UTF8.GetBytes (Text); + var (version, frames) = kind switch { + "utf8-title" => ((byte)3, Frame ("TIT2", [3, .. utf8], 3)), + "utf8-comment" => ((byte)3, Frame ("COMM", [3, .. "eng"u8, 0, .. utf8], 3)), + "embedded-utf8-subtitle" => ((byte)3, Frame ("CHAP", [.. "ch1"u8, 0, 0, 0, 0, 0, 0, 0, 0x03, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, .. Frame ("TIT3", [3, .. utf8], 3)], 3)), + _ => ((byte)4, Frame ("TIT2", [0, 0, 0x17, 0x38, .. Deflate ([0, .. System.Text.Encoding.ASCII.GetBytes (new string ('a', 2999))])], 4, 0x09)), + }; + return [.. TestBuilders.Id3v2.CreateHeader (version, (uint)frames.Length), .. frames]; + } + + static readonly string[] Kinds = ["utf8-title", "utf8-comment", "embedded-utf8-subtitle", "compressed-v24-title"]; + static readonly string[] Edits = ["title", "clear", "assign"]; + + static readonly bool[] NoTrail = [false]; + static readonly bool[] Trails = [false, true]; + + // WAV and AIFF also run with a tag chunk after the form, so the save compares the tag it writes with the tag as + // read to decide whether that chunk is superseded (TagRewritten). + public static IEnumerable Rows => + from format in Id3v22CarrierBuilder.Formats + from trailing in format.Format is "wav" or "aiff" ? Trails : NoTrail + from kind in Kinds + from edit in Edits + from save in Id3v2WrittenEncodingCarrierTests.Saves + where Id3v2WrittenEncodingCarrierTests.HasSave (format.Format, save) + select new object[] { format.Format, format.Extension, trailing, kind, edit, save }; + + /// A small tag in a chunk after the form: "id3 " with a little-endian size in WAV, "ID3 " big-endian in AIFF. + static byte[] TrailingChunk (string format) + { + byte[] tag = [.. TestBuilders.Id3v2.CreateHeader (3, 15), .. Frame ("TIT2", [0, .. "tail"u8], 3)]; + var size = tag.Length; + byte[] header = format == "wav" + ? [.. "id3 "u8, (byte)size, (byte)(size >> 8), (byte)(size >> 16), (byte)(size >> 24)] + : [.. "ID3 "u8, (byte)(size >> 24), (byte)(size >> 16), (byte)(size >> 8), (byte)size]; + return (size & 1) == 1 ? [.. header, .. tag, 0] : [.. header, .. tag]; + } + + [TestMethod] + [DynamicData (nameof (Rows))] + public async Task Save_TagAsReadRendersPastTheLimit_ReturnsAResultAndNeverThrows (string format, string extension, bool trailing, string kind, string edit, string save) + { + var tag = OriginalTag (kind); + // The compressed v2.4 TIT2 declares 3000 bytes (syncsafe 0x17 0x38): 1 + 2999. + var reRendered = Id3v2Tag.Read (tag).Tag!.Render (0).Length; + var original = Id3v22CarrierBuilder.Build (format, tag); + if (trailing) + original = [.. original, .. TrailingChunk (format)]; + var files = new MockFileSystem (); + var name = "/file" + extension; + files.AddFile (name, original); + var read = save == "render" ? MediaFile.ReadFromData (original, name) : MediaFile.Read (name, files); + Assert.IsTrue (read.IsSuccess, read.Error); + var file = (IMediaFile)read.File!; + var id3 = Id3v22CarrierBuilder.Id3 (file)!; + switch (edit) { + case "title": + id3.Title = "x"; + break; + case "clear": + id3.Clear (); + break; + default: + file.GetType ().GetProperty ("Id3v2Tag")!.SetValue (file, new Id3v2Tag (Id3v2Version.V24) { Title = "x" }); + break; + } + + // Below the tag as read, rendered again, and above the caller's small tag. + using var lowered = Id3v2TagTooLargeException.LowerLimit (reRendered - Id3v2Header.HeaderSize - 1); + if (save == "render") { + // A render cannot return a failure: it may throw the documented InvalidOperationException, and nothing else. + try { + SkipPicturesFixtures.Render (file, original); + } catch (Exception error) { + var thrown = error is System.Reflection.TargetInvocationException { InnerException: { } inner } ? inner : error; + Assert.IsInstanceOfType (thrown); + StringAssert.Contains (thrown.Message, "more than an ID3v2 size can hold"); + } + return; + } + + // The caller's tag decides: one that fits saves, whatever the tag as read renders to; one that does not fails. + var current = Id3v22CarrierBuilder.Id3 (file); + var fits = current is null || current.TryRender () is not null; + + var result = await Id3v2WrittenEncodingCarrierTests.SaveResultAsync (file, original, files, name, save); + + Assert.AreEqual (fits, result.IsSuccess, result.Error); + if (!result.IsSuccess) { + StringAssert.Contains (result.Error!, "more than an ID3v2 size can hold"); + CollectionAssert.AreEqual (original, files.ReadAllBytes (name), "a failed save leaves the source as it was"); + Assert.IsFalse (files.FileExists ("/out"), "a failed save writes nothing"); + } + } + + /// A v2.4 tag with a footer, as appended to an MPEG program stream, holding a compressed TIT2 of 3000 bytes. + static byte[] AppendedCompressedTag () + { + var frame = Frame ("TIT2", [0, 0, 0x17, 0x38, .. Deflate ([0, .. System.Text.Encoding.ASCII.GetBytes (new string ('a', 2999))])], 4, 0x09); + var size = frame.Length; + byte[] size4 = [(byte)((size >> 21) & 0x7F), (byte)((size >> 14) & 0x7F), (byte)((size >> 7) & 0x7F), (byte)(size & 0x7F)]; + return [.. "ID3"u8, 4, 0, 0x10, .. size4, .. frame, .. "3DI"u8, 4, 0, 0x10, .. size4]; + } + + public static IEnumerable MpegPsSaves => + from save in Id3v2WrittenEncodingCarrierTests.Saves + where save != "render" + select new object[] { save }; + + // An MPEG program stream with a front tag and an appended tag compares the appended tag it writes with the one it + // read (TryRenderForEnd). With the limit below the appended tag as read, re-rendered, a save that makes the tag small + // saves (#275 review 9). + [TestMethod] + [DynamicData (nameof (MpegPsSaves))] + public async Task Save_MpegPsAppendedTagAsReadPastTheLimit_SavesASmallerTag (string save) + { + var appended = AppendedCompressedTag (); + var reRendered = Id3v2Tag.Read (appended).Tag!.Render (0, withFooter: true).Length; + var stream = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.ProgramStream (new TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Audio.None }); + byte[] front = new Id3v2Tag (Id3v2Version.V24) { Album = "front" }.Render (0).ToArray (); + byte[] original = [.. front, .. stream, .. appended]; + var files = new MockFileSystem (); + files.AddFile ("/file.mpg", original); + var file = (IMediaFile)MediaFile.Read ("/file.mpg", files).File!; + Id3v22CarrierBuilder.Id3 (file)!.Title = "x"; + + FileWriteResult result; + using (Id3v2TagTooLargeException.LowerLimit (reRendered - 2 * Id3v2Header.HeaderSize - 1)) + result = await Id3v2WrittenEncodingCarrierTests.SaveResultAsync (file, original, files, "/file.mpg", save); + + Assert.IsTrue (result.IsSuccess, result.Error); + } + + // "mpg-update": an MPEG program stream whose tag is an appended update tag, rendered with no padding and a 7-byte + // extended header (RenderForEnd). + static readonly (string Format, string Extension, int Padding)[] PaddedCarriers = [("avi", ".avi", 0), ("mp3", ".mp3", 1024), ("mpg-update", ".mpg", 7)]; + static readonly string[] BoundarySaves = ["path", "in-place"]; + static readonly bool[] Below = [false, true]; + + public static IEnumerable BoundaryRows => + from format in PaddedCarriers + from save in BoundarySaves + from below in Below + select new object[] { format.Format, format.Extension, format.Padding, save, below }; + + // The save's size check refuses exactly the tags the carrier's own render would: AVI renders with no padding, MP3 + // with the default 1 KiB, and an MPEG-PS appended update tag with none and a 7-byte extended header. At a limit equal + // to the carrier's render the save succeeds; one byte below, it fails (#275 reviews 9 and 10). + [TestMethod] + [DynamicData (nameof (BoundaryRows))] + public async Task Save_TagAtTheLimit_IsRefusedExactlyWhenTheCarriersRenderIs (string format, string extension, int padding, string save, bool below) + { + var update = format == "mpg-update"; + byte[] original = update + ? [.. new Id3v2Tag (Id3v2Version.V24) { Album = "front" }.Render (0).ToArray (), + .. TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.ProgramStream (new TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Options { VideoFrames = 1, AudioFrames = 0, AudioKind = TagLibSharp2.Tests.Mpeg.MpegPsTestBuilder.Audio.None }), + .. TagLibSharp2.Tests.Mpeg.MpegPsAppendedTagTests.UpdateTag ("u")] + : Id3v22CarrierBuilder.Build (format, [.. TestBuilders.Id3v2.CreateHeader (3, 16), .. new byte[16]]); + var files = new MockFileSystem (); + var name = "/file" + extension; + files.AddFile (name, original); + var file = (IMediaFile)MediaFile.Read (name, files).File!; + var id3 = Id3v22CarrierBuilder.Id3 (file)!; + id3.Title = new string ('t', 3000); + // An update tag's size counts its body and the extended header; the others', their body and padding. + var size = update + ? id3.Render (0, withFooter: true).Length - 2 * Id3v2Header.HeaderSize + padding + : id3.Render (padding, withFooter: false).Length - Id3v2Header.HeaderSize; + + FileWriteResult result; + FileWriteResult? gate; + var spanRenderThrew = false; + using (Id3v2TagTooLargeException.LowerLimit (below ? size - 1 : size)) { + // The save's own gate, before anything is rendered: it refuses exactly where the carrier's render would. + gate = PictureSkip.Refuse (file, id3, file switch { + TagLibSharp2.Mpeg.MpegPsFile mpg => mpg.Id3PaddingSize, + TagLibSharp2.Riff.AviFile => TagLibSharp2.Riff.AviRewrite.Id3PaddingSize, + _ => Id3v2Tag.DefaultPaddingSize, + }); + // A render of the bytes has no gate: the carrier's render itself refuses, with the documented exception. + try { + SkipPicturesFixtures.Render (file, original); + } catch (Exception error) { + var thrown = error is System.Reflection.TargetInvocationException { InnerException: { } inner } ? inner : error; + Assert.IsInstanceOfType (thrown); + spanRenderThrew = true; + } + result = await Id3v2WrittenEncodingCarrierTests.SaveResultAsync (file, original, files, name, save); + } + + Assert.AreEqual (below, gate is not null, "the gate"); + Assert.AreEqual (below, spanRenderThrew, "the carrier's render"); + Assert.AreEqual (!below, result.IsSuccess, result.Error); + } +} diff --git a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs index 1e482be1..e09778e4 100644 --- a/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs +++ b/tests/TagLibSharp2.Tests/Id3/Id3v2/Id3v2WrittenEncodingCarrierTests.cs @@ -97,6 +97,17 @@ static async Task SaveAsync (IMediaFile file, byte[] original, MockFileS if (save == "render") return SkipPicturesFixtures.Render (file, original)!; + var result = await SaveResultAsync (file, original, files, name, save); + Assert.IsTrue (result.IsSuccess, result.Error); + return files.ReadAllBytes (save.EndsWith ("in-place", StringComparison.Ordinal) ? name : "/out"); + } + + /// + /// The result of saving through , any entry but the span render: to + /// "/out", or over in place. + /// + internal static async Task SaveResultAsync (IMediaFile file, byte[] original, MockFileSystem files, string name, string save) + { var type = file.GetType (); var result = save switch { "path-with-data" => file switch { @@ -127,8 +138,7 @@ static async Task SaveAsync (IMediaFile file, byte[] original, MockFileS ? (FileWriteResult)inPlace.Invoke (file, [files])! : (FileWriteResult)type.GetMethod ("SaveToFile", [typeof (string), typeof (IFileSystem)])!.Invoke (file, [name, files])!, }; - Assert.IsTrue (result.IsSuccess, result.Error); - return files.ReadAllBytes (save.EndsWith ("in-place", StringComparison.Ordinal) ? name : "/out"); + return result; } /// The ID3v2.3 or ID3v2.4 tag in a saved carrier.