Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
299527a
refactor: Remove dead and duplicated save-source code
decriptor Dec 1, 2026
a3c0499
fix: Save a file again after a path save (#179)
decriptor Dec 1, 2026
3eec724
fix: Take an ID3v2.4 footer only when its "3DI" is there (#202)
decriptor Dec 3, 2026
b4d85a4
fix: Fail a FLAC save that would drop bytes a metadata block holds (#…
decriptor Dec 3, 2026
aa01762
fix: Report a duration that overflows as unknown (#181, #182, #193)
decriptor Dec 1, 2026
665b459
fix: Read the formats' unknown-duration markers as unknown (#183, #191)
decriptor Dec 1, 2026
1c06714
fix: Read a WavPack block too small for its header as no block (#201)
decriptor Dec 3, 2026
18dab68
fix: Walk WAV and AIFF chunks by one rule (#192, #197, #203)
decriptor Dec 2, 2026
471a08e
fix: Read rate fields without wrapping (#194, #198)
decriptor Dec 2, 2026
d3e2909
fix: Return a failure, never throw, from an AIFF save that cannot be …
decriptor Dec 2, 2026
ba8cc13
fix: Save an AIFF or WAV file again after a path save over its source…
decriptor Dec 3, 2026
66b0e4d
fix: Read the Ogg FLAC duration from the granule when STREAMINFO has …
decriptor Dec 1, 2026
5f723ae
fix: Read and keep an Ogg page with no segments at the end (#189)
decriptor Dec 2, 2026
2b7843f
fix: Carry every ASF header object across a save, whatever the count …
decriptor Dec 3, 2026
a01face
fix: Read the same Ogg duration when a header page ends the stream (#…
decriptor Dec 2, 2026
8fe8c86
fix: Carry every Ogg audio page across a save, or fail (#199)
decriptor Dec 2, 2026
5bc42b9
fix: Carry the bytes after the last whole Ogg page across a save (#215)
decriptor Dec 3, 2026
285a2a2
fix: Step back past a -1 granule position to find the duration (#185)
decriptor Dec 1, 2026
3824c1c
fix: Read an untargeted Matroska TITLE as the title alone (#221)
decriptor Dec 4, 2026
42fe22f
fix: Write a Matroska clear after a save from the same object (#244)
decriptor Dec 4, 2026
162a44f
fix: Keep a Matroska save from growing quadratically with its picture…
decriptor Dec 4, 2026
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
32 changes: 30 additions & 2 deletions CHANGELOG.md

Large diffs are not rendered by default.

170 changes: 109 additions & 61 deletions src/TagLibSharp2/Aac/AacFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ internal void MarkPicturesSkipped ()
// as ffmpeg writes it; some readers (mediainfo) find the tag only through the header.
ApeTag? _readApeTag;

// The layout the file holds for _readApeTag after a save over the source wrote it; null after a read, where the
// tag's own read layout is the file's.
bool? _readApeHeader;

AacFile ()
{
}
Expand All @@ -93,7 +97,8 @@ internal void MarkPicturesSkipped ()
public Id3v1Tag? Id3v1Tag { get; set; }

/// <summary>
/// Gets the size in bytes of the ID3v2 tag that was read (0 if none).
/// Gets the size in bytes of the ID3v2 tag of the file the object describes (0 if none): the one it read or, after
/// a save over its source, the one that save wrote.
/// </summary>
public int Id3v2Size { get; private set; }

Expand Down Expand Up @@ -220,7 +225,8 @@ static AacFileReadResult ReadSeekable (Stream stream, ReadOnlyMemory<byte> bytes
var prefix = StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize);
var header = Id3v2Header.Read (prefix);
if (header.IsSuccess) {
audioStart = Math.Min ((long)header.Header.TotalSize, length);
// The audio starts after the tag, and after its footer only when one is there (#202).
audioStart = Math.Min ((long)header.Header.TotalSizeIn (stream, 0), length);
stream.Position = 0;
var tag = options.SkipPictures
? Id3v2Tag.ReadWithoutPictures (stream, audioStart)
Expand Down Expand Up @@ -251,6 +257,7 @@ void TakeTags (AacTail tail)
{
ApeTag = tail.ApeTag;
_readApeTag = tail.ApeTag;
_readApeHeader = null;
Id3v1Tag = tail.Id3v1Tag;
}

Expand Down Expand Up @@ -363,22 +370,22 @@ public static bool IsValidFormat (ReadOnlySpan<byte> data)
internal static bool IsValidFormat (Stream stream)
{
stream.Position = 0;
var prefix = StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize);
var start = StreamStart (prefix);
var header = Id3v2Header.Read (StreamBytes.ReadAtMost (stream, Id3v2Header.HeaderSize));
var start = header.IsSuccess ? (int)Math.Min (header.Header.TotalSizeIn (stream, 0), int.MaxValue) : 0;
return AacStream.FindStart (stream, start, SearchBytes (start), -1, out _) >= 0;
}

// A leading ID3v2 tag says this is an audio file, so the first frame may sit after padding, as
// AacFile.Read allows. Without a tag only offset 0 counts; the .aac extension covers the rest.
static int SearchBytes (int start) => start > 0 ? AacStream.FirstFrameSearchBytes : 1;

// The byte after a leading ID3v2 tag (header, body, and v2.4 footer), or 0 without one.
// The byte after a leading ID3v2 tag (header, body, and a v2.4 footer that is there), or 0 without one.
static int StreamStart (ReadOnlySpan<byte> data)
{
var header = Id3v2Header.Read (data);
if (!header.IsSuccess)
return 0;
var total = header.Header.TotalSize;
var total = header.Header.TotalSizeIn (data);
return total > int.MaxValue ? int.MaxValue : (int)total;
}

Expand All @@ -402,37 +409,88 @@ public BinaryData Render (ReadOnlySpan<byte> originalData)
_creation?.Settle ([Id3v2Tag, ApeTag, Id3v1Tag]);
if (Id3v1Refusal () is string refusal)
throw new InvalidOperationException (refusal);
// The read's tail rule against the read's audio start, so a save keeps every frame the read counted.
var audioStart = Math.Min (Id3v2Size, originalData.Length);
var tail = AacTail.Locate (new AacTailSource (originalData), Math.Min (_audioStart, originalData.Length), readTags: false);
var audioEnd = Math.Max (tail.AudioEnd, audioStart);
return Assemble (originalData, Plan (new AacTailSource (originalData)));
}

var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty;
var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true);
var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty;
static BinaryData Assemble (ReadOnlySpan<byte> originalData, Written written)
{
using var builder = new BinaryDataBuilder ((int)written.Length);
builder.Add (written.Id3v2);
builder.Add (originalData.Slice ((int)written.AudioStart, (int)written.AudioLength));
builder.Add (written.Ape);
builder.Add (originalData.Slice ((int)written.LyricsStart, (int)written.LyricsLength));
builder.Add (written.Id3v1);
return builder.ToBinaryData ();
}

// The file a save writes: the current tags, the audio and any Lyrics3 block in front of ID3v1, both copied from the
// file at the offsets the object describes.
readonly record struct Written (
BinaryData Id3v2,
long AudioStart,
long AudioLength,
BinaryData Ape,
bool ApeHeader,
long LyricsStart,
long LyricsLength,
BinaryData Id3v1)
{
public long Length => Id3v2.Length + AudioLength + Ape.Length + LyricsLength + Id3v1.Length;
}

// The read's tail rule against the read's audio start, so a save keeps every frame the read counted.
Written Plan (AacTailSource source)
{
var fileLength = source.Length;
var audioStart = Math.Min ((long)Id3v2Size, fileLength);
var tail = AacTail.Locate (source, Math.Min (_audioStart, fileLength), readTags: false);
var audioEnd = Math.Max (tail.AudioEnd, audioStart);

// Lyrics3 belongs in front of ID3v1 and goes when that tag goes.
var lyrics = Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart
? originalData[(int)tail.LyricsStart..(int)tail.Id3v1Start]
: [];

var audio = originalData[audioStart..(int)audioEnd];
using var builder = new BinaryDataBuilder (id3v2.Length + audio.Length + ape.Length + lyrics.Length + id3v1.Length);
builder.Add (id3v2);
builder.Add (audio);
builder.Add (ape);
builder.Add (lyrics);
builder.Add (id3v1);
return builder.ToBinaryData ();
var keepsLyrics = Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart;
var apeHeader = ApeTag is not null && ApeTag.HeaderForSave (ApeTag, _readApeTag, _readApeHeader, defaultHeader: true);
return new Written (
Id3v2Tag?.Render () ?? BinaryData.Empty,
audioStart,
audioEnd - audioStart,
ApeTag?.RenderWithOptions (apeHeader) ?? BinaryData.Empty,
apeHeader,
keepsLyrics ? tail.LyricsStart : 0,
keepsLyrics ? tail.Id3v1Start - tail.LyricsStart : 0,
Id3v1Tag?.Render () ?? BinaryData.Empty);
}

// A save that rewrote the source leaves the object describing the file it wrote (#179), as a read of it would: the
// audio starts after the ID3v2 tag written (at the start when none was), the tail is found from there, and the
// APEv2 tag written is the tag read, with the layout it was written with: the file's, not the one it was parsed with.
FileWriteResult Adopt (FileWriteResult result, Written written, IFileSystem? fileSystem)
{
var length = written.Length;
if (!result.IsSuccess
|| !SavedOverSource.Holds (SourcePath, fileSystem, length,
new WrittenBytes (0, written.Id3v2.Memory),
new WrittenBytes (written.Id3v2.Length + written.AudioLength, written.Ape.Memory),
new WrittenBytes (length - written.Id3v1.Length, written.Id3v1.Memory)))
return result;

_audioStart = written.Id3v2.Length;
Id3v2Size = written.Id3v2.Length;
_readApeTag = ApeTag;
_readApeHeader = written.ApeHeader;
Source.Rewrote (length);
return result;
}

async Task<FileWriteResult> Adopt (Task<FileWriteResult> save, Written written, IFileSystem? fileSystem) =>
Adopt (await save.ConfigureAwait (false), written, fileSystem);

/// <summary>
/// Saves the file to the specified path using atomic write.
/// </summary>
/// <param name="path">The target file path.</param>
/// <param name="originalData">The bytes of the file this object was read from; the payload is taken from them at the
/// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and
/// nothing is written.</param>
/// <param name="originalData">The bytes of the file this object was read from or, after a save over its source, of the
/// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a
/// file it saved elsewhere among them, fail with a result, and nothing is written.</param>
/// <param name="fileSystem">Optional file system abstraction for testing.</param>
/// <returns>A result indicating success or failure.</returns>
public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData, IFileSystem? fileSystem = null)
Expand All @@ -446,20 +504,22 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (Source.Refuse ("AAC", originalData.Length) is { } mismatch)
return mismatch;

var rendered = Render (originalData);
var written = Plan (new AacTailSource (originalData));
var rendered = Assemble (originalData, written);
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render AAC file");

return AtomicFileWriter.Write (path, rendered.Span, fileSystem ?? _sourceFileSystem);
fileSystem ??= _sourceFileSystem;
return Adopt (AtomicFileWriter.Write (path, rendered.Span, fileSystem), written, fileSystem);
}

/// <summary>
/// Asynchronously saves the file to the specified path using atomic write.
/// </summary>
/// <param name="path">The target file path.</param>
/// <param name="originalData">The bytes of the file this object was read from; the payload is taken from them at the
/// offsets the read found. Bytes of any other length, a file it has saved since among them, fail with a result, and
/// nothing is written.</param>
/// <param name="originalData">The bytes of the file this object was read from or, after a save over its source, of the
/// file that save wrote; the payload is taken from them at the offsets of that file. Bytes of any other length, a
/// file it saved elsewhere among them, fail with a result, and nothing is written.</param>
/// <param name="fileSystem">Optional file system abstraction for testing.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>A task containing a result indicating success or failure.</returns>
Expand All @@ -478,11 +538,13 @@ public Task<FileWriteResult> SaveToFileAsync (
if (Source.Refuse ("AAC", originalData.Length) is { } mismatch)
return Task.FromResult (mismatch);

var rendered = Render (originalData.Span);
var written = Plan (new AacTailSource (originalData.Span));
var rendered = Assemble (originalData.Span, written);
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render AAC file"));

return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem ?? _sourceFileSystem, cancellationToken);
fileSystem ??= _sourceFileSystem;
return Adopt (AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken), written, fileSystem);
}

/// <summary>
Expand Down Expand Up @@ -561,27 +623,12 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
try {
if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error))
return error;
if (Source.Refuse ("AAC", source!.Length, "the source file") is { } changed)
return changed;

var opened = source!;
var fileLength = opened.Length;
var audioStart = Math.Min ((long)Id3v2Size, fileLength);
var tail = AacTail.Locate (
new AacTailSource (opened.Stream, fileLength),
Math.Min (_audioStart, fileLength),
readTags: false);
var audioEnd = Math.Max (tail.AudioEnd, audioStart);
var id3v2 = Id3v2Tag?.Render () ?? BinaryData.Empty;
var ape = ApeTag.RenderForSave (ApeTag, _readApeTag, defaultHeader: true);
var id3v1 = Id3v1Tag?.Render () ?? BinaryData.Empty;
long lyricsStart = 0;
long lyricsLength = 0;
if (Id3v1Tag is not null && tail.LyricsStart >= audioEnd && tail.Id3v1Start > tail.LyricsStart) {
lyricsStart = tail.LyricsStart;
lyricsLength = tail.Id3v1Start - tail.LyricsStart;
}

var audioLength = audioEnd - audioStart;
if (id3v2.IsEmpty && audioLength <= 0 && ape.IsEmpty && lyricsLength <= 0 && id3v1.IsEmpty)
var written = Plan (new AacTailSource (opened.Stream, opened.Length));
if (written.Length == 0)
return FileWriteResult.Failure ("Failed to render AAC file");

if (cancellationToken.IsCancellationRequested)
Expand All @@ -590,15 +637,15 @@ FileWriteResult SaveFromSource (string destinationPath, IFileSystem? fileSystem,
chunk = StreamCopy.Rent ();
var copyBuffer = chunk;
var stream = opened.Stream;
var written = PathSave.Replace (destinationPath, opened, output => {
StreamCopy.Write (output, id3v2.Span, copyBuffer);
CopyRange (stream, output, audioStart, audioLength, copyBuffer);
StreamCopy.Write (output, ape.Span, copyBuffer);
CopyRange (stream, output, lyricsStart, lyricsLength, copyBuffer);
StreamCopy.Write (output, id3v1.Span, copyBuffer);
var saved = PathSave.Replace (destinationPath, opened, output => {
StreamCopy.Write (output, written.Id3v2.Span, copyBuffer);
CopyRange (stream, output, written.AudioStart, written.AudioLength, copyBuffer);
StreamCopy.Write (output, written.Ape.Span, copyBuffer);
CopyRange (stream, output, written.LyricsStart, written.LyricsLength, copyBuffer);
StreamCopy.Write (output, written.Id3v1.Span, copyBuffer);
});
source = null;
return written;
return Adopt (saved, written, fileSystem);
} finally {
source?.Dispose ();
if (chunk is not null)
Expand Down Expand Up @@ -648,6 +695,7 @@ public void Dispose ()
Id3v2Tag = null;
ApeTag = null;
_readApeTag = null;
_readApeHeader = null;
Id3v1Tag = null;
SourcePath = null;
_sourceFileSystem = null;
Expand Down
6 changes: 3 additions & 3 deletions src/TagLibSharp2/Aac/AacStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ static bool TryReadAdif (Stream stream, long start, long end, out AacAudioProper

var payload = end - start - header.Size;
var duration = header.Bitrate > 0 && payload > 0
? TimeSpan.FromTicks ((long)Math.Round ((double)payload * 8 * TimeSpan.TicksPerSecond / header.Bitrate))
? Durations.FromTicks ((double)payload * 8 * TimeSpan.TicksPerSecond / header.Bitrate)
: TimeSpan.Zero;
var program = header.Program;
properties = new AacAudioProperties (
Expand Down Expand Up @@ -391,9 +391,9 @@ static bool TryWalkAdts (ScanReader reader, long first, long end, out AacAudioPr

var sampleRate = stream0.SampleRate;
var samples = (double)blocks * AdtsHeader.SamplesPerBlock;
var duration = TimeSpan.FromTicks ((long)Math.Round (samples * TimeSpan.TicksPerSecond / sampleRate));
var duration = Durations.FromTicks (samples * TimeSpan.TicksPerSecond / sampleRate);
var bitrate = duration > TimeSpan.Zero
? (int)(bytes * 8 / duration.TotalSeconds / 1000)
? Rates.Kbps (bytes * 8 / duration.TotalSeconds)
: 0;
properties = new AacAudioProperties (
duration,
Expand Down
4 changes: 2 additions & 2 deletions src/TagLibSharp2/Aiff/AiffAudioProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public class AiffAudioProperties : IMediaProperties

// Calculate duration
if (sampleRate > 0 && sampleFrames > 0)
Duration = TimeSpan.FromSeconds ((double)sampleFrames / sampleRate);
Duration = Durations.FromSeconds ((double)sampleFrames / sampleRate);
else
Duration = TimeSpan.Zero;

Expand Down Expand Up @@ -155,7 +155,7 @@ public static bool TryParse (BinaryData commData, out AiffAudioProperties? prope

// Parse sample rate from 80-bit extended float
var sampleRateDouble = ExtendedFloat.ToDouble (commData.Slice (8, 10));
int sampleRate = (int)Math.Round (sampleRateDouble);
var sampleRate = Rates.SampleRate (sampleRateDouble);

// Parse AIFC compression fields if present
string? compressionType = null;
Expand Down
39 changes: 22 additions & 17 deletions src/TagLibSharp2/Aiff/AiffChunk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ public class AiffChunk
/// </remarks>
public long TotalSize => HeaderSize + (long)Size + (Size % 2 == 1 ? 1 : 0);

/// <summary>
/// The bytes <see cref="Render"/> writes: the header, the bytes present and a pad to an even length. A chunk read
/// with a size past its bytes (a cut-off file, or a placeholder size) is written with the size of its bytes (#197),
/// as a WAV chunk is.
/// </summary>
internal long RenderedSize => HeaderSize + (long)Data.Length + (Data.Length & 1);

AiffChunk (string fourCC, uint size, BinaryData data)
{
FourCC = fourCC;
Expand Down Expand Up @@ -79,14 +86,14 @@ public AiffChunk (string fourCC, BinaryData data)
/// <returns>The complete chunk including header and padding.</returns>
public BinaryData Render ()
{
var needsPadding = Size % 2 == 1;
using var builder = new BinaryDataBuilder (HeaderSize + (int)Size + (needsPadding ? 1 : 0));
var needsPadding = (Data.Length & 1) == 1;
using var builder = new BinaryDataBuilder ((int)RenderedSize);

// Write FourCC
builder.AddStringLatin1 (FourCC);

// Write size (big-endian)
builder.AddUInt32BE (Size);
// Write the size of the bytes present (big-endian)
builder.AddUInt32BE ((uint)Data.Length);

// Write data
builder.Add (Data);
Expand All @@ -105,7 +112,15 @@ public BinaryData Render ()
/// <param name="offset">The offset where the chunk starts.</param>
/// <param name="chunk">The parsed chunk, or null if parsing failed.</param>
/// <returns>True if parsing succeeded; otherwise, false.</returns>
public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk)
public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk) =>
TryParse (data, offset, data.Length, out chunk);

/// <summary>
/// <see cref="TryParse(BinaryData, int, out AiffChunk?)"/> within a FORM that ends at <paramref name="end"/>: the
/// chunk holds <see cref="ChunkExtent.PresentBytes"/>, the rule the stream walk applies too (#197). A chunk whose
/// size runs past them keeps that size and the bytes present.
/// </summary>
internal static bool TryParse (BinaryData data, int offset, int end, out AiffChunk? chunk)
{
chunk = null;

Expand All @@ -125,18 +140,8 @@ public static bool TryParse (BinaryData data, int offset, out AiffChunk? chunk)
(span[offset + 6] << 8) |
span[offset + 7]);

// Overflow protection: reject chunks claiming > int.MaxValue size
if (size > int.MaxValue)
return false;

// Verify we have enough data
if (data.Length < offset + HeaderSize + size)
return false;

// Extract chunk data (safe cast after overflow check)
var chunkData = data.Slice (offset + HeaderSize, (int)size);

chunk = new AiffChunk (fourCC, size, chunkData);
var present = (int)ChunkExtent.PresentBytes (size, offset + HeaderSize, Math.Min (end, data.Length));
chunk = new AiffChunk (fourCC, size, present > 0 ? data.Slice (offset + HeaderSize, present) : BinaryData.Empty);
return true;
}
}
Loading
Loading