diff --git a/CHANGELOG.md b/CHANGELOG.md index 722c56aa..938c3575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A save of a Monkey's Audio, WavPack or Musepack file no longer drops the APEv2 tag's 32-byte header and clears the footer's "has header" flag (#217). The tag read from the file is written back the way it was read: with a header when it had one, footer-only when it had none, so a save with no edit keeps the tag's layout and the file's size. Any other tag, a new one or one parsed elsewhere and assigned, gets the format's layout, as before: footer-only in these formats, a header in raw AAC. `ApeTag.Render ()` writes a parsed tag with the header it was read with, and a new one without; `RenderWithOptions` is unchanged. Items are still written in order of size, as before. +- An APEv2 footer that claims a header (bit 31) with no `APETAGEX` in front of its items reads the same from a path or stream as from bytes (#240). The stream tag read of Monkey's Audio, WavPack and Musepack and the MPEG-PS trailer search took the claim at its word: a small Musepack file read no tag from a path, a small Monkey's Audio file read a bitrate of 0, and an MPEG-PS file did not find an ID3v2 tag appended before such an APE tag. Every reader now counts a header only when those bytes are there, as the bytes read already did. +- A path save of a Monkey's Audio, WavPack or Musepack file whose APEv2 tag is followed by Lyrics3 v2 and ID3v1 no longer keeps the old tag in front of the new one (#241). When the first read from the end held LYRICSBEGIN but only part of the APE footer in front of it, the save did not read further, kept the old tag as audio and grew the file by its size. It now reads the footer, and writes what `Render` writes. +- A path or stream read of a Monkey's Audio, WavPack or Musepack file with no APEv2 tag at its end no longer returns a tag that sits at the end of the header bytes it reads (#242). Those reads parse the header bytes joined to the tag read from the end; with no tag there, a footer and items at the end of the header bytes became the file's tag, and a save wrote it at the end of the file. A tag now counts only when it starts in the part read from the end, so these reads find a tag only where a read from bytes does. - A save no longer drops the ID3v2 frames this library does not read, such as `PCNT`, `MCDI`, `RVAD`, `ETCO`, `USER`, `COMR` and experimental frames (#207). Each is written back as it was stored, flags and any compressed, encrypted or unsynchronised body included, when the tag is saved in the version it was read in; a frame from an ID3v2.2 tag is written under its ID3v2.3 ID, except `LNK`, whose body differs. A frame of an ID this library reads that it cannot parse (a 1-byte `APIC`, a short `COMM` or `USLT`, a `POPM`, `UFID` or `PRIV` with no terminator, a truncated `CHAP` or `CTOC`, a `TALB` with an invalid encoding byte, a frame of size 0) is kept the same way, until a property sets or clears that ID, or a call removes every frame of it, as `Pictures = []` does; a rejected `COMM` or `USLT` goes with any write of `Comment` or `Lyrics`, and a rejected `TXXX` with a write or removal of the custom field its description names. A rejected ID3v2.2 `PIC` is not written as an `APIC`. Such frames make `IsEmpty` false, and `Clear` removes them - A Matroska file with bytes that are not an element inside its Segment, such as the 0x0A filler a live recording puts after an unknown Segment size (the Matroska test suite's `test4.mkv`), read no tracks from a path or a seekable stream, while `ReadFromData` and a non-seekable stream read its audio and video (#208). The path and stream read now skip such bytes as the read from memory does, one window at a time. A save refused a file with such bytes anywhere after the Segment's first element ("Matroska segment cannot be bounded"); every save now keeps them where they are, as the reads skip them, and a save with no edit writes the file back unchanged - MP3 audio in an MP4 `mp4a` sample entry (esds object type 0x6B or 0x69) is reported as `Mp4AudioCodec.Mp3` and codec "MP3", with its bit rate; it was reported as AAC (#206). The esds is found after a QuickTime sound description's version 1 or 2 fields too. Those object types hold MPEG audio of any layer, so the codec is named from the first frame's header, as MP3 files name it: Layer II in MP4 (`mp2.mp4`) is "MPEG-1 Layer II", where it read "MP3" and MediaInfo says Layer 2. QuickTime's `.mp3` sound entry (`mp3.mov`) had no codec; it is `Mp4AudioCodec.Mp3` and "MP3". Apple ProRes video (`apco`, `apcs`, `apcn`, `apch`, `ap4h`, `ap4x`) is named "ProRes" and H.263 (`s263`, `h263`) "H.263", where the fourcc was echoed diff --git a/src/TagLibSharp2/Aac/AacFile.cs b/src/TagLibSharp2/Aac/AacFile.cs index a1ef509a..d8c4736d 100644 --- a/src/TagLibSharp2/Aac/AacFile.cs +++ b/src/TagLibSharp2/Aac/AacFile.cs @@ -63,10 +63,10 @@ internal void MarkPicturesSkipped () // even when the tag's body did not parse. Render places the tail against it, as the read did. long _audioStart; - // The APEv2 tag that was read, when it had only a footer. Spec-valid, so a save keeps that layout - // for that tag. Every other tag, including one assigned in its place, is written with a header and - // a footer, as ffmpeg writes it; some readers (mediainfo) find the tag only through the header. - ApeTag? _footerOnlyApeTag; + // The APEv2 tag this file's read produced. A save writes it back with the header it had. Any other tag, a new + // one or one assigned in its place (parsed elsewhere or taken from another file), gets a header and a footer, + // as ffmpeg writes it; some readers (mediainfo) find the tag only through the header. + ApeTag? _readApeTag; AacFile () { @@ -250,8 +250,7 @@ static AacFileReadResult ReadSeekable (Stream stream, ReadOnlyMemory bytes void TakeTags (AacTail tail) { ApeTag = tail.ApeTag; - if (tail.ApeTag is not null && !tail.ApeHasHeader) - _footerOnlyApeTag = tail.ApeTag; + _readApeTag = tail.ApeTag; Id3v1Tag = tail.Id3v1Tag; } @@ -409,7 +408,7 @@ public BinaryData Render (ReadOnlySpan originalData) var audioEnd = Math.Max (tail.AudioEnd, audioStart); var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty; - var ape = ApeTag?.RenderWithOptions (includeHeader: !ReferenceEquals (ApeTag, _footerOnlyApeTag)) ?? BinaryData.Empty; + var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true); var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty; // Lyrics3 belongs in front of ID3v1 and goes when that tag goes. @@ -572,7 +571,7 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem, readTags: false); var audioEnd = Math.Max (tail.AudioEnd, audioStart); var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty; - var ape = ApeTag?.RenderWithOptions (includeHeader: !ReferenceEquals (ApeTag, _footerOnlyApeTag)) ?? BinaryData.Empty; + var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true); var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty; long lyricsStart = 0; long lyricsLength = 0; @@ -648,7 +647,7 @@ public void Dispose () Id3v2Tag = null; ApeTag = null; - _footerOnlyApeTag = null; + _readApeTag = null; Id3v1Tag = null; SourcePath = null; _sourceFileSystem = null; diff --git a/src/TagLibSharp2/Aac/AacTail.cs b/src/TagLibSharp2/Aac/AacTail.cs index 030bfda4..af7db747 100644 --- a/src/TagLibSharp2/Aac/AacTail.cs +++ b/src/TagLibSharp2/Aac/AacTail.cs @@ -112,14 +112,13 @@ internal readonly struct AacTail const int LyricsEndLength = 9; const int LyricsV1SearchLimit = 64 * 1024; - AacTail (long audioEnd, long apeStart, long lyricsStart, long id3v1Start, ApeTag? apeTag, bool apeHasHeader, Id3v1Tag? id3v1Tag) + AacTail (long audioEnd, long apeStart, long lyricsStart, long id3v1Start, ApeTag? apeTag, Id3v1Tag? id3v1Tag) { AudioEnd = audioEnd; ApeStart = apeStart; LyricsStart = lyricsStart; Id3v1Start = id3v1Start; ApeTag = apeTag; - ApeHasHeader = apeHasHeader; Id3v1Tag = id3v1Tag; } @@ -138,9 +137,6 @@ internal readonly struct AacTail /// Gets the trailing APEv2 tag when it was asked for and parsed, or null. public ApeTag? ApeTag { get; } - /// Gets a value indicating whether the APEv2 tag had a header in front of its items. - public bool ApeHasHeader { get; } - /// Gets the ID3v1 tag, or null. public Id3v1Tag? Id3v1Tag { get; } @@ -161,14 +157,14 @@ public static AacTail Locate (AacTailSource source, long audioStart, bool readTa { var length = source.Length; if (!HasMarker (source)) - return new AacTail (length, -1, -1, -1, null, false, null); + return new AacTail (length, -1, -1, -1, null, null); var scratch = new byte[ApeTagItem.MeasureWindow]; // An APEv2 footer that ends the file decides first: nothing follows it, so "TAG" 128 bytes before the end // is inside the APE tag, not an ID3v1 tag (https://id3.org/ID3v1: ID3v1 is the last 128 bytes). - if (TryApe (source, length, audioStart, readTags, skipPictures, scratch, out var eofApe, out var eofHeader, out var eofStart)) - return new AacTail (eofStart >= 0 ? eofStart : length, eofStart, -1, -1, eofApe, eofHeader, null); + if (TryApe (source, length, audioStart, readTags, skipPictures, scratch, out var eofApe, out var eofStart)) + return new AacTail (eofStart >= 0 ? eofStart : length, eofStart, -1, -1, eofApe, null); Id3v1Tag? id3v1 = null; long id3Start = -1; @@ -184,10 +180,9 @@ public static AacTail Locate (AacTailSource source, long audioStart, bool readTa // The APEv2 footer in front of Lyrics3, else in front of ID3v1. ApeTag? ape = null; - var apeHasHeader = false; long apeStart = -1; if (id3Start >= 0) - TryApe (source, lyricsStart >= 0 ? lyricsStart : id3Start, audioStart, readTags, skipPictures, scratch, out ape, out apeHasHeader, out apeStart); + TryApe (source, lyricsStart >= 0 ? lyricsStart : id3Start, audioStart, readTags, skipPictures, scratch, out ape, out apeStart); var audioEnd = length; if (apeStart >= 0) @@ -196,7 +191,7 @@ public static AacTail Locate (AacTailSource source, long audioStart, bool readTa audioEnd = Math.Min (audioEnd, lyricsStart); if (id3Start >= 0) audioEnd = Math.Min (audioEnd, id3Start); - return new AacTail (audioEnd, apeStart, lyricsStart, id3Start, ape, apeHasHeader, id3v1); + return new AacTail (audioEnd, apeStart, lyricsStart, id3Start, ape, id3v1); } // "TAG" opens the last 128 bytes, or an APEv2 footer ends the file. Without either there is no trailing tag: @@ -208,10 +203,9 @@ static bool HasMarker (AacTailSource source) => // True when a valid footer (not a header) ends at tagEnd. A footer that is found decides, whether or not its tag // is valid; a footer that is not found leaves the next placement to try. The tag is placed only when its items // pass the same rules ApeTag.Parse applies (ItemsAreValid); its object is built only for a read. - static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool readTags, bool skipPictures, byte[] scratch, out ApeTag? tag, out bool hasHeader, out long start) + static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool readTags, bool skipPictures, byte[] scratch, out ApeTag? tag, out long start) { tag = null; - hasHeader = false; start = -1; var footerBytes = source.Read (tagEnd - ApeTagFooter.Size, ApeTagFooter.Size); if (footerBytes.IsEmpty) @@ -222,8 +216,8 @@ static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool rea return false; var total = (long)parsed.TagSize; - if (parsed.HasHeader && total <= tagEnd - ApeTagFooter.Size - && source.Read (tagEnd - total - ApeTagFooter.Size, 8).SequenceEqual (ApeTagFooter.Magic)) + // A header starts after the leading ID3v2 tag, as the APE tag does; bytes inside that tag are not one. + if (parsed.CanHaveHeader (tagEnd, audioStart) && parsed.HeaderIn (source.Read (parsed.HeaderStart (tagEnd), ApeTagFooter.Magic.Length))) total += ApeTagFooter.Size; if (total < ApeTagFooter.Size || total > tagEnd - audioStart || total > int.MaxValue) @@ -234,7 +228,6 @@ static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool rea return true; start = tagEnd - total; - hasHeader = total > parsed.TagSize; if (readTags) { var bytes = skipPictures && source.Stream is { } stream && ApeTagTail.TryWithoutCovers (stream, start, tagEnd, parsed, out var stripped) ? stripped @@ -248,7 +241,7 @@ static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool rea } /// - /// The item checks of , without copying a value: the 11-byte-per-item budget, each + /// The item checks of , without copying a value: the 11-byte-per-item budget, each /// item by (the rules uses), and the count rule. /// Each item costs one read of at most bytes into . /// diff --git a/src/TagLibSharp2/Ape/ApeTag.cs b/src/TagLibSharp2/Ape/ApeTag.cs index f0279641..53367501 100644 --- a/src/TagLibSharp2/Ape/ApeTag.cs +++ b/src/TagLibSharp2/Ape/ApeTag.cs @@ -83,6 +83,10 @@ public sealed class ApeTag : Tag { private readonly Dictionary _items; + // Whether the tag was read with a header; null for a tag created here. The header is optional at the end of a + // file (APEv2: "must have at least a footer"), so a save writes the tag back the way it was read. + private readonly bool? _readWithHeader; + /// /// Standard APE key names (Title-case per spec). /// @@ -157,11 +161,12 @@ public ApeTag () } /// - /// Creates an APE tag with the specified items. + /// Creates an APE tag with the specified items, read with or without a header. /// - private ApeTag (Dictionary items) + private ApeTag (Dictionary items, bool readWithHeader) { _items = items; + _readWithHeader = readWithHeader; } /// @@ -1102,7 +1107,15 @@ private void SetOrRemove (string key, string? value, string? alias = null) /// LYRICSBEGIN must sit within 64 KB. The footer is the 32 bytes before LYRICSBEGIN, /// or at EOF-160 when ID3v1 follows and no Lyrics3 block is present. /// - public static ApeTagParseResult Parse (ReadOnlySpan data) + public static ApeTagParseResult Parse (ReadOnlySpan data) => Parse (data, floor: 0); + + /// + /// for a tag that cannot start before . A path or + /// stream read parses the header bytes it keeps joined to the tag it read from the end of the file, and passes + /// their length: a tag in those bytes is not the file's (#242). Whether the tag has a header is decided where the + /// tail is read, and the tail's footer says so (ApeTagTail). + /// + internal static ApeTagParseResult Parse (ReadOnlySpan data, int floor) { var location = ApeTagLocation.Locate (data); if (!location.Found) { @@ -1126,6 +1139,9 @@ public static ApeTagParseResult Parse (ReadOnlySpan data) return ApeTagParseResult.Failure ("Invalid APE tag layout"); } + if (itemsStart < floor) + return ApeTagParseResult.Failure ($"APE tag starts at {itemsStart}, before the tail at {floor}"); + if (ItemBudgetError (footer.ItemCount, itemsSize) is { } budget) return ApeTagParseResult.Failure (budget); @@ -1154,7 +1170,8 @@ public static ApeTagParseResult Parse (ReadOnlySpan data) if (CountMismatchError (footer.ItemCount, itemsParsed, offset, itemsData.Length) is { } mismatch) return ApeTagParseResult.Failure (mismatch); - return ApeTagParseResult.Success (new ApeTag (items)); + var readWithHeader = ApeTagLocation.HeaderSpan (data, footer, location.TagEnd) > 0; + return ApeTagParseResult.Success (new ApeTag (items, readWithHeader)); } // The item-region rules of Parse, shared with the skip walk (ApeTagTail) so both stop at the same item. @@ -1190,9 +1207,23 @@ internal static bool MoreItems (long offset, long length, int parsed, uint count public override void Clear () => _items.Clear (); /// - /// Renders the tag to binary data (without header). + /// Renders the tag to binary data: with a header when it was read with one, otherwise footer-only. /// - public override BinaryData Render () => RenderWithOptions (includeHeader: false); + public override BinaryData Render () => RenderWithOptions (_readWithHeader ?? false); + + /// + /// The bytes a save writes for , or none when it is null, in a file whose read produced + /// . That tag keeps the layout it was read with, so a save with no edit reproduces it. + /// Any other tag, one created here or one parsed from other bytes and assigned, gets + /// : the carrier's layout for a tag it did not read. + /// + internal static BinaryData RenderForSave (ApeTag? tag, ApeTag? readTag, bool defaultHeader) + { + if (tag is null) + return BinaryData.Empty; + var header = ReferenceEquals (tag, readTag) ? tag._readWithHeader ?? defaultHeader : defaultHeader; + return tag.RenderWithOptions (header); + } /// /// Renders the tag to binary data with optional header. diff --git a/src/TagLibSharp2/Ape/ApeTagFooter.cs b/src/TagLibSharp2/Ape/ApeTagFooter.cs index 43d07369..5a9ab3dc 100644 --- a/src/TagLibSharp2/Ape/ApeTagFooter.cs +++ b/src/TagLibSharp2/Ape/ApeTagFooter.cs @@ -115,6 +115,27 @@ public sealed class ApeTagFooter /// public bool HasHeader => (Flags & 0x80000000) != 0; + /// + /// Whether the tag this footer ends has a header. Bit 31 must be set and , the bytes at + /// , must start with "APETAGEX": a header the footer claims but the file does not hold is + /// not part of the tag. This is the one rule every reader and writer applies (#240). + /// + internal bool HeaderIn (ReadOnlySpan preamble) => + HasHeader && preamble.Length >= Magic.Length && preamble[..Magic.Length].SequenceEqual (Magic); + + /// + /// Where the header of the tag that ends at starts: 32 bytes in front of its items, + /// as the tag size counts the items and the footer and not the header. Negative when it would start before byte 0. + /// + internal long HeaderStart (long tagEnd) => tagEnd - TagSize - Size; + + /// + /// Whether the tag that ends at can have a header: bit 31 claims one, and it would start at + /// or after , the first byte the tag may use (0, or the end of a tag or header in front of + /// the audio). Only then are the bytes at read for . + /// + internal bool CanHaveHeader (long tagEnd, long floor) => HasHeader && HeaderStart (tagEnd) >= floor; + /// /// True if the tag contains a footer (bit 30 NOT set). /// diff --git a/src/TagLibSharp2/Ape/ApeTagLocation.cs b/src/TagLibSharp2/Ape/ApeTagLocation.cs index d3bcfe26..0e66d384 100644 --- a/src/TagLibSharp2/Ape/ApeTagLocation.cs +++ b/src/TagLibSharp2/Ape/ApeTagLocation.cs @@ -377,12 +377,14 @@ static long EarliestNeeded (ReadOnlySpan tail, long tailStart, long fileLe return tailStart; if (TryReadLyrics3 (tail, out var lyricsOffset, out _)) { - if (lyricsOffset >= ApeTagFooter.Size) { - var footerRel = lyricsOffset - ApeTagFooter.Size; - var lyricsFooter = ApeTagFooter.Parse (tail.Slice (footerRel, ApeTagFooter.Size)); - if (IsFooter (lyricsFooter)) - return TagBytesStart (lyricsFooter.Footer!, tailStart + lyricsOffset); - } + // The APE footer is the 32 bytes before LYRICSBEGIN. Read them first when the tail holds only part of them. + if (lyricsOffset < ApeTagFooter.Size) + return tailStart + lyricsOffset - ApeTagFooter.Size; + + var footerRel = lyricsOffset - ApeTagFooter.Size; + var lyricsFooter = ApeTagFooter.Parse (tail.Slice (footerRel, ApeTagFooter.Size)); + if (IsFooter (lyricsFooter)) + return TagBytesStart (lyricsFooter.Footer!, tailStart + lyricsOffset); return tailStart; } @@ -441,19 +443,14 @@ static bool TryDecimal (ReadOnlySpan digits, out int value) return true; } + // The first byte a path save reads for the tag that ends at tagEnd. It takes in the 32 bytes a header would use when + // bit 31 claims one, so that Locate can apply ApeTagFooter.HeaderIn to them; it sizes a read and decides nothing. static long TagBytesStart (ApeTagFooter footer, long tagEnd) { if (footer.TagSize < (uint)ApeTagFooter.Size || footer.TagSize > (ulong)tagEnd) return tagEnd - ApeTagFooter.Size; - var start = tagEnd - (long)footer.TagSize; - if (footer.HasHeader) { - var headerStart = start - ApeTagFooter.Size; - if (headerStart >= 0) - start = headerStart; - } - - return start; + return footer.CanHaveHeader (tagEnd, 0) ? footer.HeaderStart (tagEnd) : tagEnd - (long)footer.TagSize; } private static bool HasTrailingId3v1 (ReadOnlySpan data) => @@ -736,18 +733,28 @@ private static bool ItemsMatch (ReadOnlySpan data, ApeTagFooter footer, in return parsed == footer.ItemCount || (offset == items.Length && parsed > 0); } - private static int HeaderSpan (ReadOnlySpan data, ApeTagFooter footer, int tagEnd) + /// + /// The 32 bytes of a header when the tag that ends at in has one + /// by , else 0. A header cannot start before . + /// + internal static int HeaderSpan (ReadOnlySpan data, ApeTagFooter footer, long tagEnd, long floor = 0) { - if (!footer.HasHeader) - return 0; + var at = footer.HeaderStart (tagEnd); + return footer.CanHaveHeader (tagEnd, floor) && at < data.Length && footer.HeaderIn (data[(int)at..]) ? ApeTagFooter.Size : 0; + } - var headerStart = (long)tagEnd - footer.TagSize - ApeTagFooter.Size; - if (headerStart < 0 || headerStart + ApeTagFooter.Magic.Length > data.Length) + /// + /// for a tag that ends at in a + /// seekable stream. The header's first bytes are read only when bit 31 claims one. + /// + internal static int HeaderSpan (Stream stream, ApeTagFooter footer, long tagEnd, long floor = 0) + { + var at = footer.HeaderStart (tagEnd); + if (!footer.CanHaveHeader (tagEnd, floor) || at >= stream.Length) return 0; - return data.Slice ((int)headerStart, ApeTagFooter.Magic.Length).SequenceEqual (ApeTagFooter.Magic) - ? ApeTagFooter.Size - : 0; + stream.Position = at; + return footer.HeaderIn (StreamBytes.ReadAtMost (stream, ApeTagFooter.Magic.Length)) ? ApeTagFooter.Size : 0; } private static ApeTagLocation Missing (int length, string error) => diff --git a/src/TagLibSharp2/Ape/ApeTagTail.cs b/src/TagLibSharp2/Ape/ApeTagTail.cs index b06d5ab2..1247af94 100644 --- a/src/TagLibSharp2/Ape/ApeTagTail.cs +++ b/src/TagLibSharp2/Ape/ApeTagTail.cs @@ -44,8 +44,7 @@ static bool TryReadEndingAt (Stream stream, long end, bool skipPictures, out byt if (!parsed.IsSuccess || parsed.Footer is not { } footer || footer.IsHeader) return false; - var header = (footer.Flags & 0x80000000) != 0 ? ApeTagFooter.Size : 0; - var total = (long)footer.TagSize + header; + var total = (long)footer.TagSize + ApeTagLocation.HeaderSpan (stream, footer, end); if (total < ApeTagFooter.Size || total > end || total > int.MaxValue) return false; @@ -55,16 +54,37 @@ static bool TryReadEndingAt (Stream stream, long end, bool skipPictures, out byt stream.Position = offset; tag = StreamBytes.ReadAtMost (stream, (int)total); - return tag.Length == total; + if (tag.Length != total) + return false; + if (total == footer.TagSize) + ClearHeaderFlag (tag); + return true; + } + + /// + /// The copy says what the file holds. A carrier parses it behind other bytes (its own header bytes, joined), so a + /// footer that still claimed a header the file does not hold would have the parse look for one in those bytes. + /// With bit 31 cleared, the parse finds a header exactly when the copy starts with the one the file holds. + /// + static void ClearHeaderFlag (byte[] tag) + { + var flags = tag.AsSpan (tag.Length - ApeTagFooter.Size + 20, 4); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian (flags, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian (flags) & ~HeaderFlag); } + // Bit 31, "Tag contains a header", and bit 29, "This is the header". + const uint HeaderFlag = 0x80000000; + const uint IsHeaderFlag = 0x20000000; + /// /// Copies the APEv2 tag that runs from to with each picture - /// item's value left out. The items are walked with the rules of + /// item's value left out. The items are walked with the rules of /// (, , ), /// and a picture item () keeps its key and flags with an empty value, so the /// copy holds the same items in the same order and parses to the same tag. /// then drops the emptied items. False when the full parse of this tag fails: the caller hands it the original. + /// takes in a header only when + /// found one, so a header is rebuilt exactly when the tag has one. /// internal static bool TryWithoutCovers (Stream stream, long start, long end, ApeTagFooter footer, out byte[] tag) { @@ -111,10 +131,11 @@ internal static bool TryWithoutCovers (Stream stream, long start, long end, ApeT var body = WithBudget (items, footer.ItemCount, lastPlaceholder); var tagSize = (uint)(body.Length + ApeTagFooter.Size); - var footerFlags = footer.Flags & ~0x20000000u; + // Bit 31 says whether this copy has a header, for the same reason as ClearHeaderFlag. + var footerFlags = (footer.Flags & ~(IsHeaderFlag | HeaderFlag)) | (header ? HeaderFlag : 0); using var rebuilt = new MemoryStream (); if (header) { - var preamble = RenderPreamble (footer.Version, tagSize, footer.ItemCount, footerFlags | 0x20000000); + var preamble = RenderPreamble (footer.Version, tagSize, footer.ItemCount, footerFlags | IsHeaderFlag); rebuilt.Write (preamble, 0, preamble.Length); } diff --git a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs index 53044338..7598cb3d 100644 --- a/src/TagLibSharp2/Ape/MonkeysAudioFile.cs +++ b/src/TagLibSharp2/Ape/MonkeysAudioFile.cs @@ -158,6 +158,9 @@ private MonkeysAudioFile () { } /// APEv2 tag (null if not present) public ApeTag? ApeTag { get; private set; } + // The tag this file's read produced. A save writes it back with the header it had; any other tag is footer-only. + ApeTag? _readApeTag; + /// /// /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag @@ -201,7 +204,7 @@ static MonkeysAudioFileReadResult Recorded (MonkeysAudioFileReadResult result, l // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static MonkeysAudioFileReadResult Parse (ReadOnlySpan data) + static MonkeysAudioFileReadResult Parse (ReadOnlySpan data, int tagFloor = 0) { if (data.Length < MagicSize) return MonkeysAudioFileReadResult.Failure ("Invalid Monkey's Audio file: data too short for magic"); @@ -240,7 +243,7 @@ static MonkeysAudioFileReadResult Parse (ReadOnlySpan data) file.CalculateProperties (); // Parse APEv2 tag at end of file - file.ParseApeTag (data); + file.ParseApeTag (data, tagFloor); return MonkeysAudioFileReadResult.Success (file); } @@ -293,7 +296,7 @@ internal static MonkeysAudioFileReadResult Read (Stream stream, string? sourcePa if (tagAt < header.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (header, tag)), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static MonkeysAudioFileReadResult Mark (MonkeysAudioFileReadResult parsed, MediaReadOptions options) @@ -527,15 +530,19 @@ private void CalculateProperties () ); } - private void ParseApeTag (ReadOnlySpan data) + // A stream read passes the length of the header bytes in front of the tail it read (ApeTag.Parse floor, #242). + private void ParseApeTag (ReadOnlySpan data, int tagFloor) { // APEv2 tag is at end of file, look for footer - var result = ApeTag.Parse (data); + var result = ApeTag.Parse (data, tagFloor); if (result.IsSuccess) { ApeTag = result.Tag; + _readApeTag = result.Tag; } } + byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -559,7 +566,7 @@ public void RemoveApeTag () public byte[] Render (ReadOnlySpan originalData) { _creation?.Settle ([ApeTag]); - byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + byte[] tagData = ApeTagBytes (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); } @@ -645,7 +652,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (SourcePath is not { Length: > 0 }) return FileWriteResult.Failure ("No source path available. File was not read from disk."); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); } @@ -712,7 +719,7 @@ public Task SaveToFileAsync ( if (SourcePath is not { Length: > 0 }) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); } @@ -741,6 +748,7 @@ public void Dispose () return; ApeTag = null; + _readApeTag = null; Properties = default; _originalData = Array.Empty (); SourcePath = null; diff --git a/src/TagLibSharp2/Dff/DffFile.cs b/src/TagLibSharp2/Dff/DffFile.cs index 46500445..d2f273b8 100644 --- a/src/TagLibSharp2/Dff/DffFile.cs +++ b/src/TagLibSharp2/Dff/DffFile.cs @@ -1111,14 +1111,14 @@ static long FindTrailerStart (Stream source, long length, byte[] chunk) if (!parsed.IsSuccess || parsed.Footer is null) return id3Start ?? -1; - var apeStart = ApeStart (source, footerEnd, parsed.Footer, chunk); + var apeStart = ApeStart (source, footerEnd, parsed.Footer, localChunkStart); if (apeStart < localChunkStart) apeStart = footerOffset; return apeStart; } - static long ApeStart (Stream source, long footerEnd, ApeTagFooter footer, byte[] chunk) + static long ApeStart (Stream source, long footerEnd, ApeTagFooter footer, long floor) { var tagSize = (long)footer.TagSize; if (tagSize < ApeTagFooter.Size) @@ -1128,16 +1128,7 @@ static long ApeStart (Stream source, long footerEnd, ApeTagFooter footer, byte[] if (start < 0) return -1; - if (footer.HasHeader) { - var headerStart = start - ApeTagFooter.Size; - if (headerStart >= 0) { - ReadExact (source, headerStart, chunk, 8); - if (chunk.AsSpan (0, 8).SequenceEqual (ApeTagFooter.Magic)) - start = headerStart; - } - } - - return start; + return start - ApeTagLocation.HeaderSpan (source, footer, footerEnd, floor); } static void ReadExact (Stream source, long offset, byte[] buffer, int count) @@ -1295,7 +1286,7 @@ private static int FindNonChunkTrailerStart (byte[] data) if (!parsed.IsSuccess || parsed.Footer is null) return id3Start ?? -1; - var apeStart = ApeContentStart (data, footerEnd, parsed.Footer); + var apeStart = ApeContentStart (data, footerEnd, parsed.Footer, localChunkStart); // TagSize does not fit in front of the footer. Keep the 32-byte footer only. if (apeStart < localChunkStart) apeStart = footerOffset; @@ -1304,7 +1295,7 @@ private static int FindNonChunkTrailerStart (byte[] data) } // Negative when TagSize cannot hold the footer or would start before byte 0. - private static int ApeContentStart (byte[] data, int footerEnd, ApeTagFooter footer) + private static int ApeContentStart (byte[] data, int footerEnd, ApeTagFooter footer, int floor) { var tagSize = (long)footer.TagSize; if (tagSize < ApeTagFooter.Size) @@ -1314,21 +1305,10 @@ private static int ApeContentStart (byte[] data, int footerEnd, ApeTagFooter foo if (start < 0) return -1; - // Header bit plus "APETAGEX" immediately before the items. TagSize does not include it. - if (footer.HasHeader) { - var headerStart = start - ApeTagFooter.Size; - if (headerStart >= 0 && HasApeMagic (data, (int)headerStart)) - start = headerStart; - } - - return (int)start; + // TagSize does not include a header; ApeTagFooter.HeaderIn decides whether there is one, after the form header. + return (int)start - ApeTagLocation.HeaderSpan (data, footer, footerEnd, floor); } - private static bool HasApeMagic (byte[] data, int offset) => - offset >= 0 - && offset <= data.Length - 8 - && data.AsSpan (offset, 8).SequenceEqual (ApeTagFooter.Magic); - private static bool IsId3v1 (byte[] data, int offset) { if (offset < 0 || offset + Id3v1Tag.TagSize > data.Length) diff --git a/src/TagLibSharp2/Mpeg/MpegPsFile.cs b/src/TagLibSharp2/Mpeg/MpegPsFile.cs index c8849f24..ed303e7a 100644 --- a/src/TagLibSharp2/Mpeg/MpegPsFile.cs +++ b/src/TagLibSharp2/Mpeg/MpegPsFile.cs @@ -578,19 +578,16 @@ static int AppendedLength (ReadOnlySpan footer, long end, long floor) } /// - /// The length of an APEv2 tag whose footer is , the 32 bytes before - /// the end of that tag, or 0. The tag size counts the footer; a header adds 32 bytes when the - /// footer's bit 31 says there is one. The caller bounds the length by the prepended tag: an - /// APEv2 tag may not start before the stream does. + /// The APEv2 footer in , the 32 bytes before the end of that tag, or null. Its tag is + /// bytes, and 32 more when finds a header; + /// the caller bounds the length by the prepended tag: an APEv2 tag may not start before the stream does. /// - static long ApeLength (ReadOnlySpan footer) + static ApeTagFooter? ApeFooter (ReadOnlySpan footer) { if (footer.Length != ApeTagFooter.Size) - return 0; + return null; var parsed = ApeTagFooter.Parse (footer); - if (!parsed.IsSuccess || parsed.Footer is not { } ape || ape.IsHeader) - return 0; - return (long)ape.TagSize + ((ape.Flags & 0x80000000) != 0 ? ApeTagFooter.Size : 0); + return parsed.IsSuccess && parsed.Footer is { IsHeader: false } ape && ape.TagSize > 0 ? ape : null; } /// @@ -1136,7 +1133,7 @@ public Task SaveToFileAsync ( /// ID3v1, or before an APEv2 tag ("before tags from other tagging systems"). /// /// - /// The reads are small (10, 32 and 128 bytes) and come one at a time, so the span, stream and + /// The reads are small (8, 10, 32 and 128 bytes) and come one at a time, so the span, stream and /// async readers share this one sequence: names a range and /// takes its bytes. /// @@ -1152,6 +1149,12 @@ internal sealed class TrailerLocator long _boundary = -1; bool _peeled; + // An APEv2 footer whose bit 31 claims a header: its tag ends at _apeEnd, and the bytes where the header would + // start are read next (Step.ApeHeader) before the search that found it (_apeSearch) goes on. + ApeTagFooter? _apeFooter; + long _apeEnd; + Step _apeSearch; + public TrailerLocator (long length, long floor) { _length = length; @@ -1171,6 +1174,7 @@ enum Step Id3v1, Id3v1Ape, StreamApe, + ApeHeader, Done } @@ -1211,6 +1215,10 @@ public bool Next (out long offset, out int count) return Before (FooterStart, ApeTagFooter.Size, out offset, out count); case Step.StreamApe: return Before (_boundary, ApeTagFooter.Size, out offset, out count); + case Step.ApeHeader: + offset = _apeFooter!.HeaderStart (_apeEnd); + count = ApeTagFooter.Magic.Length; + return true; default: if (_peeled) return false; @@ -1248,12 +1256,7 @@ public void Supply (ReadOnlySpan bytes) break; case Step.EofApe: // An APEv2 tag ends the file: there is no ID3v1, and an appended tag may sit before it. - _step = Step.Id3v1; - if (ApeLength (bytes) is var eofApe and > 0 && eofApe <= _length - _floor) { - _boundary = _length - eofApe; - Probe (_boundary, Step.Done); - } - + Ape (bytes, _length, Step.EofApe); break; case Step.Id3v1: // ID3v1 is the last 128 bytes after the stream; 128 bytes that start inside the @@ -1266,20 +1269,58 @@ public void Supply (ReadOnlySpan bytes) _step = Step.Done; } + break; + case Step.Id3v1Ape: + Ape (bytes, FooterStart, Step.Id3v1Ape); + break; + case Step.StreamApe: + Ape (bytes, _boundary, Step.StreamApe); + break; + case Step.ApeHeader: + ApeFound ((long)_apeFooter!.TagSize + (_apeFooter.HeaderIn (bytes) ? ApeTagFooter.Size : 0), _apeSearch); + break; + } + } + + // The footer read before end for a search. A header the footer claims is read before the tag's length is known. + // It starts after the prepended tag, as the APE tag does; bytes inside that tag are not one. + void Ape (ReadOnlySpan bytes, long end, Step search) + { + var footer = ApeFooter (bytes); + if (footer is not null && footer.CanHaveHeader (end, _floor)) { + _apeFooter = footer; + _apeEnd = end; + _apeSearch = search; + _step = Step.ApeHeader; + return; + } + + ApeFound (footer?.TagSize ?? 0, search); + } + + // The search that read an APEv2 footer goes on with its tag's length, or 0 when there was no footer. + void ApeFound (long length, Step search) + { + switch (search) { + case Step.EofApe: + _step = Step.Id3v1; + if (length > 0 && length <= _length - _floor) { + _boundary = _length - length; + Probe (_boundary, Step.Done); + } + break; case Step.Id3v1Ape: _step = Step.Done; - if (ApeLength (bytes) is var ape and > 0 && ape <= FooterStart - _floor) { - _boundary = FooterStart - ape; + if (length > 0 && length <= FooterStart - _floor) { + _boundary = FooterStart - length; Probe (_boundary, Step.Done); } break; - case Step.StreamApe: + default: _step = Step.Done; - StreamEnd = ApeLength (bytes) is var before and > 0 && before <= _boundary - _floor - ? _boundary - before - : _boundary; + StreamEnd = length > 0 && length <= _boundary - _floor ? _boundary - length : _boundary; break; } } diff --git a/src/TagLibSharp2/Musepack/MusepackFile.cs b/src/TagLibSharp2/Musepack/MusepackFile.cs index 0daaeda2..17a2e500 100644 --- a/src/TagLibSharp2/Musepack/MusepackFile.cs +++ b/src/TagLibSharp2/Musepack/MusepackFile.cs @@ -145,6 +145,9 @@ private MusepackFile () { } /// APEv2 tag (null if not present) public ApeTag? ApeTag { get; private set; } + // The tag this file's read produced. A save writes it back with the header it had; any other tag is footer-only. + ApeTag? _readApeTag; + /// /// /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag @@ -185,18 +188,18 @@ static MusepackFileReadResult Recorded (MusepackFileReadResult result, long leng // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static MusepackFileReadResult Parse (ReadOnlySpan data) + static MusepackFileReadResult Parse (ReadOnlySpan data, int tagFloor = 0) { if (data.Length < MinHeaderSize) return MusepackFileReadResult.Failure ("Invalid Musepack file: data too short for magic"); // Check for SV7 magic "MP+" if (data[..3].SequenceEqual (SV7Magic)) - return ParseSV7 (data); + return ParseSV7 (data, tagFloor); // Check for SV8 magic "MPCK" if (data.Length >= 4 && data[..4].SequenceEqual (SV8Magic)) - return ParseSV8 (data); + return ParseSV8 (data, tagFloor); return MusepackFileReadResult.Failure ("Invalid Musepack file: missing magic (expected 'MP+' or 'MPCK')"); } @@ -204,7 +207,7 @@ static MusepackFileReadResult Parse (ReadOnlySpan data) /// /// Parse SV7 format (MP+ magic). /// - private static MusepackFileReadResult ParseSV7 (ReadOnlySpan data) + private static MusepackFileReadResult ParseSV7 (ReadOnlySpan data, int tagFloor) { // SV7 Header structure: // [0-2] Magic "MP+" @@ -246,7 +249,7 @@ private static MusepackFileReadResult ParseSV7 (ReadOnlySpan data) file.CalculateProperties (); // Parse APEv2 tag at end of file - file.ParseApeTag (data); + file.ParseApeTag (data, tagFloor); return MusepackFileReadResult.Success (file); } @@ -254,7 +257,7 @@ private static MusepackFileReadResult ParseSV7 (ReadOnlySpan data) /// /// Parse SV8 format (MPCK magic). /// - private static MusepackFileReadResult ParseSV8 (ReadOnlySpan data) + private static MusepackFileReadResult ParseSV8 (ReadOnlySpan data, int tagFloor) { // SV8 is packet-based format // Magic "MPCK" followed by packets @@ -312,7 +315,7 @@ private static MusepackFileReadResult ParseSV8 (ReadOnlySpan data) file.CalculateProperties (); // Parse APEv2 tag at end of file - file.ParseApeTag (data); + file.ParseApeTag (data, tagFloor); return MusepackFileReadResult.Success (file); } @@ -361,7 +364,7 @@ internal static MusepackFileReadResult Read (Stream stream, string? sourcePath, return Mark (Finish (Read (StreamBytes.ReadToEnd (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); } - return Mark (Finish (Recorded (Parse (Join (header, tag)), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (Recorded (Parse (Join (header, tag), header.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static MusepackFileReadResult Mark (MusepackFileReadResult parsed, MediaReadOptions options) @@ -574,14 +577,18 @@ private void CalculateProperties () ); } - private void ParseApeTag (ReadOnlySpan data) + // A stream read passes the length of the header bytes in front of the tail it read (ApeTag.Parse floor, #242). + private void ParseApeTag (ReadOnlySpan data, int tagFloor) { - var result = ApeTag.Parse (data); + var result = ApeTag.Parse (data, tagFloor); if (result.IsSuccess) { ApeTag = result.Tag; + _readApeTag = result.Tag; } } + byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -605,7 +612,7 @@ public void RemoveApeTag () public byte[] Render (ReadOnlySpan originalData) { _creation?.Settle ([ApeTag]); - byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + byte[] tagData = ApeTagBytes (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); } @@ -691,7 +698,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (SourcePath is not { Length: > 0 }) return FileWriteResult.Failure ("No source path available. File was not read from disk."); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); } @@ -758,7 +765,7 @@ public Task SaveToFileAsync ( if (SourcePath is not { Length: > 0 }) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); } @@ -787,6 +794,7 @@ public void Dispose () return; ApeTag = null; + _readApeTag = null; Properties = default; _originalData = []; SourcePath = null; diff --git a/src/TagLibSharp2/WavPack/WavPackFile.cs b/src/TagLibSharp2/WavPack/WavPackFile.cs index 22223bd6..d69fa44d 100644 --- a/src/TagLibSharp2/WavPack/WavPackFile.cs +++ b/src/TagLibSharp2/WavPack/WavPackFile.cs @@ -164,6 +164,9 @@ private WavPackFile () { } /// APEv2 tag (null if not present) public ApeTag? ApeTag { get; private set; } + // The tag this file's read produced. A save writes it back with the header it had; any other tag is footer-only. + ApeTag? _readApeTag; + /// /// /// The APEv2 tag. A file with none has a view whose first write creates one, and a write that leaves that tag @@ -207,7 +210,7 @@ static WavPackFileReadResult Recorded (WavPackFileReadResult result, long length // The parse of Read without the length it records: a stream reader parses part of the stream and records the // stream's length. - static WavPackFileReadResult Parse (ReadOnlySpan data) + static WavPackFileReadResult Parse (ReadOnlySpan data, int tagFloor = 0) { if (data.Length < MagicSize) return WavPackFileReadResult.Failure ("Invalid WavPack file: data too short for magic"); @@ -247,7 +250,7 @@ static WavPackFileReadResult Parse (ReadOnlySpan data) file.CalculateProperties (); // Parse APEv2 tag at end of file - file.ParseApeTag (data); + file.ParseApeTag (data, tagFloor); return WavPackFileReadResult.Success (file); } @@ -319,7 +322,7 @@ internal static WavPackFileReadResult Read (Stream stream, string? sourcePath, I if (tagAt < block.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (block, tag)), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (Recorded (Parse (Join (block, tag), block.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } static WavPackFileReadResult Mark (WavPackFileReadResult result, MediaReadOptions options) @@ -449,7 +452,7 @@ static WavPackFileReadResult ReadRiffWrapped (Stream stream, string? sourcePath, if (tagAt < window.Length) return Mark (Finish (Read (ReadWhole (stream)), sourcePath, fileSystem, keepPayload: sourcePath is null), options); - return Mark (Finish (Recorded (Parse (Join (window, tag)), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); + return Mark (Finish (Recorded (Parse (Join (window, tag), window.Length), stream.Length), sourcePath, fileSystem, keepPayload: false, fileLength: stream.Length), options); } // Copies fmt and the wvpk header bytes that are present (at most 32). A declared @@ -645,11 +648,13 @@ private void CalculateProperties () ); } - private void ParseApeTag (ReadOnlySpan data) + // A stream read passes the length of the header bytes in front of the tail it read (ApeTag.Parse floor, #242). + private void ParseApeTag (ReadOnlySpan data, int tagFloor) { - var result = ApeTag.Parse (data); + var result = ApeTag.Parse (data, tagFloor); if (result.IsSuccess) { ApeTag = result.Tag; + _readApeTag = result.Tag; } } @@ -783,6 +788,8 @@ private static int ParseMultiChannelCount (ReadOnlySpan data) return 0; } + byte[] ApeTagBytes () => ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: false).ToArray (); + /// /// Ensures an APE tag exists, creating one if necessary. /// @@ -806,7 +813,7 @@ public void RemoveApeTag () public byte[] Render (ReadOnlySpan originalData) { _creation?.Settle ([ApeTag]); - byte[] tagData = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + byte[] tagData = ApeTagBytes (); var location = ApeTagLocation.Locate (originalData); return ApeTagLocation.Rewrite (originalData, location, tagData); } @@ -892,7 +899,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (SourcePath is not { Length: > 0 }) return FileWriteResult.Failure ("No source path available. File was not read from disk."); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag)); } @@ -959,7 +966,7 @@ public Task SaveToFileAsync ( if (SourcePath is not { Length: > 0 }) return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); - var tag = ApeTag is null ? [] : ApeTag.Render ().ToArray (); + var tag = ApeTagBytes (); return Task.FromResult (Source.Saved (ApeTagLocation.WriteFromSource (SourcePath, path, fs, tag, cancellationToken))); } @@ -988,6 +995,7 @@ public void Dispose () return; ApeTag = null; + _readApeTag = null; Properties = default; _originalData = Array.Empty (); SourcePath = null; diff --git a/tests/TagLibSharp2.Tests/Aac/AacDetectionTests.cs b/tests/TagLibSharp2.Tests/Aac/AacDetectionTests.cs index cfaa98a4..81a5c9af 100644 --- a/tests/TagLibSharp2.Tests/Aac/AacDetectionTests.cs +++ b/tests/TagLibSharp2.Tests/Aac/AacDetectionTests.cs @@ -453,13 +453,6 @@ static byte[] ApeWithADamagedHeader () static byte[] Lyrics3V1 () => Concat ("LYRICSBEGIN"u8.ToArray (), "la la la"u8.ToArray (), "LYRICSEND"u8.ToArray ()); // Lyrics3 v2 (https://id3.org/Lyrics3v2): LYRICSBEGIN and fields, a 6-digit size of that body, LYRICS200. - static byte[] Lyrics3V2 () - { - var body = Concat ("LYRICSBEGIN"u8.ToArray (), "IND00003110"u8.ToArray (), "LYR00008la la la"u8.ToArray ()); - var size = System.Text.Encoding.ASCII.GetBytes (body.Length.ToString ("D6", System.Globalization.CultureInfo.InvariantCulture)); - return Concat (body, size, "LYRICS200"u8.ToArray ()); - } - [TestMethod] public void SpanDetectionSpanReadAndStreamRead_AlwaysAgree () { diff --git a/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs index 68bd3700..622c2dc8 100644 --- a/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Aac/AacSaveStreamsAudioTests.cs @@ -91,13 +91,6 @@ static byte[] Build () } // Lyrics3 v2 (https://id3.org/Lyrics3v2): body, a 6-digit size of that body, then LYRICS200. - static byte[] Lyrics3V2 () - { - var body = Concat ("LYRICSBEGIN"u8.ToArray (), "IND00003110"u8.ToArray (), "LYR00008la la la"u8.ToArray ()); - var size = System.Text.Encoding.ASCII.GetBytes (body.Length.ToString ("D6", System.Globalization.CultureInfo.InvariantCulture)); - return Concat (body, size, "LYRICS200"u8.ToArray ()); - } - static void AssertSameBytes (byte[] expected, byte[] actual) { Assert.AreEqual (expected.Length, actual.Length, "saved length"); diff --git a/tests/TagLibSharp2.Tests/Aac/AacTestBuilder.cs b/tests/TagLibSharp2.Tests/Aac/AacTestBuilder.cs index d40d46a9..3c5188b8 100644 --- a/tests/TagLibSharp2.Tests/Aac/AacTestBuilder.cs +++ b/tests/TagLibSharp2.Tests/Aac/AacTestBuilder.cs @@ -167,6 +167,17 @@ static void WritePce (BitWriter bits, int[] front, int lfe, int sampleRateIndex, /// An ID3v1 tag with a title. public static byte[] Id3v1Bytes (string title) => new Id3v1Tag { Title = title }.Render ().ToArray (); + /// + /// A Lyrics3 v2 block: "LYRICSBEGIN", the fields, a 6-digit size of everything before it, and "LYRICS200". + /// It sits between an APEv2 tag and ID3v1. + /// + public static byte[] Lyrics3V2 () + { + var body = Concat ("LYRICSBEGIN"u8.ToArray (), "IND00003110"u8.ToArray (), "LYR00008la la la"u8.ToArray ()); + var size = System.Text.Encoding.ASCII.GetBytes (body.Length.ToString ("D6", System.Globalization.CultureInfo.InvariantCulture)); + return Concat (body, size, "LYRICS200"u8.ToArray ()); + } + /// An APEv2 tag with a title. public static byte[] ApeBytes (string title) => new ApeTag { Title = title }.Render ().ToArray (); diff --git a/tests/TagLibSharp2.Tests/Ape/ApeCarrierFixtures.cs b/tests/TagLibSharp2.Tests/Ape/ApeCarrierFixtures.cs new file mode 100644 index 00000000..77046c3e --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeCarrierFixtures.cs @@ -0,0 +1,161 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Musepack; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.WavPack; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// Monkey's Audio, WavPack and Musepack files whose header bytes end with chosen bytes, and the reads that compare a +/// path or stream read with the span read. A path or stream read keeps those header bytes (the descriptor and +/// header, the first block, the packets up to SH) and parses them joined to the tag it reads from the end, so bytes at +/// their end sit where a span read sees audio. +/// +public static class ApeCarrierFixtures +{ + public enum Entry { Path, PathAsync, Stream } + + static readonly string[] Carriers = [".ape", ".wv", ".mpc"]; + static readonly bool[] Skips = [false, true]; + static readonly Entry[] Entries = [Entry.Path, Entry.PathAsync, Entry.Stream]; + + /// {ape, wv, mpc} × {full, SkipPictures} × {path, async path, stream}. + public static IEnumerable Cases => + from ext in Carriers + from skip in Skips + from entry in Entries + select new object[] { ext, skip, entry }; + + /// {full, SkipPictures} × {path, async path, stream}, for the RIFF-wrapped WavPack read. + public static IEnumerable RiffCases => + from skip in Skips + from entry in Entries + select new object[] { skip, entry }; + + /// + /// RIFF/WAVE holding WavPack: fmt, a "junk" chunk holding , and a data chunk with a minimal + /// block and bytes after it. A stream read keeps everything up to the data chunk header and + /// the 32-byte block header (the window); the rest stays on disk. + /// + public static byte[] RiffWavPack (byte[] junk, int audio) + { + var fmt = new byte[16]; + BinaryPrimitives.WriteUInt16LittleEndian (fmt, 1); + BinaryPrimitives.WriteUInt16LittleEndian (fmt.AsSpan (2), 2); + BinaryPrimitives.WriteUInt32LittleEndian (fmt.AsSpan (4), 44100); + BinaryPrimitives.WriteUInt32LittleEndian (fmt.AsSpan (8), 44100 * 4); + BinaryPrimitives.WriteUInt16LittleEndian (fmt.AsSpan (12), 4); + BinaryPrimitives.WriteUInt16LittleEndian (fmt.AsSpan (14), 16); + var body = Concat (TestBuilders.WavPack.CreateMinimal (), new byte[audio]); + var file = Concat ("RIFF"u8.ToArray (), new byte[4], "WAVE"u8.ToArray (), Chunk ("fmt ", fmt), Chunk ("junk", junk), Chunk ("data", body)); + BinaryPrimitives.WriteUInt32LittleEndian (file.AsSpan (4), (uint)(file.Length - 8)); + return file; + } + + static byte[] Chunk (string id, byte[] payload) + { + var header = new byte[8]; + System.Text.Encoding.ASCII.GetBytes (id).CopyTo (header, 0); + BinaryPrimitives.WriteUInt32LittleEndian (header.AsSpan (4), (uint)payload.Length); + return Concat (header, payload, new byte[payload.Length % 2]); + } + + /// + /// The header bytes of a minimal file, with written bytes before + /// the end of what a stream read keeps: + /// + /// Monkey's Audio: the descriptor and header, which the reader keeps whole. The last 32 bytes are the end of + /// the descriptor's MD5 and padding, then the header; a footer written there makes the header read version 2000 + /// compression and no frames. + /// WavPack: the first block, with a dummy metadata sub-block (ID 0) after its header that holds the bytes. + /// Musepack SV8: "MPCK", then an SH packet whose payload is the stream header fields and room for the bytes, + /// then SE. + /// + /// + public static byte[] HeaderBytesEndingWith (string ext, byte[] bytes, int fromEnd) + { + var (prefix, kept) = ext switch { + ".ape" => MonkeysAudio (), + ".wv" => WavPack (fromEnd), + _ => Musepack (fromEnd), + }; + bytes.CopyTo (prefix.AsSpan (kept - fromEnd)); + return prefix; + } + + static (byte[] Prefix, int Kept) MonkeysAudio () + { + var prefix = TestBuilders.MonkeysAudio.CreateMinimal (); + return (prefix, prefix.Length); + } + + static (byte[] Prefix, int Kept) WavPack (int room) + { + var subBlock = new byte[2 + room + (room % 2)]; + subBlock[1] = (byte)((subBlock.Length - 2) / 2); + var prefix = Concat (TestBuilders.WavPack.CreateMinimal (), subBlock); + BinaryPrimitives.WriteUInt32LittleEndian (prefix.AsSpan (4), (uint)(prefix.Length - 8)); + return (prefix, prefix.Length); + } + + // The minimal file is "MPCK", SH (key, a 1-byte size, the fields) and SE. The SH written here has a size that + // counts its key, itself and its payload, as the reader takes it. + static (byte[] Prefix, int Kept) Musepack (int room) + { + var minimal = TestBuilders.Musepack.CreateMinimal (); + var fieldsEnd = 7 + minimal[6] - 2; + var fields = minimal[7..fieldsEnd]; + var payload = Concat (fields, new byte[room]); + var sh = Concat ("SH"u8.ToArray (), [(byte)(3 + payload.Length)], payload); + var prefix = Concat (minimal[..4], sh, minimal[fieldsEnd..]); + return (prefix, 4 + sh.Length); + } + + /// Reads from a path, an async path or a seekable stream. + public static async Task ReadAsync (Entry entry, byte[] data, string ext, MediaReadOptions options, MockFileSystem fs) + { + fs.AddFile ("/in" + ext, data); + return entry switch { + Entry.Path => MediaFile.Read ("/in" + ext, options, fs), + Entry.PathAsync => await MediaFile.ReadAsync ("/in" + ext, options, fs), + _ => MediaFile.Read (new MemoryStream (data, writable: false), options, "x" + ext), + }; + } + + /// The APE tag the file holds, or null. + public static ApeTag? ApeOf (object file) => + (ApeTag?)file.GetType ().GetProperty ("ApeTag")!.GetValue (file); + + /// The span read's no-edit save. Render takes a span, so it is called by type. + public static byte[] SpanSave (object file, byte[] data) => file switch { + MonkeysAudioFile ape => ape.Render (data), + WavPackFile wv => wv.Render (data), + MusepackFile mpc => mpc.Render (data), + _ => throw new AssertFailedException (file.GetType ().Name), + }; + + /// A path read's no-edit save to "/out" plus . + public static byte[] PathSave (object file, string ext, MockFileSystem fs) + { + var save = file.GetType ().GetMethod ("SaveToFile", [typeof (string), typeof (IFileSystem)])!; + var saved = (FileWriteResult)save.Invoke (file, ["/out" + ext, fs])!; + Assert.IsTrue (saved.IsSuccess, saved.Error); + return fs.ReadAllBytes ("/out" + ext); + } + + static byte[] Concat (params byte[][] parts) + { + var result = new byte[parts.Sum (p => p.Length)]; + var offset = 0; + foreach (var part in parts) { + part.CopyTo (result, offset); + offset += part.Length; + } + return result; + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeFamilySaveStreamsAudioTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeFamilySaveStreamsAudioTests.cs index 2a3f1dfc..2a9dda3f 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeFamilySaveStreamsAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeFamilySaveStreamsAudioTests.cs @@ -4,6 +4,7 @@ using TagLibSharp2.Ape; using TagLibSharp2.Core; using TagLibSharp2.Musepack; +using TagLibSharp2.Tests.Core; using TagLibSharp2.WavPack; namespace TagLibSharp2.Tests.Ape; @@ -204,6 +205,54 @@ static void AssertSameBytes (byte[] expected, byte[] actual) Assert.AreEqual (-1, mismatch, $"first mismatched byte at {mismatch}"); } + /// + /// A path save writes what writes when Lyrics3 v2 and ID3v1 follow the APE + /// tag. The lyrics lengths move LYRICSBEGIN across the first bytes the save reads from the end, so the APE footer + /// in front of it is in that read, only partly in it, or not in it. + /// + [TestMethod] + public void WriteFromSource_ApeTagBeforeLyrics3AndId3v1_WritesWhatRewriteWrites () + { + var audio = new byte[4096]; + audio.AsSpan ().Fill (0x11); + var tag = new ApeTag { Title = "Original", Artist = "Someone" }.RenderWithOptions (includeHeader: true).ToArray (); + var replacement = new ApeTag { Title = "Edited" }.RenderWithOptions (includeHeader: true).ToArray (); + var id3 = TestBuilders.Id3v1.CreateTag (title: "Back"); + var failures = new List (); + for (var length = 0; length <= 80; length++) { + var original = Concat (audio, tag, Lyrics3V2 (new string ('l', length)), id3); + var fs = new MockFileSystem (); + fs.AddFile ("/in.ape", original); + + var saved = ApeTagLocation.WriteFromSource ("/in.ape", "/out.ape", fs, replacement); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var expected = ApeTagLocation.Rewrite (original, ApeTagLocation.Locate (original), replacement); + if (!fs.ReadAllBytes ("/out.ape").AsSpan ().SequenceEqual (expected)) + failures.Add ($"lyrics {length}: {fs.ReadAllBytes ("/out.ape").Length} bytes, expected {expected.Length}"); + } + + Assert.AreEqual (0, failures.Count, string.Join ("; ", failures)); + } + + static byte[] Lyrics3V2 (string lyrics) + { + var body = Concat ("LYRICSBEGIN"u8.ToArray (), System.Text.Encoding.ASCII.GetBytes ($"LYR{lyrics.Length:D5}{lyrics}")); + var size = System.Text.Encoding.ASCII.GetBytes (body.Length.ToString ("D6", System.Globalization.CultureInfo.InvariantCulture)); + return Concat (body, size, "LYRICS200"u8.ToArray ()); + } + + static byte[] Concat (params byte[][] parts) + { + var result = new byte[parts.Sum (p => p.Length)]; + var offset = 0; + foreach (var part in parts) { + part.CopyTo (result, offset); + offset += part.Length; + } + return result; + } + [TestMethod] public async Task HugeTail_DoesNotReplaceTheDestination_AndRejectsAFullFileRead () { diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagAtTheEndTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagAtTheEndTests.cs new file mode 100644 index 00000000..6cf4c6d0 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagAtTheEndTests.cs @@ -0,0 +1,80 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +using static TagLibSharp2.Tests.Ape.ApeCarrierFixtures; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// An APEv2 tag in Monkey's Audio, WavPack and Musepack is the one that ends the file (or ends before Lyrics3 and +/// ID3v1). A path or stream read parses the header bytes it keeps joined to the tag it reads from the end; with no +/// tag at the end, those header bytes alone are parsed. A tag at their end is not the file's tag (#242). +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public sealed class ApeTagAtTheEndTests +{ + /// + /// The header bytes end with a whole footer-only tag, then come 4,096 bytes of audio and no tag. A path or stream + /// read finds an APE tag only where the span read does, and a no-edit save writes what the span read's save writes. + /// + [TestMethod] + [DynamicData (nameof (Cases), typeof (ApeCarrierFixtures))] + public async Task Read_HeaderBytesEndWithATag_FindsNoTagWhereTheSpanReadFindsNone (string ext, bool skip, Entry entry) + { + var phantom = new ApeTag { Title = "Phantom" }.RenderWithOptions (includeHeader: false).ToArray (); + var data = Concat (HeaderBytesEndingWith (ext, phantom, phantom.Length), new byte[4096]); + + await AssertNoTagWhereTheSpanReadFindsNone (data, ext, skip, entry); + } + + /// + /// The RIFF-wrapped WavPack read keeps the RIFF chunks before data, the data chunk header and the block header. + /// A "junk" chunk holds a footer-only tag, then "TAG" and 85 bytes, so the last 128 bytes of that window are an + /// ID3v1 tag and the tag sits where a footer before ID3v1 does. There is no tag at the end of the file. + /// + [TestMethod] + [DynamicData (nameof (RiffCases), typeof (ApeCarrierFixtures))] + public async Task Read_RiffWindowEndsWithATagBeforeId3v1_FindsNoTagWhereTheSpanReadFindsNone (bool skip, Entry entry) + { + const int dataAndBlockHeaders = 8 + 32; + var phantom = new ApeTag { Title = "Phantom!" }.RenderWithOptions (includeHeader: false).ToArray (); + var id3 = Concat ("TAG"u8.ToArray (), new byte[128 - 3 - dataAndBlockHeaders]); + var junk = Concat (phantom, id3); + Assert.AreEqual (0, junk.Length % 2, "fixture: no pad byte after the junk chunk"); + + await AssertNoTagWhereTheSpanReadFindsNone (RiffWavPack (junk, audio: 4096), ".wv", skip, entry); + } + + static async Task AssertNoTagWhereTheSpanReadFindsNone (byte[] data, string ext, bool skip, Entry entry) + { + var span = MediaFile.ReadFromData (data, "x" + ext); + Assert.IsTrue (span.IsSuccess, span.Error); + Assert.IsNull (ApeOf (span.File!), "fixture: the span read finds no tag"); + + var fs = new MockFileSystem (); + var read = await ReadAsync (entry, data, ext, new MediaReadOptions { SkipPictures = skip }, fs); + Assert.IsTrue (read.IsSuccess, read.Error); + Assert.IsNull (ApeOf (read.File!)?.Title, "the tag the read holds"); + + if (skip || entry == Entry.Stream) + return; + CollectionAssert.AreEqual (SpanSave (span.File!, data), PathSave (read.File!, ext, fs), "a save with no edit"); + } + + static byte[] Concat (params byte[][] parts) + { + var result = new byte[parts.Sum (p => p.Length)]; + var offset = 0; + foreach (var part in parts) { + part.CopyTo (result, offset); + offset += part.Length; + } + return result; + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderRuleTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderRuleTests.cs new file mode 100644 index 00000000..d0b494ac --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderRuleTests.cs @@ -0,0 +1,191 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Reflection; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Musepack; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.Tests.Mpeg; +using TagLibSharp2.WavPack; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// An APEv2 tag has a header only when the footer sets bit 31 ("Tag contains a header") and the 32 bytes in front +/// of the items start with "APETAGEX". The span read, the stream read of every carrier and the MPEG-PS trailer +/// search apply that one rule, so a footer whose bit 31 is set with no header in front reads the same everywhere. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public sealed class ApeTagHeaderRuleTests +{ + static readonly string[] Extensions = [".ape", ".wv", ".mpc", ".aac"]; + static readonly int[] Paddings = [0, 4096]; + static readonly bool[] Flags = [false, true]; + + public static IEnumerable Cases => + from ext in Extensions + from padding in Paddings + from flag in Flags + select new object[] { ext, padding, flag }; + + /// + /// The path read of a file whose tag claims a header it does not have shows what the span read shows: the same + /// tag and the same audio properties. A tag that starts less than 32 bytes after the audio header is the case + /// where taking the claim at its word reads audio as tag, or finds no room for the tag at all. + /// + [TestMethod] + [DynamicData (nameof (Cases))] + public void PathRead_FooterClaimsAHeaderItDoesNotHave_ReadsWhatTheSpanReadReads (string ext, int padding, bool flag) + { + var data = Concat (Audio (ext), new byte[padding], FooterOnly ("Title", flag)); + + var span = MediaFile.ReadFromData (data, "x" + ext); + var fs = new MockFileSystem (); + fs.AddFile ("/in" + ext, data); + var path = MediaFile.Read ("/in" + ext, fs); + + Assert.IsTrue (span.IsSuccess, span.Error); + Assert.IsTrue (path.IsSuccess, path.Error); + Assert.AreEqual ("Title", span.Tag?.Title, "span"); + Assert.AreEqual ("Title", path.Tag?.Title, "path"); + AssertSameProperties (((IMediaFile)span.File!).AudioProperties, ((IMediaFile)path.File!).AudioProperties); + } + + /// + /// An appended ID3v2 tag before an APEv2 tag that ends the file is found when that tag's footer claims a header + /// it does not have (ID3v2.4 section 5: a tag appended "before tags from other tagging systems"). + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void MpegPs_AppendedTagBeforeApeThatClaimsAHeader_IsTheId3v2Tag (bool flag) + { + var data = MpegPsTestBuilder.Concat (MpegPsTestBuilder.ProgramStream (), MpegPsAppendedTagTests.Appended ("Before Ape"), FooterOnly ("Ape", flag)); + + var span = MpegPsFile.Read (data).File!; + var fs = new MockFileSystem (); + fs.AddFile ("/in.mpg", data); + var path = (MpegPsFile)MediaFile.Read ("/in.mpg", fs).File!; + + Assert.AreEqual ("Before Ape", span.Id3v2Tag?.Title, "span"); + Assert.AreEqual ("Before Ape", path.Id3v2Tag?.Title, "path"); + } + + /// + /// An APEv2 tag cannot start before the stream does, so a header it claims cannot either. Fewer than 32 bytes of + /// stream sit between the prepended tag and an APE tag whose footer claims a header, and the 8 bytes where that + /// header would start, inside the prepended tag, are "APETAGEX". The tag is the items and the footer, and the + /// stream ends where it starts. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void MpegPs_ClaimedHeaderInsideThePrependedTag_IsNotCounted (bool claimHeader) + { + const int floor = 64; + const int stream = 8; + var tag = FooterOnly ("Ape", claimHeader); + var data = Concat (new byte[floor], new byte[stream], tag); + ApeTagFooter.Magic.CopyTo (data.AsSpan (floor + stream - ApeTagFooter.Size)); + + var trailer = new MpegPsFile.TrailerLocator (data.Length, floor); + while (trailer.Next (out var offset, out var count)) + trailer.Supply (count > 0 ? data.AsSpan ((int)offset, count) : []); + + Assert.AreEqual (floor + stream, trailer.StreamEnd); + } + + /// + /// The AAC twin: the ID3v2 tag in front of the frames ends with "APETAGEX" in its padding, where the header of the + /// APE tag after them would start. That header would start inside the ID3v2 tag, so the APE tag has none and is read. + /// + [TestMethod] + [DataRow (false)] + [DataRow (true)] + public void Aac_ClaimedHeaderInsideTheId3v2Tag_IsNotCounted (bool claimHeader) + { + // "APETAGEX" in the last 8 bytes of the ID3v2 padding, after the zero that ends its frames. + var id3 = AacTestBuilder.Id3v2Bytes ("Front"); + var magicAt = id3.Length - ApeTagFooter.Magic.Length; + ApeTagFooter.Magic.CopyTo (id3.AsSpan (magicAt)); + var frames = AacTestBuilder.Adts (1, length: magicAt + ApeTagFooter.Size - id3.Length); + var data = Concat (id3, frames, FooterOnly ("Title", claimHeader)); + Assert.IsTrue (frames.Length is > 7 and < ApeTagFooter.Size, $"fixture: {frames.Length} bytes of frames"); + + var file = TagLibSharp2.Aac.AacFile.Read (data); + + Assert.IsTrue (file.IsSuccess, file.Error); + Assert.AreEqual ("Title", file.File!.ApeTag?.Title); + } + + /// + /// A path or stream read parses the header bytes it keeps (the descriptor and header, the first block, the + /// packets up to SH) joined to the tag it reads from the end. Those header bytes end with "APETAGEX" 32 bytes + /// before their end, and the footer claims a header the file does not hold. The read decides on the file's bytes + /// in front of the items, as the span read does, not on the header bytes in front of them in the joined copy. + /// The no-edit save of a full path read writes what the span read's save writes (a footer-only tag, as the file + /// holds no header); a skip read's tag is the full read's without pictures. + /// + [TestMethod] + [DynamicData (nameof (ApeCarrierFixtures.Cases), typeof (ApeCarrierFixtures))] + public async Task Read_HeaderBytesEndLikeAnApeHeader_ReadsWhatTheSpanReadReads (string ext, bool skip, ApeCarrierFixtures.Entry entry) + { + var prefix = ApeCarrierFixtures.HeaderBytesEndingWith (ext, ApeTagFooter.Magic.ToArray (), ApeTagFooter.Size); + var data = Concat (prefix, new byte[4096], FooterOnly ("Title", claimHeader: true, cover: true)); + + var span = MediaFile.ReadFromData (data, "x" + ext); + Assert.IsTrue (span.IsSuccess, span.Error); + var expected = ApeCarrierFixtures.ApeOf (span.File!)!; + Assert.IsFalse (HasHeader (expected.Render ().ToArray ()), "fixture: the span read finds no header"); + if (skip) + expected.Pictures = []; + + var fs = new MockFileSystem (); + var read = await ApeCarrierFixtures.ReadAsync (entry, data, ext, new MediaReadOptions { SkipPictures = skip }, fs); + Assert.IsTrue (read.IsSuccess, read.Error); + CollectionAssert.AreEqual (expected.Render ().ToArray (), ApeCarrierFixtures.ApeOf (read.File!)!.Render ().ToArray (), "the tag the read holds"); + + if (skip || entry == ApeCarrierFixtures.Entry.Stream) + return; + CollectionAssert.AreEqual (ApeCarrierFixtures.SpanSave (span.File!, data), ApeCarrierFixtures.PathSave (read.File!, ext, fs), "a save with no edit"); + } + + static bool HasHeader (byte[] tag) => tag.AsSpan (0, 8).SequenceEqual (ApeTagFooter.Magic) && tag.Length > ApeTagFooter.Size * 2; + + /// A footer-only tag, with bit 31 set in its footer when . + static byte[] FooterOnly (string title, bool claimHeader, bool cover = false) + { + var ape = new ApeTag { Title = title }; + if (cover) + ape.Pictures = [new ApePicture ("image/jpeg", PictureType.FrontCover, "cover.jpg", new BinaryData (new byte[64]))]; + var tag = ape.RenderWithOptions (includeHeader: false).ToArray (); + if (claimHeader) { + var flags = tag.AsSpan (tag.Length - ApeTagFooter.Size + 20); + BinaryPrimitives.WriteUInt32LittleEndian (flags, BinaryPrimitives.ReadUInt32LittleEndian (flags) | 0x80000000); + } + return tag; + } + + static byte[] Audio (string ext) => ext switch { + ".ape" => TestBuilders.MonkeysAudio.CreateMinimal (), + ".wv" => TestBuilders.WavPack.CreateMinimal (), + ".mpc" => TestBuilders.Musepack.CreateMinimal (), + _ => AacTestBuilder.Adts (30, length: 90), + }; + + static void AssertSameProperties (IMediaProperties? span, IMediaProperties? path) + { + Assert.IsNotNull (span); + Assert.IsNotNull (path); + foreach (var property in span.GetType ().GetProperties (BindingFlags.Public | BindingFlags.Instance)) + Assert.AreEqual (property.GetValue (span), property.GetValue (path), property.Name); + } + + static byte[] Concat (params byte[][] parts) => MpegPsTestBuilder.Concat (parts); +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderSaveTests.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderSaveTests.cs new file mode 100644 index 00000000..e75f5cd0 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagHeaderSaveTests.cs @@ -0,0 +1,293 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Aac; +using TagLibSharp2.Ape; +using TagLibSharp2.Core; +using TagLibSharp2.Musepack; +using TagLibSharp2.Tests.Aac; +using TagLibSharp2.Tests.Core; +using TagLibSharp2.WavPack; + +namespace TagLibSharp2.Tests.Ape; + +/// +/// A save writes the APEv2 tag read from the file back with the header it was read with (#217). At the end of a +/// file the header is optional ("An APE tag at the end of a file ... must have at least a footer", APEv2 +/// specification; flags bit 31, "Tag contains a header"). A tag read with one keeps it, a tag read without one +/// stays footer-only, and a save with no edit reproduces the file. Any other tag, one this library creates or +/// one parsed from other bytes and assigned, gets the carrier's default: footer-only in Monkey's Audio, WavPack +/// and Musepack, a header in raw AAC. The rows cover every carrier that renders an , the +/// span, path and async path entry points, and no trailing data, ID3v1, or Lyrics3 v2 and ID3v1 after the tag. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Ape")] +public sealed class ApeTagHeaderSaveTests +{ + public enum Entry { Span, Path, PathAsync } + + public enum Trailing { None, Id3v1, Lyrics3AndId3v1 } + + /// + /// What happens to the tag before the save. The replacements are tags other than the one read: in AAC a tag + /// parsed from other bytes (with or without a header) is assigned; the other carriers have no setter, so the + /// read tag is removed and a new one created. + /// + public enum Change { None, Edit, ReplaceWithHeaderParse, ReplaceWithFooterOnlyParse } + + public sealed record Carrier ( + string Name, + string Extension, + Func Audio, + Func ReadSpan, + Func Render, + Func Tag, + Func EnsureTag, + Action Replace, + Func Save, + Func> SaveAsync, + bool NewTagHeader) + { + public override string ToString () => Name; + } + + static readonly Carrier MonkeysAudio = new ( + "Monkey's Audio", ".ape", + () => TestBuilders.MonkeysAudio.CreateMinimal (), + data => Read (MonkeysAudioFile.Read (data).File, data), + (f, original) => ((MonkeysAudioFile)f).Render (original), + f => ((MonkeysAudioFile)f).ApeTag, + f => ((MonkeysAudioFile)f).EnsureApeTag (), + (f, source) => { + ((MonkeysAudioFile)f).RemoveApeTag (); + ((MonkeysAudioFile)f).EnsureApeTag ().Title = source.Title; + }, + (f, path, fs) => ((MonkeysAudioFile)f).SaveToFile (path, fs), + (f, path, fs) => ((MonkeysAudioFile)f).SaveToFileAsync (path, fs), + NewTagHeader: false); + + static readonly Carrier WavPack = new ( + "WavPack", ".wv", + () => TestBuilders.WavPack.CreateMinimal (), + data => Read (WavPackFile.Read (data).File, data), + (f, original) => ((WavPackFile)f).Render (original), + f => ((WavPackFile)f).ApeTag, + f => ((WavPackFile)f).EnsureApeTag (), + (f, source) => { + ((WavPackFile)f).RemoveApeTag (); + ((WavPackFile)f).EnsureApeTag ().Title = source.Title; + }, + (f, path, fs) => ((WavPackFile)f).SaveToFile (path, fs), + (f, path, fs) => ((WavPackFile)f).SaveToFileAsync (path, fs), + NewTagHeader: false); + + static readonly Carrier Musepack = new ( + "Musepack", ".mpc", + () => TestBuilders.Musepack.CreateMinimal (), + data => Read (MusepackFile.Read (data).File, data), + (f, original) => ((MusepackFile)f).Render (original), + f => ((MusepackFile)f).ApeTag, + f => ((MusepackFile)f).EnsureApeTag (), + (f, source) => { + ((MusepackFile)f).RemoveApeTag (); + ((MusepackFile)f).EnsureApeTag ().Title = source.Title; + }, + (f, path, fs) => ((MusepackFile)f).SaveToFile (path, fs), + (f, path, fs) => ((MusepackFile)f).SaveToFileAsync (path, fs), + NewTagHeader: false); + + static readonly Carrier Aac = new ( + "AAC", ".aac", + () => AacTestBuilder.Adts (30, length: 90), + data => Read (AacFile.Read (data).File, data), + (f, original) => ((AacFile)f).Render (original).ToArray (), + f => ((AacFile)f).ApeTag, + f => ((AacFile)f).ApeTag ??= new ApeTag (), + (f, source) => ((AacFile)f).ApeTag = source, + (f, path, fs) => ((AacFile)f).SaveToFile (path, fs), + (f, path, fs) => ((AacFile)f).SaveToFileAsync (path, fs), + NewTagHeader: true); + + static readonly Carrier[] Carriers = [MonkeysAudio, WavPack, Musepack, Aac]; + static readonly bool[] Booleans = [true, false]; + static readonly Entry[] Entries = [Entry.Span, Entry.Path, Entry.PathAsync]; + static readonly Trailing[] Trailings = [Trailing.None, Trailing.Id3v1, Trailing.Lyrics3AndId3v1]; + static readonly Change[] Changes = [Change.None, Change.Edit, Change.ReplaceWithHeaderParse, Change.ReplaceWithFooterOnlyParse]; + + static object Read (object? file, byte[] data) => + file ?? throw new AssertFailedException ($"the {data.Length}-byte fixture did not read"); + + public static IEnumerable SaveCases => + from carrier in Carriers + from header in Booleans + from trailing in Trailings + from change in Changes + from entry in Entries + select new object[] { carrier, header, trailing, change, entry }; + + public static IEnumerable NewTagCases => + from carrier in Carriers + from trailing in Trailings + from entry in Entries + select new object[] { carrier, trailing, entry }; + + [TestMethod] + [DynamicData (nameof (SaveCases))] + public async Task Save_TagReadWithOrWithoutHeader_KeepsWhatTheFileHad (Carrier carrier, bool header, Trailing trailing, Change change, Entry entry) + { + var audio = carrier.Audio (); + var after = TrailingBytes (trailing); + var original = Concat (audio, new ApeTag { Title = "Original", Artist = "Someone" }.RenderWithOptions (header).ToArray (), after); + Assert.AreEqual (header, HeaderOf (original, after.Length), "fixture"); + + var saved = await SaveAsync (carrier, original, entry, file => { + switch (change) { + case Change.Edit: + carrier.Tag (file)!.Title = "Edited title"; + break; + case Change.ReplaceWithHeaderParse or Change.ReplaceWithFooterOnlyParse: + carrier.Replace (file, Parsed ("Replaced", change == Change.ReplaceWithHeaderParse)); + break; + } + }); + + CollectionAssert.AreEqual (after, saved[^after.Length..], "the data after the tag"); + CollectionAssert.AreEqual (audio, saved[..TagStart (saved, after.Length)], "the bytes in front of the one tag"); + switch (change) { + case Change.None: + CollectionAssert.AreEqual (original, saved, "a save with no edit must reproduce the file"); + break; + case Change.Edit: + Assert.AreEqual (header, HeaderOf (saved, after.Length), header ? "the APEv2 header was dropped" : "a header was added"); + Assert.AreEqual ("Edited title", carrier.Tag (carrier.ReadSpan (saved))!.Title); + break; + default: + Assert.AreEqual (carrier.NewTagHeader, HeaderOf (saved, after.Length), "a tag other than the one read gets the carrier default"); + Assert.AreEqual ("Replaced", carrier.Tag (carrier.ReadSpan (saved))!.Title); + break; + } + } + + [TestMethod] + [DynamicData (nameof (NewTagCases))] + public async Task Save_NewTag_GetsTheCarrierDefault (Carrier carrier, Trailing trailing, Entry entry) + { + var after = TrailingBytes (trailing); + var original = Concat (carrier.Audio (), after); + + var saved = await SaveAsync (carrier, original, entry, file => carrier.EnsureTag (file).Title = "New"); + + Assert.AreEqual (carrier.NewTagHeader, HeaderOf (saved, after.Length)); + CollectionAssert.AreEqual (after, saved[^after.Length..], "the data after the tag"); + CollectionAssert.AreEqual (original[..^after.Length], saved[..TagStart (saved, after.Length)], "the bytes in front of the tag"); + Assert.AreEqual ("New", carrier.Tag (carrier.ReadSpan (saved))!.Title); + } + + [TestMethod] + [DataRow (true)] + [DataRow (false)] + public void Render_ParsedTag_ReproducesTheTagAsRead (bool header) + { + var bytes = new ApeTag { Title = "Title", Album = "Album" }.RenderWithOptions (header).ToArray (); + + var parsed = ApeTag.Parse (bytes); + + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + CollectionAssert.AreEqual (bytes, parsed.Tag!.Render ().ToArray ()); + } + + [TestMethod] + public void Render_HeaderFlagWithoutHeaderBytes_IsFooterOnly () + { + // The footer claims a header, but the 32 bytes before the items are not "APETAGEX". The tag was read + // without a header, so it is written without one. + var bytes = new ApeTag { Title = "Title" }.RenderWithOptions (includeHeader: false).ToArray (); + var flags = bytes.AsSpan (bytes.Length - ApeTagFooter.Size + 20); + BinaryPrimitives.WriteUInt32LittleEndian (flags, BinaryPrimitives.ReadUInt32LittleEndian (flags) | 0x80000000); + var data = Concat (new byte[ApeTagFooter.Size], bytes); + + var parsed = ApeTag.Parse (data); + + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.IsFalse (HeaderOf (parsed.Tag!.Render ().ToArray (), 0)); + } + + static ApeTag Parsed (string title, bool header) + { + var parsed = ApeTag.Parse (new ApeTag { Title = title }.RenderWithOptions (header).Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + return parsed.Tag!; + } + + static byte[] TrailingBytes (Trailing trailing) => trailing switch { + Trailing.Id3v1 => AacTestBuilder.Id3v1Bytes ("Back"), + Trailing.Lyrics3AndId3v1 => Concat (AacTestBuilder.Lyrics3V2 (), AacTestBuilder.Id3v1Bytes ("Back")), + _ => [], + }; + + static async Task SaveAsync (Carrier carrier, byte[] original, Entry entry, Action change) + { + if (entry == Entry.Span) { + var file = carrier.ReadSpan (original); + change (file); + return carrier.Render (file, original); + } + + var input = "/in" + carrier.Extension; + var output = "/out" + carrier.Extension; + var fs = new MockFileSystem (); + fs.AddFile (input, original); + var read = entry == Entry.Path ? MediaFile.Read (input, fs) : await MediaFile.ReadAsync (input, fs); + Assert.IsTrue (read.IsSuccess, read.Error); + var opened = read.File!; + using var dispose = (IDisposable)opened; + change (opened); + var result = entry == Entry.Path ? carrier.Save (opened, output, fs) : await carrier.SaveAsync (opened, output, fs); + Assert.IsTrue (result.IsSuccess, result.Error); + return fs.ReadAllBytes (output); + } + + /// + /// Whether the APEv2 tag that ends bytes before the end of the file has a header: + /// the footer's bit 31 is set, and the 32 bytes before the items are a header (bit 29 set) that carries the + /// footer's size and item count. A footer that sets bit 31 without those bytes fails, so the oracle also catches + /// a flag that disagrees with the bytes. + /// + static bool HeaderOf (byte[] file, int trailing) => HeaderOf (file, trailing, out _); + + /// The first byte of the APEv2 tag that ends bytes before the end, its header included. + static int TagStart (byte[] file, int trailing) + { + HeaderOf (file, trailing, out var start); + return start; + } + + static bool HeaderOf (byte[] file, int trailing, out int start) + { + var end = file.Length - trailing; + var footer = ApeTagFooter.Parse (file.AsSpan (end - ApeTagFooter.Size, ApeTagFooter.Size)); + Assert.IsTrue (footer.IsSuccess, footer.Error); + var flagged = footer.Footer!.HasHeader; + var at = end - (int)footer.Footer.TagSize - ApeTagFooter.Size; + var present = at >= 0 && ApeTagFooter.Parse (file.AsSpan (at, ApeTagFooter.Size)) is { IsSuccess: true } header + && header.Footer!.IsHeader + && header.Footer.TagSize == footer.Footer.TagSize + && header.Footer.ItemCount == footer.Footer.ItemCount; + Assert.AreEqual (flagged, present, "the footer's has-header flag disagrees with the bytes"); + start = present ? at : at + ApeTagFooter.Size; + return present; + } + + static byte[] Concat (params byte[][] parts) + { + var result = new byte[parts.Sum (p => p.Length)]; + var offset = 0; + foreach (var part in parts) { + part.CopyTo (result, offset); + offset += part.Length; + } + return result; + } +} diff --git a/tests/TagLibSharp2.Tests/Ape/ApeTagTestData.cs b/tests/TagLibSharp2.Tests/Ape/ApeTagTestData.cs index 41fa7090..cc94e49d 100644 --- a/tests/TagLibSharp2.Tests/Ape/ApeTagTestData.cs +++ b/tests/TagLibSharp2.Tests/Ape/ApeTagTestData.cs @@ -39,7 +39,8 @@ public static void AssertId3v1SaveRoundTrip (byte[] audio, Func static List Snapshot (ApeTag tag) { - var data = tag.Render ().ToArray (); + var data = tag.RenderWithOptions (includeHeader: false).ToArray (); var rows = new List (); var pos = 0; var end = data.Length - 32; diff --git a/tests/TagLibSharp2.Tests/Dff/DffFileTests.cs b/tests/TagLibSharp2.Tests/Dff/DffFileTests.cs index 096c8e59..1e3672c3 100644 --- a/tests/TagLibSharp2.Tests/Dff/DffFileTests.cs +++ b/tests/TagLibSharp2.Tests/Dff/DffFileTests.cs @@ -9,6 +9,7 @@ using TagLibSharp2.Dsf; using TagLibSharp2.Id3; using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Tests.Core; namespace TagLibSharp2.Tests.Dff; @@ -1040,6 +1041,85 @@ public void Render_ApeTagWithItem_AppendedId3KeepsWholeTag (string soundChunkId, AssertTrailerAfterId3 (rendered, soundChunkId, payload, trailer); } + /// + /// An APE tag after the form is copied whole, header included, and nothing in front of it is: a header counts only + /// when bit 31 claims one and "APETAGEX" is in front of the items (, #240). The + /// rows cover a tag with a header and a footer that claims a header the file does not hold, on the span save and on + /// the path save, which finds the trailer through the stream. + /// + [TestMethod] + [DataRow ("DSD ", false, false)] + [DataRow ("DST ", false, false)] + [DataRow ("DSD ", true, false)] + [DataRow ("DST ", true, false)] + [DataRow ("DSD ", false, true)] + [DataRow ("DST ", false, true)] + [DataRow ("DSD ", true, true)] + [DataRow ("DST ", true, true)] + public void Save_ApeTagWithOrWithoutTheHeaderItClaims_KeepsTheSoundChunk (string soundChunkId, bool path, bool realHeader) + { + var payload = new byte[40]; + payload.AsSpan ().Fill (0x5A); + var trailer = new ApeTag { Title = "ApeTitle" }.RenderWithOptions (includeHeader: realHeader).ToArray (); + var flags = trailer.AsSpan (trailer.Length - ApeTagFooter.Size + 20); + BinaryPrimitives.WriteUInt32LittleEndian (flags, BinaryPrimitives.ReadUInt32LittleEndian (flags) | 0x80000000); + + var fileBytes = Concat (CreateSoundFile (soundChunkId, payload), trailer); + BinaryPrimitives.WriteUInt64BigEndian (fileBytes.AsSpan (4, 8), (ulong)(fileBytes.Length - 12)); + + BinaryData rendered; + if (path) { + var fs = new MockFileSystem (); + fs.AddFile ("/in.dff", fileBytes); + var opened = (DffFile)MediaFile.Read ("/in.dff", fs).File!; + opened.EnsureId3v2Tag ().Title = "New Title"; + var saved = opened.SaveToFile ("/out.dff", fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + rendered = new BinaryData (fs.ReadAllBytes ("/out.dff")); + } else { + var read = DffFile.Read (fileBytes); + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.EnsureId3v2Tag ().Title = "New Title"; + rendered = read.File.Render (); + } + + AssertTrailerAfterId3 (rendered, soundChunkId, payload, trailer); + } + + /// + /// A claimed header cannot start inside the 16-byte form header: the FRM8 size field at offset 4 reads "APETAGEX", + /// and the APE footer's size and bit 31 put a header there. The tag has no header, so the trailer is the items and + /// the footer, and the span save and the path save, which find the trailer by separate searches, write the same bytes. + /// + [TestMethod] + [DataRow ("DSD ")] + [DataRow ("DST ")] + public void Save_ClaimedHeaderInsideTheFormHeader_SpanAndPathSavesAgree (string soundChunkId) + { + var sound = CreateSoundFile (soundChunkId, new byte[40]); + ApeTagFooter.Magic.CopyTo (sound.AsSpan (4)); + // The tag ends with the file; its header would start at offset 4: footerEnd - TagSize - 32 = 4. + var tagSize = (uint)(sound.Length + ApeTagFooter.Size - 4 - ApeTagFooter.Size); + var fileBytes = Concat (sound, ApeTagFooter.Create (tagSize, 0, hasHeader: true).Render ().ToArray ()); + + var read = DffFile.Read (fileBytes); + Assert.IsTrue (read.IsSuccess, read.Error); + read.File!.EnsureId3v2Tag ().Title = "New Title"; + var spanSaved = read.File.Render ().ToArray (); + + var fs = new MockFileSystem (); + fs.AddFile ("/in.dff", fileBytes); + var opened = (DffFile)MediaFile.Read ("/in.dff", fs).File!; + opened.EnsureId3v2Tag ().Title = "New Title"; + var saved = opened.SaveToFile ("/out.dff", fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + + // Without a header the tag starts at offset 36, and everything from there is copied after the form as the trailer. + var trailer = fileBytes[(fileBytes.Length - (int)tagSize)..]; + CollectionAssert.AreEqual (trailer, spanSaved[^trailer.Length..], "the trailer"); + CollectionAssert.AreEqual (spanSaved, fs.ReadAllBytes ("/out.dff")); + } + [TestMethod] [DataRow ("DSD ")] [DataRow ("DST ")] diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index 9622ed2a..346723aa 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -438,6 +438,89 @@ public void CrcCheck_RejectsABrokenChecksumUnderAnElementWithoutOne () Assert.IsFalse (EveryCrcMatches (FileWith (Master (0x7373, inner)))); } + /// + /// A leaf whose value starts like a CRC-32 element (0xBF, size 4) is a value, not a child (#218). A save writes + /// random 8-byte UIDs, and one of them can start that way. + /// + [TestMethod] + public void CrcCheck_LeafValueThatLooksLikeACrcElement_IsNotAChild () + { + byte[] looksLikeCrc = [0xBF, 0x84, 0, 0, 0, 0, 0x12, 0x34]; + var attachments = Master (0x1941A469, Master (0x61A7, Concat ( + Element (0x466E, "a.bin"u8), + Element (0x4660, "application/octet-stream"u8), + Element (0x465C, new byte[] { 1 }), + Element (0x46AE, looksLikeCrc)))); + var chapters = Master (0x1043A770, Master (0x45B9, Concat ( + Element (0x45BC, looksLikeCrc), + Master (0xB6, Concat (Element (0x73C4, looksLikeCrc), Element (0x91, new byte[] { 0 })))))); + var cluster = Master (MatroskaIds.Cluster, Concat (Element (0xE7, new byte[] { 0 }), Element (0xA3, looksLikeCrc))); + + Assert.IsTrue (EveryCrcMatches (FileWith (attachments, chapters, cluster))); + } + + /// + /// The check descends into every master element: a CRC-32 with a wrong checksum as the first child of any of them + /// fails it. One row per master, listed here apart from MasterIds, so leaving one out of that set turns its row red. + /// The first 42 rows are RFC 9559 section 5.1, then Appendix A, then the two from the Matroska schema. + /// + [TestMethod] + [DataRow (0x114D9B74u, "SeekHead")] + [DataRow (0x4DBBu, "Seek")] + [DataRow (0x1549A966u, "Info")] + [DataRow (0x6924u, "ChapterTranslate")] + [DataRow (0x1F43B675u, "Cluster")] + [DataRow (0xA0u, "BlockGroup")] + [DataRow (0x75A1u, "BlockAdditions")] + [DataRow (0xA6u, "BlockMore")] + [DataRow (0x1654AE6Bu, "Tracks")] + [DataRow (0xAEu, "TrackEntry")] + [DataRow (0x41E4u, "BlockAdditionMapping")] + [DataRow (0x6624u, "TrackTranslate")] + [DataRow (0xE0u, "Video")] + [DataRow (0x55B0u, "Colour")] + [DataRow (0x55D0u, "MasteringMetadata")] + [DataRow (0x7670u, "Projection")] + [DataRow (0xE1u, "Audio")] + [DataRow (0xE2u, "TrackOperation")] + [DataRow (0xE3u, "TrackCombinePlanes")] + [DataRow (0xE4u, "TrackPlane")] + [DataRow (0xE9u, "TrackJoinBlocks")] + [DataRow (0x6D80u, "ContentEncodings")] + [DataRow (0x6240u, "ContentEncoding")] + [DataRow (0x5034u, "ContentCompression")] + [DataRow (0x5035u, "ContentEncryption")] + [DataRow (0x47E7u, "ContentEncAESSettings")] + [DataRow (0x1C53BB6Bu, "Cues")] + [DataRow (0xBBu, "CuePoint")] + [DataRow (0xB7u, "CueTrackPositions")] + [DataRow (0xDBu, "CueReference")] + [DataRow (0x1941A469u, "Attachments")] + [DataRow (0x61A7u, "AttachedFile")] + [DataRow (0x1043A770u, "Chapters")] + [DataRow (0x45B9u, "EditionEntry")] + [DataRow (0xB6u, "ChapterAtom")] + [DataRow (0x80u, "ChapterDisplay")] + [DataRow (0x6944u, "ChapProcess")] + [DataRow (0x6911u, "ChapProcessCommand")] + [DataRow (0x1254C367u, "Tags")] + [DataRow (0x7373u, "Tag")] + [DataRow (0x63C0u, "Targets")] + [DataRow (0x67C8u, "SimpleTag")] + [DataRow (0x5854u, "SilentTracks")] + [DataRow (0x8Eu, "Slices")] + [DataRow (0xE8u, "TimeSlice")] + [DataRow (0xC8u, "ReferenceFrame")] + [DataRow (0x4520u, "EditionDisplay")] + [DataRow (0x8Fu, "ChapterTrack")] + public void CrcCheck_RejectsABrokenChecksumInEveryMaster (uint id, string name) + { + var inner = WithCrc (id, Element (0xEC, new byte[] { 0 })); + inner[^1] ^= 0xFF; + + Assert.IsFalse (EveryCrcMatches (FileWith (inner)), name); + } + [TestMethod] public void Save_SettingTitle_KeepsSortAndOtherLanguages () { @@ -1429,12 +1512,41 @@ static bool EveryCrcMatches (byte[] file) return CrcTreeMatches (body); } + /// + /// The master elements of a Segment body. Only these hold child elements; every other payload is a value, such as + /// an 8-byte UID that can start with the CRC-32 ID (#218). Most are RFC 9559 section 5.1. Four are RFC 9559 + /// Appendix A, "Historic Deprecated Elements" (SilentTracks, Slices, TimeSlice, ReferenceFrame): new files must not + /// use them, but older muxers wrote them, so a file can carry one. EditionDisplay and ChapterTrack are not in + /// RFC 9559; they are masters of the Matroska schema (matroska.org) that MatroskaChapters keeps on a save. + /// The Segment's own CRC-32, if any, is not checked: these tests are about the CRCs inside its children. + /// + static readonly HashSet MasterIds = [ + 0x114D9B74, 0x4DBB, // SeekHead, Seek + 0x1549A966, 0x6924, // Info, ChapterTranslate + 0x1F43B675, 0xA0, 0x75A1, 0xA6, // Cluster, BlockGroup, BlockAdditions, BlockMore + 0x1654AE6B, 0xAE, 0x41E4, 0x6624, // Tracks, TrackEntry, BlockAdditionMapping, TrackTranslate + 0xE0, 0x55B0, 0x55D0, 0x7670, 0xE1, // Video, Colour, MasteringMetadata, Projection, Audio + 0xE2, 0xE3, 0xE4, 0xE9, // TrackOperation, TrackCombinePlanes, TrackPlane, TrackJoinBlocks + 0x6D80, 0x6240, 0x5034, 0x5035, 0x47E7, // ContentEncodings, ContentEncoding, ContentCompression, ContentEncryption, ContentEncAESSettings + 0x1C53BB6B, 0xBB, 0xB7, 0xDB, // Cues, CuePoint, CueTrackPositions, CueReference + 0x1941A469, 0x61A7, // Attachments, AttachedFile + 0x1043A770, 0x45B9, 0xB6, 0x80, 0x6944, 0x6911, // Chapters, EditionEntry, ChapterAtom, ChapterDisplay, ChapProcess, ChapProcessCommand + 0x1254C367, 0x7373, 0x63C0, 0x67C8, // Tags, Tag, Targets, SimpleTag + 0x5854, 0x8E, 0xE8, 0xC8, // Appendix A: SilentTracks, Slices, TimeSlice, ReferenceFrame + 0x4520, 0x8F, // Matroska schema, not RFC 9559: EditionDisplay, ChapterTrack + ]; + static bool CrcTreeMatches (ReadOnlySpan body) { var offset = 0; while (offset < body.Length) { if (!EbmlReader.TryRead (body, offset, body.Length, out var element) || element.UnknownSize) return true; + if (!MasterIds.Contains (element.Id)) { + offset = element.End; + continue; + } + var payload = body.Slice (element.DataOffset, (int)element.DataLength); if (payload.Length > 0 && EbmlReader.TryRead (payload, 0, payload.Length, out var first) && first.Id == MatroskaIds.Crc32) { if (!CrcMatches (payload))