From ff2783dfe7a52ae241eb459cbb456677ac91a96f Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Mon, 16 Nov 2026 18:32:34 -0700 Subject: [PATCH 1/3] feat: Read MP3, FLAC, and WAV without the audio payload MediaFile.Read and ReadAsync accept a stream. A seekable MP3, FLAC, or WAV is read from its tags and headers, so a scan does not allocate the audio. A stream that cannot seek is copied once. --- src/TagLibSharp2/Core/MediaFile.cs | 167 +++++++- src/TagLibSharp2/Core/StreamBytes.cs | 101 +++++ src/TagLibSharp2/Mpeg/Mp3File.cs | 192 ++++++++- src/TagLibSharp2/Mpeg/MpegAudioProperties.cs | 34 +- src/TagLibSharp2/Riff/RiffChunk.cs | 7 + src/TagLibSharp2/Riff/RiffFile.cs | 83 ++++ src/TagLibSharp2/Riff/WavFile.cs | 112 +++++- src/TagLibSharp2/Xiph/FlacFile.cs | 98 ++++- .../Core/MediaFileAsyncTests.cs | 4 +- .../Core/MediaFileStreamTests.cs | 307 ++++++++++++++ .../Core/WindowedReadDefectTests.cs | 375 ++++++++++++++++++ .../Docs/DocExamplesCompileTests.cs | 4 +- .../TagLibSharp2.PublicApi.verified.txt | 2 + 13 files changed, 1460 insertions(+), 26 deletions(-) create mode 100644 src/TagLibSharp2/Core/StreamBytes.cs create mode 100644 tests/TagLibSharp2.Tests/Core/MediaFileStreamTests.cs create mode 100644 tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs index 7c6b85f..cad0bac 100644 --- a/src/TagLibSharp2/Core/MediaFile.cs +++ b/src/TagLibSharp2/Core/MediaFile.cs @@ -41,7 +41,7 @@ namespace TagLibSharp2.Core; /// /// Reading and Modifying Tags /// -/// Use or to open a file. The result contains +/// Use or to open a file. The result contains /// the strongly-typed file object (e.g., , /// ) with Tag and audio property access. /// Modify tag properties directly on the file object. @@ -148,11 +148,39 @@ public static MediaFileResult Read (string path, IFileSystem? fileSystem = null) ArgumentNullException.ThrowIfNull (path); #endif - var readResult = FileHelper.SafeReadAllBytes (path, fileSystem); - if (!readResult.IsSuccess) - return MediaFileResult.Failure (readResult.Error!); + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (!fs.FileExists (path)) + return MediaFileResult.Failure ($"File not found: {path}"); + + try { + using var stream = fs.OpenRead (path); + return Read (stream, path, path, fs); + } catch (IOException ex) { + return MediaFileResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return MediaFileResult.Failure ($"Access denied: {ex.Message}"); + } + } - return ReadCore (readResult.Data!.Value, path, fileSystem, rememberPath: true); + /// + /// Reads a media file from a stream. + /// + /// The stream to read. The caller keeps ownership of it. + /// Optional file name used when the bytes do not identify a format. + /// A result containing the parsed file or an error. + /// + /// A seekable stream is read by the ranges the format needs. MP3, FLAC, and WAV + /// do not read the audio payload. A stream that cannot seek is copied once. + /// + public static MediaFileResult Read (Stream stream, string? pathHint = null) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (stream is null) + throw new ArgumentNullException (nameof (stream)); +#else + ArgumentNullException.ThrowIfNull (stream); +#endif + return Read (stream, pathHint, sourcePath: null, fileSystem: null); } /// @@ -174,12 +202,131 @@ public static async Task ReadAsync ( ArgumentNullException.ThrowIfNull (path); #endif - var readResult = await FileHelper.SafeReadAllBytesAsync (path, fileSystem, cancellationToken) - .ConfigureAwait (false); - if (!readResult.IsSuccess) - return MediaFileResult.Failure (readResult.Error!); + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (!fs.FileExists (path)) + return MediaFileResult.Failure ($"File not found: {path}"); + + try { + using var stream = fs.OpenRead (path); + return await ReadAsync (stream, path, path, fs, cancellationToken).ConfigureAwait (false); + } catch (IOException ex) { + return MediaFileResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return MediaFileResult.Failure ($"Access denied: {ex.Message}"); + } catch (OperationCanceledException) { + return MediaFileResult.Failure ("Operation was cancelled"); + } + } + + /// + /// Reads a media file from a stream asynchronously. + /// + /// The stream to read. The caller keeps ownership of it. + /// Optional file name used when the bytes do not identify a format. + /// Cancellation token. + /// A result containing the parsed file or an error. + /// + /// A seekable stream is read by the ranges the format needs. MP3, FLAC, and WAV + /// do not read the audio payload. A stream that cannot seek is copied once. + /// + public static Task ReadAsync ( + Stream stream, + string? pathHint = null, + CancellationToken cancellationToken = default) + { +#if NETSTANDARD2_0 || NETSTANDARD2_1 + if (stream is null) + throw new ArgumentNullException (nameof (stream)); +#else + ArgumentNullException.ThrowIfNull (stream); +#endif + return ReadAsync (stream, pathHint, sourcePath: null, fileSystem: null, cancellationToken); + } + + static MediaFileResult Read (Stream stream, string? pathHint, string? sourcePath, IFileSystem? fileSystem) + { + if (!stream.CanSeek) + return RememberMatroskaSource (ReadFromData (StreamBytes.ReadToEnd (stream), pathHint), sourcePath, fileSystem); + + if (stream.Position != 0) + stream.Position = 0; + + var peek = StreamBytes.ReadAtMost (stream, 4096); + stream.Position = 0; + return RememberMatroskaSource ( + OpenDetected (DetectFormat (peek, pathHint), stream, sourcePath, fileSystem, pathHint), + sourcePath, + fileSystem); + } + + static async Task ReadAsync ( + Stream stream, + string? pathHint, + string? sourcePath, + IFileSystem? fileSystem, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested (); + if (!stream.CanSeek) + return RememberMatroskaSource ( + ReadFromData (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false), pathHint), + sourcePath, + fileSystem); + + if (stream.Position != 0) + stream.Position = 0; + + var peek = await StreamBytes.ReadAtMostAsync (stream, 4096, cancellationToken).ConfigureAwait (false); + stream.Position = 0; + var format = DetectFormat (peek, pathHint); + var result = format switch { + MediaFormat.Mp3 => FromMp3 (await Mp3File.ReadAsync (stream, cancellationToken).ConfigureAwait (false)), + MediaFormat.Flac => FromFlac (await FlacFile.ReadAsync (stream, cancellationToken).ConfigureAwait (false)), + MediaFormat.Wav => FromWav (WavFile.Read (stream, sourcePath, fileSystem)), + _ => ReadFromData (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false), pathHint) + }; + return RememberMatroskaSource (result, sourcePath, fileSystem); + } + + static MediaFileResult OpenDetected (MediaFormat format, Stream stream, string? sourcePath, IFileSystem? fileSystem, string? pathHint) => + format switch { + MediaFormat.Mp3 => FromMp3 (Mp3File.Read (stream)), + MediaFormat.Flac => FromFlac (FlacFile.Read (stream)), + MediaFormat.Wav => FromWav (WavFile.Read (stream, sourcePath, fileSystem)), + _ => ReadFromData (StreamBytes.ReadToEnd (stream), pathHint) + }; + + // ReadFromData's path is only an extension hint. A path read can save Matroska back to that file. + static MediaFileResult RememberMatroskaSource (MediaFileResult result, string? sourcePath, IFileSystem? fileSystem) + { + if (sourcePath is not null && result.IsSuccess && result.File is MatroskaFile matroska) + matroska.SetSourcePath (sourcePath, fileSystem); + return result; + } + + static MediaFileResult FromMp3 (Mp3FileReadResult result) + { + if (!result.IsSuccess || result.File is null) + return MediaFileResult.Failure (result.Error ?? "Failed to parse MP3 file"); + return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Mp3); + } - return ReadCore (readResult.Data!.Value, path, fileSystem, rememberPath: true); + static MediaFileResult FromFlac (FlacFileReadResult result) + { + if (!result.IsSuccess || result.File is null) + return MediaFileResult.Failure (result.Error ?? "Failed to parse FLAC file"); + return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Flac); + } + + static MediaFileResult FromWav (WavFileReadResult result) + { + if (!result.IsSuccess || result.File is null) + return MediaFileResult.Failure (result.Error ?? "Failed to parse WAV file"); + + Tag? tag = result.File.Id3v2Tag is not null + ? result.File.Id3v2Tag + : result.File.InfoTag; + return MediaFileResult.Success (result.File, tag, MediaFormat.Wav); } /// diff --git a/src/TagLibSharp2/Core/StreamBytes.cs b/src/TagLibSharp2/Core/StreamBytes.cs new file mode 100644 index 0000000..3b0e30d --- /dev/null +++ b/src/TagLibSharp2/Core/StreamBytes.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +namespace TagLibSharp2.Core; + +/// +/// Reads a bounded number of bytes from a stream. A short read is the end of the stream. +/// +internal static class StreamBytes +{ + public static byte[] ReadAtMost (Stream stream, int count) + { + if (count <= 0) + return []; + + var buffer = new byte[count]; + var read = Read (stream, buffer, 0, count); + return read == count ? buffer : Trim (buffer, read); + } + + public static async Task ReadAtMostAsync (Stream stream, int count, CancellationToken cancellationToken) + { + if (count <= 0) + return []; + + var buffer = new byte[count]; + var read = await ReadAsync (stream, buffer, 0, count, cancellationToken).ConfigureAwait (false); + return read == count ? buffer : Trim (buffer, read); + } + + public static byte[] ReadToEnd (Stream stream) + { + if (stream.CanSeek) { + var remaining = stream.Length - stream.Position; + if (remaining <= 0) + return []; + if (remaining > int.MaxValue) + throw new IOException ("File is too large to read into memory"); + return ReadAtMost (stream, (int)remaining); + } + + using var copy = new MemoryStream (); + stream.CopyTo (copy); + return copy.ToArray (); + } + + public static async Task ReadToEndAsync (Stream stream, CancellationToken cancellationToken) + { + if (stream.CanSeek) { + var remaining = stream.Length - stream.Position; + if (remaining <= 0) + return []; + if (remaining > int.MaxValue) + throw new IOException ("File is too large to read into memory"); + return await ReadAtMostAsync (stream, (int)remaining, cancellationToken).ConfigureAwait (false); + } + + using var copy = new MemoryStream (); + await stream.CopyToAsync (copy, 81920, cancellationToken).ConfigureAwait (false); + return copy.ToArray (); + } + + static int Read (Stream stream, byte[] buffer, int offset, int count) + { + var read = 0; + while (read < count) { + var n = stream.Read (buffer, offset + read, count - read); + if (n == 0) + break; + read += n; + } + + return read; + } + + static async Task ReadAsync (Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + var read = 0; + while (read < count) { +#if NETSTANDARD2_0 + var n = await stream.ReadAsync (buffer, offset + read, count - read, cancellationToken).ConfigureAwait (false); +#else + var n = await stream.ReadAsync (buffer.AsMemory (offset + read, count - read), cancellationToken).ConfigureAwait (false); +#endif + if (n == 0) + break; + read += n; + } + + return read; + } + + static byte[] Trim (byte[] buffer, int length) + { + if (length == 0) + return []; + var exact = new byte[length]; + Array.Copy (buffer, exact, length); + return exact; + } +} diff --git a/src/TagLibSharp2/Mpeg/Mp3File.cs b/src/TagLibSharp2/Mpeg/Mp3File.cs index 906f2c0..402821c 100644 --- a/src/TagLibSharp2/Mpeg/Mp3File.cs +++ b/src/TagLibSharp2/Mpeg/Mp3File.cs @@ -34,7 +34,7 @@ public sealed class Mp3File : IMediaFile /// /// /// This is set when using or . - /// It is null when the file was read from binary data using . + /// It is null when the file was read from binary data using . /// public string? SourcePath { get; private set; } @@ -358,6 +358,196 @@ public static Mp3FileReadResult Read (ReadOnlySpan data) return Mp3FileReadResult.Success (file); } + /// + /// Reads an MP3 from a stream. A seekable stream supplies the tag, the first + /// audio frames, and the ID3v1 footer. The bytes between them stay unread. + /// + internal static Mp3FileReadResult Read (Stream stream) + { + if (!stream.CanSeek) + return Read (StreamBytes.ReadToEnd (stream)); + + return ReadWindow (stream, static (source, count) => StreamBytes.ReadAtMost (source, count)); + } + + internal static async Task ReadAsync (Stream stream, CancellationToken cancellationToken) + { + if (!stream.CanSeek) + return Read (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false)); + + if (stream.Position != 0) + stream.Position = 0; + + var length = stream.Length; + if (length < 4) + return Mp3FileReadResult.Failure ("Invalid MP3 file: data too short"); + + var window = new Mp3Window (length); + while (true) { + cancellationToken.ThrowIfCancellationRequested (); + switch (window.Next (stream.Position, out var count, out var seek)) { + case Mp3WindowStep.ReadPrefix: + window.AddPrefix (await StreamBytes.ReadAtMostAsync (stream, count, cancellationToken).ConfigureAwait (false)); + break; + case Mp3WindowStep.ReadTail: + var asyncTail = await StreamBytes.ReadAtMostAsync (stream, count, cancellationToken).ConfigureAwait (false); + if (TryFinishWindow (window, asyncTail, out var asyncParsed)) + return asyncParsed; + stream.Position = 0; + return Read (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false)); + case Mp3WindowStep.Seek: + stream.Position = seek; + window.NoteSeek (); + break; + default: + return Read (window.Prefix ()); + } + } + } + + static Mp3FileReadResult ReadWindow (Stream stream, Func read) + { + if (stream.Position != 0) + stream.Position = 0; + + var length = stream.Length; + if (length < 4) + return Mp3FileReadResult.Failure ("Invalid MP3 file: data too short"); + + var window = new Mp3Window (length); + while (true) { + switch (window.Next (stream.Position, out var count, out var seek)) { + case Mp3WindowStep.ReadPrefix: + window.AddPrefix (read (stream, count)); + break; + case Mp3WindowStep.ReadTail: + if (TryFinishWindow (window, read (stream, count), out var parsed)) + return parsed; + stream.Position = 0; + return Read (StreamBytes.ReadToEnd (stream)); + case Mp3WindowStep.Seek: + stream.Position = seek; + window.NoteSeek (); + break; + default: + return Read (window.Prefix ()); + } + } + } + + static bool TryFinishWindow (Mp3Window window, byte[] tail, out Mp3FileReadResult result) + { + result = ReadWindows (window.Prefix (), tail, window.Length, out var needsEntireFile); + return !needsEntireFile; + } + + enum Mp3WindowStep + { + ReadPrefix, + ReadTail, + Seek, + ParsePrefix + } + + /// + /// The seekable MP3 read, shared by the sync and async entry points. + /// The audio between the probe and the ID3v1 footer stays unread. + /// + sealed class Mp3Window + { + const int AudioProbeBytes = 32 * 1024; + + readonly List _prefix = []; + readonly long _length; + int _stage; + + public Mp3Window (long length) => _length = length; + + public long Length => _length; + + public byte[] Prefix () => _prefix.ToArray (); + + public Mp3WindowStep Next (long position, out int count, out long seek) + { + count = 0; + seek = 0; + switch (_stage) { + case 0: + count = Id3v2Header.HeaderSize; + return Mp3WindowStep.ReadPrefix; + case 1: + count = Id3Remainder (); + if (count > 0) + return Mp3WindowStep.ReadPrefix; + _stage = 2; + goto case 2; + case 2: + count = AudioProbeBytes; + return Mp3WindowStep.ReadPrefix; + case 3: + if (position < _length && _length - position <= Id3v1Size) { + count = (int)(_length - position); + return Mp3WindowStep.ReadPrefix; + } + + _stage = 4; + goto case 4; + case 4: + if (position >= _length) + return Mp3WindowStep.ParsePrefix; + seek = _length - Id3v1Size; + return Mp3WindowStep.Seek; + default: + count = Id3v1Size; + return Mp3WindowStep.ReadTail; + } + } + + public void AddPrefix (byte[] data) + { + if (data.Length > 0) + _prefix.AddRange (data); + _stage++; + } + + public void NoteSeek () => _stage++; + + int Id3Remainder () + { + var header = Id3v2Header.Read (_prefix.ToArray ()); + if (!header.IsSuccess) + return 0; + var total = Math.Min ((long)header.Header.TotalSize, _length); + return (int)Math.Max (0, total - _prefix.Count); + } + } + + static Mp3FileReadResult ReadWindows (byte[] prefix, byte[] tail, long fileLength, out bool needsEntireFile) + { + needsEntireFile = false; + var file = new Mp3File (); + var id3v2Result = Id3v2Tag.Read (prefix); + if (id3v2Result.IsSuccess) { + file.Id3v2Tag = id3v2Result.Tag; + file.Id3v2Size = id3v2Result.BytesConsumed; + } + + if (tail.Length >= Id3v1Size) { + var id3v1Result = Id3v1Tag.Read (tail.AsSpan (tail.Length - Id3v1Size, Id3v1Size)); + if (id3v1Result.IsSuccess) + file.Id3v1Tag = id3v1Result.Tag; + } + + if (MpegAudioProperties.TryParse (new BinaryData (prefix), file.Id3v2Size, fileLength, out var audioProps, out needsEntireFile)) + file.Properties = audioProps; + else if (needsEntireFile) { + file.Dispose (); + return Mp3FileReadResult.Failure ("The MPEG frame count has to be read from the audio"); + } + + return Mp3FileReadResult.Success (file); + } + /// /// Attempts to read an MP3 file from binary data. /// diff --git a/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs b/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs index 42d46e6..82e63e6 100644 --- a/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs +++ b/src/TagLibSharp2/Mpeg/MpegAudioProperties.cs @@ -110,9 +110,26 @@ public sealed class MpegAudioProperties : IMediaProperties /// The offset where audio data starts (after ID3v2). /// The parsed properties, or null if parsing failed. /// True if parsing succeeded, false otherwise. - public static bool TryParse (BinaryData data, int audioOffset, out MpegAudioProperties? properties) + public static bool TryParse (BinaryData data, int audioOffset, out MpegAudioProperties? properties) => + TryParse (data, audioOffset, data.Length, out properties, out _); + + /// + /// Parses audio properties when is the real file + /// and is only the tag plus the first audio frames. + /// is set when a Xing or VBRI byte count does + /// not fit that file, so the frame count has to be walked from the audio itself. + /// + internal static bool TryParse ( + BinaryData data, + int audioOffset, + long fileLength, + out MpegAudioProperties? properties, + out bool needsEntireFile) { properties = null; + needsEntireFile = false; + if (fileLength < data.Length) + fileLength = data.Length; // Find the first valid MPEG frame var frameOffset = FindFirstFrame (data, audioOffset); @@ -146,8 +163,8 @@ public static bool TryParse (BinaryData data, int audioOffset, out MpegAudioProp bool isVbr; uint? frameCount = null; - var audioDataSize = data.Length - audioOffset; - var bytesFromFrame = data.Length - frameOffset; + var audioDataSize = fileLength - audioOffset; + var bytesFromFrame = fileLength - frameOffset; var trustVbri = xingHeader is null && vbriHeader is not null && DeclaredSizeFits (vbriHeader.ByteCount > 0 ? vbriHeader.ByteCount : null, bytesFromFrame); @@ -178,6 +195,13 @@ public static bool TryParse (BinaryData data, int audioOffset, out MpegAudioProp else bitrate = frame.Bitrate; } else if (xingHeader?.FrameCount != null || vbriHeader is not null) { + // The bytes we hold are not the whole file. Counting frames here would + // stop at the end of the probe instead of the end of the audio. + if (fileLength > data.Length) { + needsEntireFile = true; + return false; + } + // The header names a byte count past the end of this buffer, so its frame // count describes a longer file. Count the frames that are actually here. var counted = CountFrames (data, frameOffset); @@ -258,11 +282,11 @@ static bool TryReadXing (BinaryData data, int offset, out XingHeader? header) /// A missing byte count makes no size claim. A count past the bytes after the /// first frame belongs to a longer file than the one in hand. /// - static bool DeclaredSizeFits (uint? byteCount, int bytesFromFrame) + static bool DeclaredSizeFits (uint? byteCount, long bytesFromFrame) { if (byteCount is null) return true; - return bytesFromFrame >= 0 && byteCount.Value <= (uint)bytesFromFrame; + return bytesFromFrame >= 0 && byteCount.Value <= bytesFromFrame; } static int CountFrames (BinaryData data, int firstOffset) diff --git a/src/TagLibSharp2/Riff/RiffChunk.cs b/src/TagLibSharp2/Riff/RiffChunk.cs index b0d297f..271316b 100644 --- a/src/TagLibSharp2/Riff/RiffChunk.cs +++ b/src/TagLibSharp2/Riff/RiffChunk.cs @@ -87,6 +87,13 @@ public RiffChunk (string fourCC, BinaryData data) Data = data; } + /// + /// A chunk whose stored size is even when + /// does not hold those bytes. + /// + internal static RiffChunk WithDeclaredSize (string fourCC, uint dataSize, BinaryData data) => + new (fourCC, dataSize, data); + /// /// Attempts to parse a RIFF chunk from binary data at the specified offset. /// diff --git a/src/TagLibSharp2/Riff/RiffFile.cs b/src/TagLibSharp2/Riff/RiffFile.cs index ec25af3..46f3c91 100644 --- a/src/TagLibSharp2/Riff/RiffFile.cs +++ b/src/TagLibSharp2/Riff/RiffFile.cs @@ -177,6 +177,89 @@ public static bool TryParse (BinaryData data, out RiffFile file) return true; } + /// + /// A chunk whose bytes were left in the file. can be + /// shorter than the declared ckSize when the file ends first. + /// + internal readonly struct SkippedChunk + { + public SkippedChunk (int index, long offset, uint presentBytes) + { + Index = index; + Offset = offset; + PresentBytes = presentBytes; + } + + public int Index { get; } + + public long Offset { get; } + + public uint PresentBytes { get; } + } + + /// + /// Reads a RIFF file from a seekable stream. Sample bytes, and any other chunk + /// whose ckSize does not fit in an int, stay in the file. Each of those chunks + /// is one , in file order. A later chunk is still parsed. + /// + internal static bool TryRead (Stream stream, out RiffFile file, out List skipped) + { + file = new RiffFile (); + skipped = []; + + var header = StreamBytes.ReadAtMost (stream, HeaderSize); + if (header.Length < HeaderSize || !IsRiff (header)) + return false; + + file.FileSize = (uint)header[4] | ((uint)header[5] << 8) | ((uint)header[6] << 16) | ((uint)header[7] << 24); + file.FormType = FourCharacters (header, 8); + + var limit = Math.Min (stream.Length, (long)file.FileSize + 8); + while (stream.Position + RiffChunk.HeaderSize <= limit) { + var chunkHeader = StreamBytes.ReadAtMost (stream, RiffChunk.HeaderSize); + if (chunkHeader.Length < RiffChunk.HeaderSize) + break; + + var fourCC = FourCharacters (chunkHeader, 0); + var size = (uint)chunkHeader[4] | ((uint)chunkHeader[5] << 8) | ((uint)chunkHeader[6] << 16) | ((uint)chunkHeader[7] << 24); + var remaining = limit - stream.Position; + var available = remaining < size ? (uint)Math.Max (0, remaining) : size; + // A data chunk is reloaded on save. A ckSize past int.MaxValue cannot be + // copied here; skipping it in long arithmetic keeps the chunks after it. + if (fourCC == "data" || size > int.MaxValue) { + if (available > 0) + skipped.Add (new SkippedChunk (file._chunks.Count, stream.Position, available)); + var pad = (size & 1) == 1 && available == size ? 1L : 0L; + var skip = (long)available + pad; + if (stream.Position > stream.Length - skip) + skip = Math.Max (0, stream.Length - stream.Position); + stream.Position += skip; + file._chunks.Add (RiffChunk.WithDeclaredSize (fourCC, size, BinaryData.Empty)); + if (available < size) + break; + continue; + } + + var payload = StreamBytes.ReadAtMost (stream, (int)available); + if ((size & 1) == 1 && payload.Length == size && stream.Position < limit) + StreamBytes.ReadAtMost (stream, 1); + file._chunks.Add (RiffChunk.WithDeclaredSize (fourCC, size, new BinaryData (payload))); + if (payload.Length < size) + break; + } + + file.IsValid = true; + return true; + } + + internal void ReplaceChunkAt (int index, RiffChunk chunk) => _chunks[index] = chunk; + + static bool IsRiff (byte[] header) => + header[0] == (byte)'R' && header[1] == (byte)'I' && header[2] == (byte)'F' && header[3] == (byte)'F'; + + static string FourCharacters (byte[] data, int offset) => + new ([(char)data[offset], (char)data[offset + 1], (char)data[offset + 2], (char)data[offset + 3]]); + /// /// Renders the RIFF file to binary data. /// diff --git a/src/TagLibSharp2/Riff/WavFile.cs b/src/TagLibSharp2/Riff/WavFile.cs index 3531e4e..9050f5b 100644 --- a/src/TagLibSharp2/Riff/WavFile.cs +++ b/src/TagLibSharp2/Riff/WavFile.cs @@ -153,11 +153,14 @@ public sealed class WavFile : IMediaFile bool _keepUnparsedBext; /// - /// The instance produced by . + /// The instance produced by . /// Original bytes are copied only while is still this instance. /// BextTag? _parsedBext; + /// File offset of sample bytes that were not copied during a stream read. + readonly List _skippedChunks = []; + WavFile (RiffFile riff) { _riff = riff; @@ -254,6 +257,36 @@ public static WavFileReadResult Read (ReadOnlySpan data) if (!RiffFile.TryParse (new BinaryData (data.ToArray ()), out var riff)) return WavFileReadResult.Failure ("Invalid WAV file: invalid RIFF structure"); + return FromParsed (riff, null); + } + + /// + /// Reads a WAV file from a stream. Sample bytes in the data chunk are skipped. + /// A later save reloads them from when that path is set. + /// + internal static WavFileReadResult Read (Stream stream, string? sourcePath, IFileSystem? fileSystem) + { + if (!stream.CanSeek) + return Read (StreamBytes.ReadToEnd (stream)); + + if (stream.Position != 0) + stream.Position = 0; + + if (!RiffFile.TryRead (stream, out var riff, out var skipped)) + return WavFileReadResult.Failure ("Invalid WAV file: invalid RIFF structure"); + + var result = FromParsed (riff, FirstDataBytes (riff, skipped)); + if (result.IsSuccess && result.File is not null) { + result.File.SourcePath = sourcePath; + result.File._sourceFileSystem = fileSystem; + result.File._skippedChunks.AddRange (skipped); + } + + return result; + } + + static WavFileReadResult FromParsed (RiffFile riff, uint? sampleBytes) + { if (riff.FormType != "WAVE") return WavFileReadResult.Failure ($"Invalid WAV file: invalid form type (expected 'WAVE', got '{riff.FormType}')"); @@ -265,9 +298,10 @@ public static WavFileReadResult Read (ReadOnlySpan data) if (fmtChunk.HasValue) { // Duration uses the sample bytes held. A declared ckSize larger than - // those bytes is not the audio that was parsed. - var dataBytes = dataChunk is { } present ? present.Data.Length : 0; - wav.Properties = WavAudioPropertiesParser.Parse (fmtChunk.Value.Data, dataBytes) ?? default; + // those bytes is not the audio that was parsed. A stream read passes + // the skipped count, because those bytes exist and were not copied. + var held = sampleBytes ?? (dataChunk is { } present ? (uint)present.Data.Length : 0u); + wav.Properties = WavAudioPropertiesParser.Parse (fmtChunk.Value.Data, held) ?? default; // Parse WAVEFORMATEXTENSIBLE if present wav.ExtendedProperties = WavAudioPropertiesParser.ParseExtended (fmtChunk.Value.Data); @@ -430,6 +464,9 @@ public BinaryData Render () if (!HasDataChunk) throw new InvalidOperationException ("Cannot render a WAV file that has no data chunk."); + if (!TryLoadSkippedSamples (out var skipped)) + throw new InvalidOperationException (skipped); + // Start with a new RIFF structure var riff = new RiffFile (); var copyBext = ShouldCopyBextChunk (); @@ -486,12 +523,31 @@ public BinaryData Render () /// /// True when a data chunk was parsed. A short payload still counts. - /// A ckSize above is not a chunk. + /// A ckSize above still counts; its samples stay in the file. /// bool HasDataChunk => _riff.GetChunk (DataChunkId) is not null; /// - /// Copy the original bext bytes only for the instance parsed, + /// Duration follows the first data chunk, which is the chunk returns. + /// + static uint? FirstDataBytes (RiffFile riff, List skipped) + { + for (var i = 0; i < riff.AllChunks.Count; i++) { + if (riff.AllChunks[i].FourCC != DataChunkId) + continue; + foreach (var chunk in skipped) { + if (chunk.Index == i) + return chunk.PresentBytes; + } + + return (uint)riff.AllChunks[i].Data.Length; + } + + return null; + } + + /// + /// Copy the original bext bytes only for the instance parsed, /// and only while that instance still matches its source. /// A assigned from another file is rendered instead. /// Null removes a parsed bext. An unparsed bext is kept while the property stays null. @@ -501,6 +557,44 @@ bool ShouldCopyBextChunk () => && ((_keepUnparsedBext && BextTag is null) || (ReferenceEquals (BextTag, _parsedBext) && BextTag is { } tag && tag.MatchesSource ())); + bool TryLoadSkippedSamples (out string? error) + { + error = null; + if (_skippedChunks.Count == 0) + return true; + + foreach (var chunk in _skippedChunks) { + if (chunk.PresentBytes > int.MaxValue) { + error = "Cannot save a WAV file whose sample data does not fit in memory."; + return false; + } + } + + if (SourcePath is not { Length: > 0 } path) { + error = "Cannot save a WAV file whose sample data was not loaded."; + return false; + } + + var fs = _sourceFileSystem ?? DefaultFileSystem.Instance; + using var stream = fs.OpenRead (path); + foreach (var chunk in _skippedChunks) { + if (stream.Length < chunk.Offset + chunk.PresentBytes) { + error = "Cannot save a WAV file whose sample data is no longer in the source file."; + return false; + } + } + + foreach (var chunk in _skippedChunks) { + stream.Position = chunk.Offset; + var samples = StreamBytes.ReadAtMost (stream, (int)chunk.PresentBytes); + var fourCC = _riff.AllChunks[chunk.Index].FourCC; + _riff.ReplaceChunkAt (chunk.Index, new RiffChunk (fourCC, new BinaryData (samples))); + } + + _skippedChunks.Clear (); + return true; + } + FileWriteResult? MissingDataChunkFailure () { if (!IsValid || HasDataChunk) @@ -522,6 +616,9 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) if (MissingDataChunkFailure () is { } failure) return failure; + if (!TryLoadSkippedSamples (out var skipped)) + return FileWriteResult.Failure (skipped!); + var data = Render (); return AtomicFileWriter.Write (path, data.Span, fileSystem); } @@ -543,6 +640,9 @@ public Task SaveToFileAsync ( if (MissingDataChunkFailure () is { } failure) return Task.FromResult (failure); + if (!TryLoadSkippedSamples (out var skipped)) + return Task.FromResult (FileWriteResult.Failure (skipped!)); + var data = Render (); return AtomicFileWriter.WriteAsync (path, data.Memory, fileSystem, cancellationToken); } diff --git a/src/TagLibSharp2/Xiph/FlacFile.cs b/src/TagLibSharp2/Xiph/FlacFile.cs index d6c1ba9..bb32252 100644 --- a/src/TagLibSharp2/Xiph/FlacFile.cs +++ b/src/TagLibSharp2/Xiph/FlacFile.cs @@ -42,7 +42,7 @@ public sealed class FlacFile : IMediaFile /// /// /// This is set when using or . - /// It is null when the file was read from binary data using . + /// It is null when the file was read from binary data using . /// public string? SourcePath { get; private set; } @@ -488,6 +488,102 @@ public static FlacFileReadResult Read (ReadOnlySpan data) return FlacFileReadResult.Success (file, offset); } + /// + /// Reads FLAC metadata from a stream and stops at the last metadata block. + /// Audio frames after that block are not read. + /// + internal static FlacFileReadResult Read (Stream stream) + { + if (!stream.CanSeek) + return Read (StreamBytes.ReadToEnd (stream)); + + if (stream.Position != 0) + stream.Position = 0; + + using var metadata = new MemoryStream (); + AppendMetadata (metadata, StreamBytes.ReadAtMost (stream, MagicSize)); + var last = false; + while (!last && stream.Position < stream.Length) { + var headerBytes = StreamBytes.ReadAtMost (stream, FlacMetadataBlockHeader.HeaderSize); + if (!TryBeginBlock (stream, metadata, headerBytes, out var declared, out var count, out var isLast)) + break; + if (!TryFinishBlock (metadata, StreamBytes.ReadAtMost (stream, count), declared, isLast, ref last)) + break; + } + + return Read (metadata.ToArray ()); + } + + internal static async Task ReadAsync (Stream stream, CancellationToken cancellationToken) + { + if (!stream.CanSeek) + return Read (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false)); + + if (stream.Position != 0) + stream.Position = 0; + + using var metadata = new MemoryStream (); + AppendMetadata (metadata, await StreamBytes.ReadAtMostAsync (stream, MagicSize, cancellationToken).ConfigureAwait (false)); + var last = false; + while (!last && stream.Position < stream.Length) { + var headerBytes = await StreamBytes.ReadAtMostAsync (stream, FlacMetadataBlockHeader.HeaderSize, cancellationToken) + .ConfigureAwait (false); + if (!TryBeginBlock (stream, metadata, headerBytes, out var declared, out var count, out var isLast)) + break; + var body = await StreamBytes.ReadAtMostAsync (stream, count, cancellationToken).ConfigureAwait (false); + if (!TryFinishBlock (metadata, body, declared, isLast, ref last)) + break; + } + + return Read (metadata.ToArray ()); + } + + static bool TryBeginBlock ( + Stream stream, + MemoryStream metadata, + byte[] headerBytes, + out int declared, + out int count, + out bool isLast) + { + declared = 0; + count = 0; + isLast = false; + if (headerBytes.Length < FlacMetadataBlockHeader.HeaderSize) + return false; + + var header = FlacMetadataBlockHeader.Read (headerBytes); + if (!header.IsSuccess) + return false; + + AppendMetadata (metadata, headerBytes); + declared = header.Header.DataLength; + if (declared < 0) + return false; + + var remaining = stream.Length - stream.Position; + count = declared; + if (count > remaining) + count = (int)Math.Max (0, remaining); + isLast = header.Header.IsLast; + return true; + } + + static bool TryFinishBlock (MemoryStream metadata, byte[] body, int declared, bool isLast, ref bool last) + { + AppendMetadata (metadata, body); + if (body.Length < declared) + return false; + last = isLast; + return true; + } + + static void AppendMetadata (MemoryStream metadata, byte[] data) + { + if (data.Length > 0) + metadata.Write (data, 0, data.Length); + } + /// /// Attempts to read a FLAC file from binary data. /// diff --git a/tests/TagLibSharp2.Tests/Core/MediaFileAsyncTests.cs b/tests/TagLibSharp2.Tests/Core/MediaFileAsyncTests.cs index beebe21..1793363 100644 --- a/tests/TagLibSharp2.Tests/Core/MediaFileAsyncTests.cs +++ b/tests/TagLibSharp2.Tests/Core/MediaFileAsyncTests.cs @@ -52,7 +52,7 @@ public async Task OpenAsync_NullPath_ThrowsArgumentNullException () { // Act & Assert await Assert.ThrowsExactlyAsync ( - () => MediaFile.ReadAsync (null!)); + () => MediaFile.ReadAsync ((string)null!)); } [TestMethod] @@ -87,7 +87,7 @@ public void Open_NullPath_ThrowsArgumentNullException () { // Act & Assert Assert.ThrowsExactly ( - () => MediaFile.Read (null!)); + () => MediaFile.Read ((string)null!)); } [TestMethod] diff --git a/tests/TagLibSharp2.Tests/Core/MediaFileStreamTests.cs b/tests/TagLibSharp2.Tests/Core/MediaFileStreamTests.cs new file mode 100644 index 0000000..14d90d3 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/MediaFileStreamTests.cs @@ -0,0 +1,307 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Id3; +using TagLibSharp2.Id3.Id3v2; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Riff; + +namespace TagLibSharp2.Tests.Core; + +[TestClass] +[TestCategory ("Unit")] +public class MediaFileStreamTests +{ + [TestMethod] + public void Read_NullStream_Throws () + { + Assert.ThrowsExactly (() => MediaFile.Read ((Stream)null!)); + } + + [TestMethod] + public void Read_Mp3Stream_SkipsTheAudioAndKeepsTheTags () + { + var file = Mp3WithALargeGap (); + var counted = new CountingStream (new MemoryStream (file)); + + var streamed = MediaFile.Read (counted, "song.mp3"); + var loaded = MediaFile.ReadFromData (file, "song.mp3"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual ("Window", streamed.Tag!.Title); + Assert.AreEqual ("Tail", streamed.GetFileAs ()!.Id3v1Tag!.Title); + Assert.AreEqual (Duration (loaded), Duration (streamed)); + Assert.IsTrue (counted.BytesRead < file.Length - 500_000, $"read {counted.BytesRead} of {file.Length}"); + } + + [TestMethod] + public async Task ReadAsync_Mp3Stream_SkipsTheAudioAndKeepsTheTags () + { + var file = Mp3WithALargeGap (); + var counted = new CountingStream (new MemoryStream (file)); + + var streamed = await MediaFile.ReadAsync (counted, "song.mp3"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual ("Window", streamed.Tag!.Title); + Assert.IsTrue (counted.BytesRead < file.Length - 500_000, $"read {counted.BytesRead} of {file.Length}"); + } + + [TestMethod] + public void Read_FlacStream_StopsBeforeTheAudioFrames () + { + var metadata = TestBuilders.Flac.CreateMinimal (); + var file = new byte[metadata.Length + (1024 * 1024)]; + metadata.CopyTo (file, 0); + var counted = new CountingStream (new MemoryStream (file)); + + var streamed = MediaFile.Read (counted, "song.flac"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual (44100, ((IMediaFile)streamed.File!).AudioProperties!.SampleRate); + Assert.IsTrue (counted.BytesRead < metadata.Length + 8192, $"read {counted.BytesRead} of {file.Length}"); + } + + [TestMethod] + public void Read_WavStream_SkipsTheSampleData () + { + var file = WavWithALargeDataChunk (); + var counted = new CountingStream (new MemoryStream (file)); + + var streamed = MediaFile.Read (counted, "song.wav"); + var loaded = MediaFile.ReadFromData (file, "song.wav"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual ("Window", streamed.Tag!.Title); + Assert.AreEqual (Duration (loaded), Duration (streamed)); + Assert.IsTrue (counted.BytesRead < file.Length - 500_000, $"read {counted.BytesRead} of {file.Length}"); + } + + [TestMethod] + public void Read_NonSeekableStream_StillReadsTheTitle () + { + var file = Mp3WithALargeGap (); + var stream = new NonSeekableStream (new MemoryStream (file)); + + var result = MediaFile.Read (stream, "song.mp3"); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Window", result.Tag!.Title); + } + + [TestMethod] + public void Read_Path_DoesNotLoadTheWholeMp3 () + { + var file = Mp3WithALargeGap (); + var files = new CountingFileSystem (); + files.AddFile ("/song.mp3", file); + + var result = MediaFile.Read ("/song.mp3", files); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Window", result.Tag!.Title); + Assert.AreEqual (0, files.ReadAllBytesCalls); + Assert.IsTrue (files.BytesRead < file.Length - 500_000, $"read {files.BytesRead} of {file.Length}"); + } + + static TimeSpan Duration (MediaFileResult result) => + ((IMediaFile)result.File!).AudioProperties!.Duration; + + static byte[] Mp3WithALargeGap () + { + var id3v2 = new Id3v2Tag { Title = "Window" }.Render ().ToArray (); + var header = new byte[] { 0xFF, 0xFB, 0x90, 0x00 }; + Assert.IsTrue (MpegFrame.TryParse (new BinaryData (header), 0, out var frame)); + var audio = new byte[frame!.FrameSize + MpegFrame.HeaderSize]; + header.CopyTo (audio, 0); + header.CopyTo (audio, frame.FrameSize); + var gap = new byte[1024 * 1024]; + var id3v1 = new Id3v1Tag { Title = "Tail" }.Render ().ToArray (); + + var file = new byte[id3v2.Length + audio.Length + gap.Length + id3v1.Length]; + var offset = 0; + id3v2.CopyTo (file, offset); + offset += id3v2.Length; + audio.CopyTo (file, offset); + offset += audio.Length; + gap.CopyTo (file, offset); + offset += gap.Length; + id3v1.CopyTo (file, offset); + return file; + } + + static byte[] WavWithALargeDataChunk () + { + using var body = new BinaryDataBuilder (); + body.AddStringLatin1 ("WAVE"); + body.AddStringLatin1 ("fmt "); + body.AddUInt32LE (16); + body.AddUInt16LE (1); + body.AddUInt16LE (1); + body.AddUInt32LE (44100); + body.AddUInt32LE (88200); + body.AddUInt16LE (2); + body.AddUInt16LE (16); + body.AddStringLatin1 ("data"); + body.AddUInt32LE (1024 * 1024); + body.Add (new byte[1024 * 1024]); + var info = InfoList ("Window"); + body.AddStringLatin1 ("LIST"); + body.AddUInt32LE ((uint)info.Length); + body.Add (info); + + var payload = body.ToBinaryData (); + using var file = new BinaryDataBuilder (); + file.AddStringLatin1 ("RIFF"); + file.AddUInt32LE ((uint)payload.Length); + file.Add (payload); + return file.ToBinaryData ().ToArray (); + } + + static byte[] InfoList (string title) + { + var text = System.Text.Encoding.ASCII.GetBytes (title + "\0"); + using var builder = new BinaryDataBuilder (); + builder.AddStringLatin1 ("INFO"); + builder.AddStringLatin1 ("INAM"); + builder.AddUInt32LE ((uint)text.Length); + builder.Add (text); + return builder.ToBinaryData ().ToArray (); + } + + sealed class CountingStream : Stream + { + readonly Stream _inner; + + public CountingStream (Stream inner) => _inner = inner; + + public long BytesRead { get; private set; } + + public override bool CanRead => _inner.CanRead; + + public override bool CanSeek => _inner.CanSeek; + + public override bool CanWrite => false; + + public override long Length => _inner.Length; + + public override long Position { + get => _inner.Position; + set => _inner.Position = value; + } + + public override void Flush () => _inner.Flush (); + + public override int Read (byte[] buffer, int offset, int count) + { + var read = _inner.Read (buffer, offset, count); + BytesRead += read; + return read; + } + + public override int Read (Span buffer) + { + var read = _inner.Read (buffer); + BytesRead += read; + return read; + } + + public override ValueTask ReadAsync (Memory buffer, CancellationToken cancellationToken = default) + { + var read = _inner.Read (buffer.Span); + BytesRead += read; + return new ValueTask (read); + } + + public override long Seek (long offset, SeekOrigin origin) => _inner.Seek (offset, origin); + + public override void SetLength (long value) => throw new NotSupportedException (); + + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } + + sealed class NonSeekableStream : Stream + { + readonly Stream _inner; + + public NonSeekableStream (Stream inner) => _inner = inner; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException (); + + public override long Position { + get => throw new NotSupportedException (); + set => throw new NotSupportedException (); + } + + public override void Flush () + { + } + + public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); + + public override long Seek (long offset, SeekOrigin origin) => throw new NotSupportedException (); + + public override void SetLength (long value) => throw new NotSupportedException (); + + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } + + sealed class CountingFileSystem : IFileSystem + { + readonly MockFileSystem _inner = new (); + + public CountingStream? Opened { get; private set; } + + public int ReadAllBytesCalls { get; private set; } + + public long BytesRead => Opened?.BytesRead ?? 0; + + public void AddFile (string path, byte[] data) => _inner.AddFile (path, data); + + public bool FileExists (string path) => _inner.FileExists (path); + + public Stream OpenRead (string path) + { + Opened = new CountingStream (_inner.OpenRead (path)); + return Opened; + } + + public Stream OpenReadWrite (string path) => _inner.OpenReadWrite (path); + + public Stream Create (string path) => _inner.Create (path); + + public byte[] ReadAllBytes (string path) + { + ReadAllBytesCalls++; + return _inner.ReadAllBytes (path); + } + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) + { + ReadAllBytesCalls++; + return _inner.ReadAllBytesAsync (path, cancellationToken); + } + + public void WriteAllBytes (string path, ReadOnlySpan data) => _inner.WriteAllBytes (path, data); + + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => + _inner.WriteAllBytesAsync (path, data, cancellationToken); + + public void Delete (string path) => _inner.Delete (path); + + public void Move (string sourcePath, string destinationPath) => _inner.Move (sourcePath, destinationPath); + + public string? GetDirectoryName (string path) => _inner.GetDirectoryName (path); + + public string GetFileName (string path) => _inner.GetFileName (path); + + public string CombinePath (string path1, string path2) => _inner.CombinePath (path1, path2); + } +} diff --git a/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs b/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs new file mode 100644 index 0000000..c089dbb --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/WindowedReadDefectTests.cs @@ -0,0 +1,375 @@ +// 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.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Riff; + +namespace TagLibSharp2.Tests.Core; + +[TestClass] +[TestCategory ("Unit")] +public class WindowedReadDefectTests +{ + [TestMethod] + public void Read_TwoDataChunks_DurationUsesTheFirstAndSaveKeepsBoth () + { + var first = new byte[] { 0x01, 0x01, 0x01, 0x01 }; + var second = new byte[] { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }; + var wav = TwoDataChunks (first, second, "Window"); + var files = new MockFileSystem (); + files.AddFile ("/song.wav", wav); + + var streamed = MediaFile.Read ("/song.wav", files); + var loaded = MediaFile.ReadFromData (wav, "song.wav"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual ("Window", streamed.Tag!.Title); + Assert.AreEqual (Duration (loaded), Duration (streamed)); + Assert.AreEqual (TimeSpan.FromSeconds (first.Length / 8000.0), Duration (streamed)); + + streamed.Tag.Title = "After"; + var saved = streamed.GetFileAs ()!.SaveToFile ("/song.wav", files); + Assert.IsTrue (saved.IsSuccess, saved.Error); + + var payloads = DataPayloads (files.ReadAllBytes ("/song.wav")); + Assert.HasCount (2, payloads); + CollectionAssert.AreEqual (first, payloads[0]); + CollectionAssert.AreEqual (second, payloads[1]); + Assert.AreEqual ("After", MediaFile.Read ("/song.wav", files).Tag!.Title); + } + + [TestMethod] + public void Read_EmptySecondDataChunk_DoesNotClearTheFirstPayload () + { + var first = new byte[] { 0x01, 0x01, 0x01, 0x01 }; + var wav = TwoDataChunks (first, [], "Window"); + var files = new MockFileSystem (); + files.AddFile ("/song.wav", wav); + + var streamed = MediaFile.Read ("/song.wav", files); + var loaded = MediaFile.ReadFromData (wav, "song.wav"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual (Duration (loaded), Duration (streamed)); + Assert.AreEqual (TimeSpan.FromSeconds (0.0005), Duration (streamed)); + + var saved = streamed.GetFileAs ()!.SaveToFile ("/song.wav", files); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var payloads = DataPayloads (files.ReadAllBytes ("/song.wav")); + Assert.HasCount (2, payloads); + CollectionAssert.AreEqual (first, payloads[0]); + Assert.IsEmpty (payloads[1]); + } + + [TestMethod] + public void Read_DataChunkPastTwoGigabytes_KeepsTheFollowingTitleAndRefusesTheSave () + { + var files = new SparseFileSystem (PastTwoGigabytes ()); + using var opened = files.OpenRead ("/song.wav"); + var streamed = WavFile.Read (opened, "/song.wav", files); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual ("Window", streamed.File!.Title); + Assert.AreEqual (TimeSpan.FromSeconds (0x80000000 / 8000.0), streamed.File.Properties.Duration); + + var saved = streamed.File.SaveToFile ("/song.wav", files); + Assert.IsFalse (saved.IsSuccess, saved.Error); + Assert.AreEqual (0, files.Writes); + } + + [TestMethod] + public void Read_XingByteCountPastFourGigabytes_UsesTheFrameCount () + { + var mp3 = new SparseMp3 (XingPastFourGigabytes ()); + var streamed = MediaFile.Read (mp3, "song.mp3"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual (TimeSpan.FromSeconds (100 * 1152 / 44100.0), Duration (streamed)); + } + + [TestMethod] + public async Task ReadAsync_XingByteCountPastFourGigabytes_UsesTheFrameCount () + { + var mp3 = new SparseMp3 (XingPastFourGigabytes ()); + var streamed = await MediaFile.ReadAsync (mp3, "song.mp3"); + + Assert.IsTrue (streamed.IsSuccess, streamed.Error); + Assert.AreEqual (TimeSpan.FromSeconds (100 * 1152 / 44100.0), Duration (streamed)); + } + + static TimeSpan Duration (MediaFileResult result) => + ((IMediaFile)result.File!).AudioProperties!.Duration; + + static byte[] TwoDataChunks (byte[] first, byte[] second, string title) + { + using var body = new BinaryDataBuilder (); + body.AddStringLatin1 ("WAVE"); + body.AddStringLatin1 ("fmt "); + body.AddUInt32LE (16); + body.AddUInt16LE (1); + body.AddUInt16LE (1); + body.AddUInt32LE (8000); + body.AddUInt32LE (8000); + body.AddUInt16LE (1); + body.AddUInt16LE (8); + AddData (body, first); + AddData (body, second); + var info = InfoList (title); + body.AddStringLatin1 ("LIST"); + body.AddUInt32LE ((uint)info.Length); + body.Add (info); + + var payload = body.ToBinaryData (); + using var file = new BinaryDataBuilder (); + file.AddStringLatin1 ("RIFF"); + file.AddUInt32LE ((uint)payload.Length); + file.Add (payload); + return file.ToBinaryData ().ToArray (); + } + + static void AddData (BinaryDataBuilder body, byte[] samples) + { + body.AddStringLatin1 ("data"); + body.AddUInt32LE ((uint)samples.Length); + if (samples.Length > 0) + body.Add (samples); + if ((samples.Length & 1) == 1) + body.Add (0); + } + + static byte[] InfoList (string title) + { + var text = Encoding.ASCII.GetBytes (title + "\0"); + using var builder = new BinaryDataBuilder (); + builder.AddStringLatin1 ("INFO"); + builder.AddStringLatin1 ("INAM"); + builder.AddUInt32LE ((uint)text.Length); + builder.Add (text); + return builder.ToBinaryData ().ToArray (); + } + + static List DataPayloads (byte[] wav) + { + var payloads = new List (); + var offset = 12; + while (offset + 8 <= wav.Length) { + var id = Encoding.ASCII.GetString (wav, offset, 4); + var size = BitConverter.ToUInt32 (wav, offset + 4); + var start = offset + 8; + if (id == "data") { + var count = (int)Math.Min (size, (uint)Math.Max (0, wav.Length - start)); + var payload = new byte[count]; + Buffer.BlockCopy (wav, start, payload, 0, count); + payloads.Add (payload); + } + + var step = 8L + size + (size & 1); + if (step <= 0 || offset + step > wav.Length) + break; + offset += (int)step; + } + + return payloads; + } + + static SparseLayout PastTwoGigabytes () + { + using var head = new BinaryDataBuilder (); + head.AddStringLatin1 ("RIFF"); + head.AddUInt32LE (0); + head.AddStringLatin1 ("WAVE"); + head.AddStringLatin1 ("fmt "); + head.AddUInt32LE (16); + head.AddUInt16LE (1); + head.AddUInt16LE (1); + head.AddUInt32LE (8000); + head.AddUInt32LE (8000); + head.AddUInt16LE (1); + head.AddUInt16LE (8); + head.AddStringLatin1 ("data"); + head.AddUInt32LE (0x80000000); + var info = InfoList ("Window"); + using var tail = new BinaryDataBuilder (); + tail.AddStringLatin1 ("LIST"); + tail.AddUInt32LE ((uint)info.Length); + tail.Add (info); + var headBytes = head.ToBinaryData ().ToArray (); + var tailBytes = tail.ToBinaryData ().ToArray (); + var total = headBytes.Length + 0x80000000L + tailBytes.Length; + var size = (uint)(total - 8); + headBytes[4] = (byte)size; + headBytes[5] = (byte)(size >> 8); + headBytes[6] = (byte)(size >> 16); + headBytes[7] = (byte)(size >> 24); + return new SparseLayout (headBytes, 0x80000000L, tailBytes); + } + + static SparseLayout XingPastFourGigabytes () + { + var header = new byte[] { 0xFF, 0xFB, 0x90, 0x00 }; + Assert.IsTrue (MpegFrame.TryParse (new BinaryData (header), 0, out var frame)); + var audio = new byte[frame!.FrameSize + MpegFrame.HeaderSize]; + header.CopyTo (audio, 0); + header.CopyTo (audio, frame.FrameSize); + audio[36] = (byte)'X'; + audio[37] = (byte)'i'; + audio[38] = (byte)'n'; + audio[39] = (byte)'g'; + audio[40] = 0; + audio[41] = 0; + audio[42] = 0; + audio[43] = 0x03; + audio[44] = 0; + audio[45] = 0; + audio[46] = 0; + audio[47] = 100; + audio[48] = 0; + audio[49] = 0; + audio[50] = 0x17; + audio[51] = 0x70; + return new SparseLayout (audio, (long)uint.MaxValue + 5000 - audio.Length, []); + } + + sealed class SparseFileSystem : IFileSystem + { + readonly SparseLayout _layout; + + public SparseFileSystem (SparseLayout layout) => _layout = layout; + + public int Writes { get; private set; } + + public bool FileExists (string path) => path == "/song.wav"; + + public Stream OpenRead (string path) => new SparseStream (_layout); + + public Stream OpenReadWrite (string path) => throw new NotSupportedException (); + + public Stream Create (string path) => throw new NotSupportedException (); + + public byte[] ReadAllBytes (string path) => throw new NotSupportedException (); + + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => + throw new NotSupportedException (); + + public void WriteAllBytes (string path, ReadOnlySpan data) => Writes++; + + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) + { + Writes++; + return Task.CompletedTask; + } + + public void Delete (string path) + { + } + + public void Move (string sourcePath, string destinationPath) + { + } + + public string? GetDirectoryName (string path) => "/"; + + public string GetFileName (string path) => "song.wav"; + + public string CombinePath (string path1, string path2) => path1 + path2; + } + + internal readonly struct SparseLayout + { + public SparseLayout (byte[] head, long hole, byte[] tail) + { + Head = head; + Hole = hole; + Tail = tail; + } + + public byte[] Head { get; } + + public long Hole { get; } + + public byte[] Tail { get; } + + public long Length => Head.Length + Hole + Tail.Length; + } + + sealed class SparseMp3 : SparseStream + { + public SparseMp3 (SparseLayout layout) : base (layout) + { + } + } + + class SparseStream : Stream + { + readonly SparseLayout _layout; + long _position; + + public SparseStream (SparseLayout layout) => _layout = layout; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => _layout.Length; + + public override long Position { + get => _position; + set => _position = value; + } + + public override void Flush () + { + } + + public override int Read (byte[] buffer, int offset, int count) + { + if (count <= 0 || _position >= Length) + return 0; + + var written = 0; + while (written < count && _position < Length) { + var tailAt = _layout.Head.Length + _layout.Hole; + if (_position < _layout.Head.Length) { + var n = (int)Math.Min (count - written, _layout.Head.Length - _position); + Buffer.BlockCopy (_layout.Head, (int)_position, buffer, offset + written, n); + _position += n; + written += n; + } else if (_position < tailAt) { + var n = (int)Math.Min (count - written, tailAt - _position); + Array.Clear (buffer, offset + written, n); + _position += n; + written += n; + } else { + var tailOffset = (int)(_position - tailAt); + var n = Math.Min (count - written, _layout.Tail.Length - tailOffset); + if (n <= 0) + break; + Buffer.BlockCopy (_layout.Tail, tailOffset, buffer, offset + written, n); + _position += n; + written += n; + } + } + + return written; + } + + public override long Seek (long offset, SeekOrigin origin) + { + _position = origin switch { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => Length + offset, + _ => throw new ArgumentOutOfRangeException (nameof (origin)) + }; + return _position; + } + + public override void SetLength (long value) => throw new NotSupportedException (); + + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } +} diff --git a/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs b/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs index 73d532e..c3ea59c 100644 --- a/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs +++ b/tests/TagLibSharp2.Tests/Docs/DocExamplesCompileTests.cs @@ -25,7 +25,9 @@ public class DocExamplesCompileTests public void QuickStart_MediaFileRead_Compiles () { // This just verifies the API exists - skip actual file access - Assert.IsNotNull (typeof (MediaFile).GetMethod ("Read")); + Assert.IsNotNull (typeof (MediaFile).GetMethod ("Read", [typeof (string), typeof (IFileSystem)])); + Assert.IsNotNull (typeof (MediaFile).GetMethod ("Read", [typeof (Stream), typeof (string)])); + Assert.IsNotNull (typeof (MediaFile).GetMethod ("ReadAsync", [typeof (Stream), typeof (string), typeof (CancellationToken)])); Assert.IsNotNull (typeof (MediaFileResult).GetProperty ("IsSuccess")); Assert.IsNotNull (typeof (MediaFileResult).GetProperty ("Tag")); Assert.IsNotNull (typeof (MediaFileResult).GetProperty ("Format")); diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 747f7ba..9dfe3d3 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -1067,7 +1067,9 @@ namespace TagLibSharp2.Core public static class MediaFile { public static TagLibSharp2.Core.MediaFormat DetectFormat(System.ReadOnlySpan data, string? pathHint = null) { } + public static TagLibSharp2.Core.MediaFileResult Read(System.IO.Stream stream, string? pathHint = null) { } public static TagLibSharp2.Core.MediaFileResult Read(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public static System.Threading.Tasks.Task ReadAsync(System.IO.Stream stream, string? pathHint = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task ReadAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } public static TagLibSharp2.Core.MediaFileResult ReadFromData(System.ReadOnlyMemory data, string? pathHint = null) { } } From d62330535686479847453b087cd16a906483a70e Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Mon, 16 Nov 2026 20:55:05 -0700 Subject: [PATCH 2/3] test: Cover the windowed-read branches the patch check missed --- .../Core/WindowedReadEdgeTests.cs | 497 ++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs diff --git a/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs b/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs new file mode 100644 index 0000000..eea3fcc --- /dev/null +++ b/tests/TagLibSharp2.Tests/Core/WindowedReadEdgeTests.cs @@ -0,0 +1,497 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Riff; +using TagLibSharp2.Xiph; + +namespace TagLibSharp2.Tests.Core; + +[TestClass] +[TestCategory ("Unit")] +public class WindowedReadEdgeTests +{ + [TestMethod] + public void Read_OpenThrows_ReturnsTheIoFailure () + { + var files = new ThrowingFileSystem (new IOException ("disk")); + var result = MediaFile.Read ("/song.mp3", files); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Failed to read file: disk", result.Error); + } + + [TestMethod] + public void Read_OpenDenied_ReturnsAccessDenied () + { + var files = new ThrowingFileSystem (new UnauthorizedAccessException ("no")); + var result = MediaFile.Read ("/song.mp3", files); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Access denied: no", result.Error); + } + + [TestMethod] + public async Task ReadAsync_OpenThrows_ReturnsTheIoFailure () + { + var files = new ThrowingFileSystem (new IOException ("disk")); + var result = await MediaFile.ReadAsync ("/song.mp3", files); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Failed to read file: disk", result.Error); + } + + [TestMethod] + public async Task ReadAsync_OpenDenied_ReturnsAccessDenied () + { + var files = new ThrowingFileSystem (new UnauthorizedAccessException ("no")); + var result = await MediaFile.ReadAsync ("/song.mp3", files); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Access denied: no", result.Error); + } + + [TestMethod] + public void Read_StreamNotAtTheStart_RewindsBeforeDetecting () + { + var bytes = TinyMp3 (200); + var stream = new MemoryStream (bytes) { Position = 8 }; + var result = MediaFile.Read (stream, "song.mp3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsTrue (Duration (result) > TimeSpan.Zero); + } + + [TestMethod] + public async Task ReadAsync_UnrecognizedBytes_CopiesTheStream () + { + var stream = new MemoryStream (new byte[16]) { Position = 4 }; + var result = await MediaFile.ReadAsync (stream, "notes.bin"); + Assert.IsFalse (result.IsSuccess); + } + + [TestMethod] + public void Read_UnrecognizedBytes_CopiesTheStream () + { + var result = MediaFile.Read (new MemoryStream (new byte[16]), "notes.bin"); + Assert.IsFalse (result.IsSuccess); + } + + [TestMethod] + public void Read_TruncatedFlac_ReturnsTheParseFailure () + { + var result = MediaFile.Read (new MemoryStream ("fLaC"u8.ToArray ()), "song.flac"); + Assert.IsFalse (result.IsSuccess); + Assert.IsTrue (result.Error!.Contains ("FLAC", StringComparison.Ordinal)); + } + + [TestMethod] + public void Read_WavExtensionThatIsNotRiff_ReturnsTheParseFailure () + { + var result = MediaFile.Read (new MemoryStream (new byte[] { 1, 2, 3, 4 }), "song.wav"); + Assert.IsFalse (result.IsSuccess); + Assert.IsTrue (result.Error!.Contains ("WAV", StringComparison.Ordinal)); + } + + [TestMethod] + public void Read_Mp3ExtensionThatIsTooShort_ReturnsTheParseFailure () + { + var result = MediaFile.Read (new MemoryStream (new byte[] { 1, 2 }), "song.mp3"); + Assert.IsFalse (result.IsSuccess); + Assert.IsTrue (result.Error!.Contains ("too short", StringComparison.Ordinal) || result.Error.Contains ("MP3", StringComparison.Ordinal)); + } + + [TestMethod] + public void ReadAtMost_NonPositiveCount_ReturnsEmpty () + { + var stream = new MemoryStream (new byte[] { 1, 2, 3 }); + Assert.IsEmpty (StreamBytes.ReadAtMost (stream, 0)); + Assert.IsEmpty (StreamBytes.ReadAtMost (stream, -1)); + } + + [TestMethod] + public async Task ReadAtMostAsync_NonPositiveCount_ReturnsEmpty () + { + var stream = new MemoryStream (new byte[] { 1, 2, 3 }); + Assert.IsEmpty (await StreamBytes.ReadAtMostAsync (stream, 0, CancellationToken.None)); + } + + [TestMethod] + public void ReadToEnd_SeekableEmptyOrAtTheEnd_ReturnsEmpty () + { + var stream = new MemoryStream (); + Assert.IsEmpty (StreamBytes.ReadToEnd (stream)); + stream.Write (new byte[] { 1 }, 0, 1); + stream.Position = stream.Length; + Assert.IsEmpty (StreamBytes.ReadToEnd (stream)); + } + + [TestMethod] + public void ReadToEnd_SeekableBytes_ReturnsThem () + { + var stream = new MemoryStream (new byte[] { 9, 8, 7 }); + CollectionAssert.AreEqual (new byte[] { 9, 8, 7 }, StreamBytes.ReadToEnd (stream)); + } + + [TestMethod] + public void ReadToEnd_PastIntMax_Throws () + { + var error = Assert.ThrowsExactly (() => StreamBytes.ReadToEnd (new ReportedLengthStream ((long)int.MaxValue + 8))); + Assert.AreEqual ("File is too large to read into memory", error.Message); + } + + [TestMethod] + public async Task ReadToEndAsync_CoversTheSeekableAndCopyPaths () + { + var empty = new MemoryStream (); + Assert.IsEmpty (await StreamBytes.ReadToEndAsync (empty, CancellationToken.None)); + + var huge = new ReportedLengthStream ((long)int.MaxValue + 8); + var error = await Assert.ThrowsExactlyAsync ( + () => StreamBytes.ReadToEndAsync (huge, CancellationToken.None)); + Assert.AreEqual ("File is too large to read into memory", error.Message); + + var copy = new NonSeekableStream (new MemoryStream (new byte[] { 4, 5 })); + CollectionAssert.AreEqual (new byte[] { 4, 5 }, await StreamBytes.ReadToEndAsync (copy, CancellationToken.None)); + } + + [TestMethod] + public void ReadAtMost_EmptyStream_ReturnsEmpty () + { + Assert.IsEmpty (StreamBytes.ReadAtMost (new MemoryStream (), 8)); + } + + [TestMethod] + public void Read_Mp3ShorterThanFourBytes_Fails () + { + var result = Mp3File.Read (new MemoryStream (new byte[] { 0xFF, 0xFB })); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Invalid MP3 file: data too short", result.Error); + } + + [TestMethod] + public async Task ReadAsync_Mp3ShorterThanFourBytes_Fails () + { + var result = await Mp3File.ReadAsync (new MemoryStream (new byte[] { 0xFF, 0xFB }), CancellationToken.None); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Invalid MP3 file: data too short", result.Error); + } + + [TestMethod] + public void Read_NonSeekableMp3_StillReturnsTheDuration () + { + var bytes = TinyMp3 (200); + var result = MediaFile.Read (new NonSeekableStream (new MemoryStream (bytes)), "song.mp3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (Duration (MediaFile.ReadFromData (bytes, "song.mp3")), Duration (result)); + } + + [TestMethod] + public async Task ReadAsync_Mp3NotAtTheStart_Rewinds () + { + var bytes = TinyMp3 (200); + var stream = new MemoryStream (bytes) { Position = 3 }; + var result = await MediaFile.ReadAsync (stream, "song.mp3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsTrue (Duration (result) > TimeSpan.Zero); + } + + [TestMethod] + public void Read_Mp3WhoseTailFitsInTheProbe_DoesNotSeekBackward () + { + var bytes = TinyMp3 ((32 * 1024) + 50); + var result = MediaFile.Read (new MemoryStream (bytes), "song.mp3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsTrue (Duration (result) > TimeSpan.Zero); + } + + [TestMethod] + public void Read_XingCountPastTheFile_ReadsTheAudioThatIsPresent () + { + var frame = Frame (); + var audio = new byte[frame.FrameSize + MpegFrame.HeaderSize]; + new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.CopyTo (audio, 0); + new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.CopyTo (audio, frame.FrameSize); + audio[36] = (byte)'X'; + audio[37] = (byte)'i'; + audio[38] = (byte)'n'; + audio[39] = (byte)'g'; + audio[43] = 0x03; + audio[47] = 10; + audio[48] = 0xFF; + audio[49] = 0xFF; + audio[50] = 0xFF; + audio[51] = 0xFF; + var file = new byte[48 * 1024]; + audio.CopyTo (file, 0); + + var result = MediaFile.Read (new MemoryStream (file), "song.mp3"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsTrue (Duration (result) > TimeSpan.Zero); + Assert.IsTrue (Duration (result) < TimeSpan.FromSeconds (10)); + } + + [TestMethod] + public void Read_NonSeekableWav_ReturnsTheTitle () + { + var wav = WavWithTitle ("Window", new byte[] { 1, 2, 3, 4 }); + var result = MediaFile.Read (new NonSeekableStream (new MemoryStream (wav)), "song.wav"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Window", result.Tag!.Title); + } + + [TestMethod] + public void Read_WavNotAtTheStart_Rewinds () + { + var wav = WavWithTitle ("Window", new byte[] { 1, 2, 3, 4 }); + var stream = new MemoryStream (wav) { Position = 4 }; + var result = WavFile.Read (stream, "/song.wav", new MockFileSystem ()); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Window", result.File!.Title); + } + + [TestMethod] + public void Read_WavThatIsNotRiff_Fails () + { + var result = WavFile.Read (new MemoryStream (new byte[16]), null, null); + Assert.IsFalse (result.IsSuccess); + Assert.AreEqual ("Invalid WAV file: invalid RIFF structure", result.Error); + } + + [TestMethod] + public void Read_OddSizedDataChunk_SkipsThePadAndKeepsTheTitle () + { + var wav = WavWithTitle ("Odd", new byte[] { 0x11 }); + var result = MediaFile.Read (new MemoryStream (wav), "song.wav"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("Odd", result.Tag!.Title); + Assert.AreEqual (TimeSpan.FromSeconds (1 / 8000.0), Duration (result)); + } + + [TestMethod] + public void Read_DataChunkCutOffByTheFile_UsesTheBytesThatExist () + { + var wav = WavWithTitle ("Short", new byte[] { 1, 2, 3, 4 }); + // Claim 40 sample bytes. The title sits inside that claim, so the walk stops on the data chunk. + var claimed = (byte[])wav.Clone (); + var dataSizeAt = IndexOf (claimed, "data"u8.ToArray ()) + 4; + claimed[dataSizeAt] = 40; + var result = MediaFile.Read (new MemoryStream (claimed), "song.wav"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsTrue (Duration (result) > TimeSpan.Zero); + Assert.IsNull (result.Tag?.Title); + } + + [TestMethod] + public void Read_WavWithNoDataChunk_HasNoDuration () + { + var result = MediaFile.Read (new MemoryStream (WavWithTitle ("Fmt", null)), "song.wav"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (TimeSpan.Zero, Duration (result)); + } + + [TestMethod] + public void Read_EmptyDataChunk_ReportsZeroDuration () + { + var result = MediaFile.Read (new MemoryStream (WavWithTitle ("Empty", [])), "song.wav"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (TimeSpan.Zero, Duration (result)); + Assert.AreEqual ("Empty", result.Tag!.Title); + } + + [TestMethod] + public void Render_SkippedSamplesWithoutAPath_Throws () + { + var wav = WavWithTitle ("Window", new byte[] { 1, 2, 3, 4 }); + var parsed = WavFile.Read (new MemoryStream (wav), null, null); + var error = Assert.ThrowsExactly (() => parsed.File!.Render ()); + Assert.AreEqual ("Cannot save a WAV file whose sample data was not loaded.", error.Message); + } + + [TestMethod] + public async Task SaveToFileAsync_SkippedSamplesWithoutAPath_Fails () + { + var wav = WavWithTitle ("Window", new byte[] { 1, 2, 3, 4 }); + var parsed = WavFile.Read (new MemoryStream (wav), null, null); + var saved = await parsed.File!.SaveToFileAsync ("/song.wav"); + Assert.IsFalse (saved.IsSuccess); + Assert.AreEqual ("Cannot save a WAV file whose sample data was not loaded.", saved.Error); + } + + [TestMethod] + public void Save_SourceShorterThanTheSkippedSamples_DoesNotWrite () + { + var wav = WavWithTitle ("Window", new byte[32]); + var files = new MockFileSystem (); + files.AddFile ("/song.wav", wav); + var opened = MediaFile.Read ("/song.wav", files); + Assert.IsTrue (opened.IsSuccess, opened.Error); + files.AddFile ("/song.wav", wav.AsSpan (0, 16).ToArray ()); + + var saved = opened.GetFileAs ()!.SaveToFile ("/song.wav", files); + Assert.IsFalse (saved.IsSuccess); + Assert.AreEqual ("Cannot save a WAV file whose sample data is no longer in the source file.", saved.Error); + Assert.AreEqual (16, files.ReadAllBytes ("/song.wav").Length); + } + + [TestMethod] + public void Read_NonSeekableFlac_ReturnsTheSampleRate () + { + var flac = TestBuilders.Flac.CreateMinimal (); + var result = MediaFile.Read (new NonSeekableStream (new MemoryStream (flac)), "song.flac"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (44100, ((IMediaFile)result.File!).AudioProperties!.SampleRate); + } + + [TestMethod] + public async Task ReadAsync_FlacNotAtTheStart_Rewinds () + { + var flac = TestBuilders.Flac.CreateMinimal (); + var stream = new MemoryStream (flac) { Position = 2 }; + var result = await MediaFile.ReadAsync (stream, "song.flac"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (44100, ((IMediaFile)result.File!).AudioProperties!.SampleRate); + } + + [TestMethod] + public void Read_FlacBlockCutOff_Stops () + { + var flac = TestBuilders.Flac.CreateMinimal (); + var cut = flac.AsSpan (0, 8).ToArray (); + var result = FlacFile.Read (new MemoryStream (cut)); + Assert.IsFalse (result.IsSuccess); + } + + [TestMethod] + public async Task ReadAsync_FlacHeaderTooShort_Stops () + { + var bytes = "fLaC"u8.ToArray ().Concat (new byte[] { 0x00 }).ToArray (); + var result = await FlacFile.ReadAsync (new MemoryStream (bytes), CancellationToken.None); + Assert.IsFalse (result.IsSuccess); + } + + static TimeSpan Duration (MediaFileResult result) => + ((IMediaFile)result.File!).AudioProperties!.Duration; + + static MpegFrame Frame () + { + Assert.IsTrue (MpegFrame.TryParse (new BinaryData (new byte[] { 0xFF, 0xFB, 0x90, 0x00 }), 0, out var frame)); + return frame!; + } + + static byte[] TinyMp3 (int length) + { + var frame = Frame (); + var audio = new byte[Math.Max (length, frame.FrameSize + MpegFrame.HeaderSize)]; + new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.CopyTo (audio, 0); + new byte[] { 0xFF, 0xFB, 0x90, 0x00 }.CopyTo (audio, frame.FrameSize); + if (audio.Length != length && length > audio.Length) + return audio; + if (length < audio.Length) + return audio.AsSpan (0, Math.Max (length, frame.FrameSize + 4)).ToArray (); + return audio; + } + + static byte[] WavWithTitle (string title, byte[]? samples) + { + using var body = new BinaryDataBuilder (); + body.AddStringLatin1 ("WAVE"); + body.AddStringLatin1 ("fmt "); + body.AddUInt32LE (16); + body.AddUInt16LE (1); + body.AddUInt16LE (1); + body.AddUInt32LE (8000); + body.AddUInt32LE (8000); + body.AddUInt16LE (1); + body.AddUInt16LE (8); + if (samples is not null) { + body.AddStringLatin1 ("data"); + body.AddUInt32LE ((uint)samples.Length); + if (samples.Length > 0) + body.Add (samples); + if ((samples.Length & 1) == 1) + body.Add (0); + } + + var text = System.Text.Encoding.ASCII.GetBytes (title + "\0"); + using var info = new BinaryDataBuilder (); + info.AddStringLatin1 ("INFO"); + info.AddStringLatin1 ("INAM"); + info.AddUInt32LE ((uint)text.Length); + info.Add (text); + var list = info.ToBinaryData (); + body.AddStringLatin1 ("LIST"); + body.AddUInt32LE ((uint)list.Length); + body.Add (list); + return Riff (body); + } + + static byte[] Riff (string form) => Riff (System.Text.Encoding.ASCII.GetBytes (form)); + + static byte[] Riff (BinaryDataBuilder body) => Riff (body.ToBinaryData ().Span); + + static byte[] Riff (ReadOnlySpan body) + { + var file = new byte[8 + body.Length]; + "RIFF"u8.CopyTo (file); + BitConverter.GetBytes ((uint)body.Length).CopyTo (file, 4); + body.CopyTo (file.AsSpan (8)); + return file; + } + + static int IndexOf (byte[] data, byte[] pattern) + { + for (var i = 0; i <= data.Length - pattern.Length; i++) { + if (data.AsSpan (i, pattern.Length).SequenceEqual (pattern)) + return i; + } + + return -1; + } + + sealed class ThrowingFileSystem : IFileSystem + { + readonly Exception _error; + public ThrowingFileSystem (Exception error) => _error = error; + public bool FileExists (string path) => true; + public Stream OpenRead (string path) => throw _error; + public Stream OpenReadWrite (string path) => throw _error; + public Stream Create (string path) => throw _error; + public byte[] ReadAllBytes (string path) => throw _error; + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => throw _error; + public void WriteAllBytes (string path, ReadOnlySpan data) => throw _error; + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => throw _error; + public void Delete (string path) => throw _error; + public void Move (string sourcePath, string destinationPath) => throw _error; + public string? GetDirectoryName (string path) => "/"; + public string GetFileName (string path) => path; + public string CombinePath (string path1, string path2) => path1 + path2; + } + + sealed class ReportedLengthStream : Stream + { + public ReportedLengthStream (long length) => Length = length; + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length { get; } + public override long Position { get; set; } + public override void Flush () { } + public override int Read (byte[] buffer, int offset, int count) => 0; + public override long Seek (long offset, SeekOrigin origin) => Position; + public override void SetLength (long value) => throw new NotSupportedException (); + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } + + sealed class NonSeekableStream : Stream + { + readonly Stream _inner; + public NonSeekableStream (Stream inner) => _inner = inner; + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException (); + public override long Position { get => throw new NotSupportedException (); set => throw new NotSupportedException (); } + public override void Flush () { } + public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); + public override long Seek (long offset, SeekOrigin origin) => throw new NotSupportedException (); + public override void SetLength (long value) => throw new NotSupportedException (); + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } +} From d76f0f4f08367479d488e07e6b5f2d4341e85c40 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Tue, 17 Nov 2026 00:44:53 -0700 Subject: [PATCH 3/3] test: Keep a Matroska source path when MediaFile opens a path MediaFile.Read and ReadAsync still record the path so a later save can find the file. A stream opened with only a path hint does not. --- .../Matroska/MatroskaSaveTests.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index e99e113..899172e 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -390,6 +390,38 @@ public void Save_MediaFileRead_SetsSourcePath () Assert.AreEqual ("Media", MatroskaFile.Read (fs.ReadAllBytes ("/media.mkv")).File!.Tag.Title); } + [TestMethod] + public async Task Save_MediaFileReadAsync_SetsSourcePath () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Media")))); + var fs = new MockFileSystem (); + fs.AddFile ("/media-async.mkv", original); + + var opened = await MediaFile.ReadAsync ("/media-async.mkv", fs); + + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = opened.GetFileAs (); + Assert.IsNotNull (file); + Assert.AreEqual ("/media-async.mkv", file!.SourcePath); + file.Tag.Album = "From MediaFile"; + var saved = await file.SaveToFileAsync (fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual ("From MediaFile", MatroskaFile.Read (fs.ReadAllBytes ("/media-async.mkv")).File!.Tag.Album); + Assert.AreEqual ("Media", MatroskaFile.Read (fs.ReadAllBytes ("/media-async.mkv")).File!.Tag.Title); + } + + [TestMethod] + public void Read_StreamPathHint_DoesNotBecomeTheMatroskaSource () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Media")))); + using var stream = new MemoryStream (original); + + var opened = MediaFile.Read (stream, "/hint.mkv"); + + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.IsNull (opened.GetFileAs ()!.SourcePath); + } + [TestMethod] public void Save_SeekHead_KeepsATagsPointerThatStillFits () {