Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 8 additions & 9 deletions src/TagLibSharp2/Aac/AacFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ()
{
Expand Down Expand Up @@ -250,8 +250,7 @@ static AacFileReadResult ReadSeekable (Stream stream, ReadOnlyMemory<byte> 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;
}

Expand Down Expand Up @@ -409,7 +408,7 @@ public BinaryData Render (ReadOnlySpan<byte> 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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -648,7 +647,7 @@ public void Dispose ()

Id3v2Tag = null;
ApeTag = null;
_footerOnlyApeTag = null;
_readApeTag = null;
Id3v1Tag = null;
SourcePath = null;
_sourceFileSystem = null;
Expand Down
27 changes: 10 additions & 17 deletions src/TagLibSharp2/Aac/AacTail.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -138,9 +137,6 @@ internal readonly struct AacTail
/// <summary>Gets the trailing APEv2 tag when it was asked for and parsed, or null.</summary>
public ApeTag? ApeTag { get; }

/// <summary>Gets a value indicating whether the APEv2 tag had a header in front of its items.</summary>
public bool ApeHasHeader { get; }

/// <summary>Gets the ID3v1 tag, or null.</summary>
public Id3v1Tag? Id3v1Tag { get; }

Expand All @@ -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;
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -248,7 +241,7 @@ static bool TryApe (AacTailSource source, long tagEnd, long audioStart, bool rea
}

/// <summary>
/// The item checks of <see cref="ApeTag.Parse"/>, without copying a value: the 11-byte-per-item budget, each
/// The item checks of <see cref="ApeTag.Parse(ReadOnlySpan{byte})"/>, without copying a value: the 11-byte-per-item budget, each
/// item by <see cref="ApeTagItem.TryMeasure"/> (the rules <see cref="ApeTagItem.Parse"/> uses), and the count rule.
/// Each item costs one read of at most <see cref="ApeTagItem.MeasureWindow"/> bytes into <paramref name="scratch"/>.
/// </summary>
Expand Down
43 changes: 37 additions & 6 deletions src/TagLibSharp2/Ape/ApeTag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ public sealed class ApeTag : Tag
{
private readonly Dictionary<string, ApeTagItem> _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;

/// <summary>
/// Standard APE key names (Title-case per spec).
/// </summary>
Expand Down Expand Up @@ -157,11 +161,12 @@ public ApeTag ()
}

/// <summary>
/// Creates an APE tag with the specified items.
/// Creates an APE tag with the specified items, read with or without a header.
/// </summary>
private ApeTag (Dictionary<string, ApeTagItem> items)
private ApeTag (Dictionary<string, ApeTagItem> items, bool readWithHeader)
{
_items = items;
_readWithHeader = readWithHeader;
}

/// <inheritdoc/>
Expand Down Expand Up @@ -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.
/// </summary>
public static ApeTagParseResult Parse (ReadOnlySpan<byte> data)
public static ApeTagParseResult Parse (ReadOnlySpan<byte> data) => Parse (data, floor: 0);

/// <summary>
/// <see cref="Parse(ReadOnlySpan{byte})"/> for a tag that cannot start before <paramref name="floor"/>. 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).
/// </summary>
internal static ApeTagParseResult Parse (ReadOnlySpan<byte> data, int floor)
{
var location = ApeTagLocation.Locate (data);
if (!location.Found) {
Expand All @@ -1126,6 +1139,9 @@ public static ApeTagParseResult Parse (ReadOnlySpan<byte> 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);

Expand Down Expand Up @@ -1154,7 +1170,8 @@ public static ApeTagParseResult Parse (ReadOnlySpan<byte> 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.
Expand Down Expand Up @@ -1190,9 +1207,23 @@ internal static bool MoreItems (long offset, long length, int parsed, uint count
public override void Clear () => _items.Clear ();

/// <summary>
/// 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.
/// </summary>
public override BinaryData Render () => RenderWithOptions (includeHeader: false);
public override BinaryData Render () => RenderWithOptions (_readWithHeader ?? false);

/// <summary>
/// The bytes a save writes for <paramref name="tag"/>, or none when it is null, in a file whose read produced
/// <paramref name="readTag"/>. 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
/// <paramref name="defaultHeader"/>: the carrier's layout for a tag it did not read.
/// </summary>
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);
}

/// <summary>
/// Renders the tag to binary data with optional header.
Expand Down
21 changes: 21 additions & 0 deletions src/TagLibSharp2/Ape/ApeTagFooter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,27 @@ public sealed class ApeTagFooter
/// </summary>
public bool HasHeader => (Flags & 0x80000000) != 0;

/// <summary>
/// Whether the tag this footer ends has a header. Bit 31 must be set and <paramref name="preamble"/>, the bytes at
/// <see cref="HeaderStart"/>, 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).
/// </summary>
internal bool HeaderIn (ReadOnlySpan<byte> preamble) =>
HasHeader && preamble.Length >= Magic.Length && preamble[..Magic.Length].SequenceEqual (Magic);

/// <summary>
/// Where the header of the tag that ends at <paramref name="tagEnd"/> 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.
/// </summary>
internal long HeaderStart (long tagEnd) => tagEnd - TagSize - Size;

/// <summary>
/// Whether the tag that ends at <paramref name="tagEnd"/> can have a header: bit 31 claims one, and it would start at
/// or after <paramref name="floor"/>, 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 <see cref="HeaderStart"/> read for <see cref="HeaderIn"/>.
/// </summary>
internal bool CanHaveHeader (long tagEnd, long floor) => HasHeader && HeaderStart (tagEnd) >= floor;

/// <summary>
/// True if the tag contains a footer (bit 30 NOT set).
/// </summary>
Expand Down
Loading
Loading