From a4c878b51d55255aca075ee1c7d1ab041e1b5d60 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:49:13 +0800 Subject: [PATCH] ImageDecoder: Open/OpenAsync(Stream) read the header only and stream frame 0 Open(Stream) no longer copies the stream whole. It sniffs 4 KiB, reads the header through the codec's row reader (ImageDecoderRegistration.CreateRowReader) and, for a still file, decodes frame 0's first full-size Decode / CopyPixels straight from the stream. Every other operation reads the whole file first (seeking, or replaying the bytes a non-seekable stream kept) and takes the span path, so results equal Open(byte[]). Codecs without a row reader are read whole at open, as before. - Open(Stream, leaveOpen, forwardOnly) / OpenAsync(..., forwardOnly, ct): forwardOnly keeps nothing a streamed decode reads; later revisits throw InvalidOperationException. - OpenAsync reads the header asynchronously, then prefetches the rest in the background. New ImageFrame.DecodeAsync / CopyPixelsAsync stream alongside the prefetch; sync Decode / CopyPixels wait for it and never read synchronously. - StreamTap: one hold on the stream, by offset, with a recorded prefix/whole for replay; prefetch and readers serialised by a semaphore. - Tests: ImageDecoderStreamingTests (RawStreamCodec + real codecs); the AOT and wasm smoke tests cover the new entry points. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- README.zh-CN.md | 2 +- src/Sdcb.SimdCodecs/ImageDecoder.Streaming.cs | 548 +++++++++++++++++ src/Sdcb.SimdCodecs/ImageDecoder.cs | 175 ++++-- src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt | 4 + src/Sdcb.SimdCodecs/StreamTap.cs | 446 ++++++++++++++ tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs | 32 +- .../Streaming/ImageDecoderStreamingTests.cs | 571 ++++++++++++++++++ 8 files changed, 1723 insertions(+), 57 deletions(-) create mode 100644 src/Sdcb.SimdCodecs/ImageDecoder.Streaming.cs create mode 100644 src/Sdcb.SimdCodecs/StreamTap.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/Streaming/ImageDecoderStreamingTests.cs diff --git a/README.md b/README.md index ae4e09e..a67b138 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ ImageCodecs.Register(HeifImageDecoder.Registration); - `DecodeOptions`: `Region` (a crop; TIFF and HEIF read only the strips or tiles it touches, JPEG, PNG and WebP convert only its rows), `ScaleDenominator` (any power of two for every codec: JPEG 1/2–1/8 and JPEG 2000 resolution levels natively, the rest by a box filter; `TryGetClosestSize` says what a codec does natively), `Pool` (an `ArrayPool` for the pixels), `ApplyOrientation` (EXIF / TIFF orientation applied, the Exif Orientation reset to 1; `GetOutputSize(info)` sizes a buffer). Every entry point takes a `CancellationToken`. - `ImageCodecs.TryReadInfo(file, out info)`: from the headers alone: format, size, stored bit depth, colour encoding (PQ / HLG HDR?), resolution (DPI), EXIF orientation, frame or page count, whether there is a thumbnail. - `ImageCodecs.TryReadMetadata(file, out metadata)` / `TryDecodeThumbnail(file, out thumb)`: the Exif, XMP and ICC blocks for a transcoder to pass on, and the embedded preview (Exif IFD1, HEIF `thmb`). `PixelTransform.Orient` turns pixels you decoded without `ApplyOrientation`. -- `ImageDecoder.Open(stream | path | memory)` / `OpenAsync(stream)`: a WIC-style session: `Format`, `FrameCount`, then `GetFrame(i).Decode(options)` or `.CopyPixels(region, format, buffer, stride)`. A file path is memory-mapped; a non-seekable stream such as an upload is buffered for you. +- `ImageDecoder.Open(stream | path | memory)` / `OpenAsync(stream)`: a WIC-style session: `Format`, `FrameCount`, then `GetFrame(i).Decode(options)` or `.CopyPixels(region, format, buffer, stride)`. A file path is memory-mapped. A stream is read only as far as its header at open; when the codec decodes from a stream, the first full-size decode of frame 0 reads its rows as they arrive (`await frame.DecodeAsync()` / `CopyPixelsAsync` for a request body), and anything that needs the file again reads it whole first, from the bytes a non-seekable stream keeps as it is read. `Open(stream, leaveOpen, forwardOnly: true)` keeps nothing, so a single streamed decode never holds the file, and a later revisit throws `InvalidOperationException`. - `ImageCodecs.TryOpenFrames(file, out reader)`: every frame by index, in any layout: animated WebP / GIF / APNG frames with durations, multi-page TIFF and JBIG2 pages, the images of an icon. `reader.EnumerateFramesInto(buffer, stride, format)` plays them through one buffer. - `ImageCodecs.Encode(image, format, stream | writer, options)` / `Encode(pixels, width, height, pixelFormat, format, …)` / `CreateEncoder(format, writer)`: every encoder takes every `PixelFormat`, rows at any stride, and writes the image's metadata; `GetClosestInputFormat` shows where an 8-bit format narrows. The options are the format's own type (`JpegEncodeOptions`, `WebpLossyEncodeOptions`, …; null for its defaults); WebP with no options is lossy. An encoder session takes the image in bands and several frames for an animation. - `ImageCodecs.TryReadPlanarInfo` / `TryDecodePlanes`: the YCbCr planes as coded (HEIF), for video pipelines and GPU upload. diff --git a/README.zh-CN.md b/README.zh-CN.md index f2a1bd7..d9fb916 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -65,7 +65,7 @@ ImageCodecs.Register(HeifImageDecoder.Registration); - `DecodeOptions`:`Region`(裁剪;TIFF 和 HEIF 只读与区域相交的条带或分块,JPEG、PNG、WebP 只转换区域内的行)、`ScaleDenominator`(每个 codec 都接受任意 2 的幂:JPEG 的 1/2–1/8 和 JPEG 2000 的分辨率级别是原生的,其余用 box 滤波;`TryGetClosestSize` 告诉你 codec 原生能做到什么)、`Pool`(像素用的 `ArrayPool`)、`ApplyOrientation`(应用 EXIF / TIFF 方向,Exif 里的方向改写为 1;缓冲区尺寸用 `GetOutputSize(info)` 算)。所有入口都接受 `CancellationToken`。 - `ImageCodecs.TryReadInfo(file, out info)`:只读文件头:格式、尺寸、存储位深、颜色编码(是不是 PQ / HLG HDR)、分辨率(DPI)、EXIF 方向、帧数或页数、有没有缩略图。 - `ImageCodecs.TryReadMetadata(file, out metadata)` / `TryDecodeThumbnail(file, out thumb)`:取出 Exif、XMP、ICC 原始块供转码透传,以及内嵌的预览图(Exif IFD1、HEIF `thmb`)。没开 `ApplyOrientation` 解出的像素,可以事后用 `PixelTransform.Orient` 转正。 -- `ImageDecoder.Open(stream | path | memory)` / `OpenAsync(stream)`:WIC 式的会话:`Format`、`FrameCount`,再 `GetFrame(i).Decode(options)` 或 `.CopyPixels(region, format, buffer, stride)`。文件路径用内存映射;上传这类不可寻址的流会替你缓冲。 +- `ImageDecoder.Open(stream | path | memory)` / `OpenAsync(stream)`:WIC 式的会话:`Format`、`FrameCount`,再 `GetFrame(i).Decode(options)` 或 `.CopyPixels(region, format, buffer, stride)`。文件路径用内存映射。打开流时只读到头部为止;编解码器支持从流解码时,第 0 帧第一次全尺寸解码直接按到达的数据逐行读取(请求体用 `await frame.DecodeAsync()` / `CopyPixelsAsync`),之后需要再次读文件的操作先读入整个文件,不可寻址的流用的是读取时保留下来的字节。`Open(stream, leaveOpen, forwardOnly: true)` 不保留任何字节,一次流式解码从不持有整个文件,之后再回头读会抛 `InvalidOperationException`。 - `ImageCodecs.TryOpenFrames(file, out reader)`:按索引、以任意布局逐帧解码:动画 WebP / GIF / APNG 的帧及其时长,多页 TIFF 和 JBIG2 的各页,图标里的每张图。`reader.EnumerateFramesInto(buffer, stride, format)` 用同一块缓冲区按顺序播放。 - `ImageCodecs.Encode(image, format, stream | writer, options)` / `Encode(pixels, width, height, pixelFormat, format, …)` / `CreateEncoder(format, writer)`:每个编码器都接收任意 `PixelFormat` 和任意行跨度,并写入图像的元数据;只能存 8 位的格式会在哪里降精度,用 `GetClosestInputFormat` 可以先看到。options 是该格式自己的类型(`JpegEncodeOptions`、`WebpLossyEncodeOptions` 等;null 表示默认值);WebP 不传 options 时为有损。编码会话可以按行带分批写入,也可以写多帧动画。 - `ImageCodecs.TryReadPlanarInfo` / `TryDecodePlanes`:按编码原样输出 YCbCr 平面(HEIF),供视频管线和 GPU 上传使用。 diff --git a/src/Sdcb.SimdCodecs/ImageDecoder.Streaming.cs b/src/Sdcb.SimdCodecs/ImageDecoder.Streaming.cs new file mode 100644 index 0000000..5ed2e8c --- /dev/null +++ b/src/Sdcb.SimdCodecs/ImageDecoder.Streaming.cs @@ -0,0 +1,548 @@ +using System; +using System.Buffers; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs; + +// The stream side of the session: open reads the header only, frame 0's first full-size decode streams its rows, and +// everything else reads the whole file first (EnsureData) and takes the span path. +public sealed partial class ImageDecoder +{ + internal const string ForwardOnlyMessage = + "The session was opened forward-only and its decode has read past bytes it did not keep: this operation needs the " + + "whole file. Open it without forwardOnly (the bytes are then kept as they are read), or from memory."; + + private readonly StreamTap? _tap; + private readonly bool _forwardOnly; + private StreamingRowReader? _header; // the header reader, until a decode takes it over + private ImageFrameInfo? _streamFrame; // frame 0 as the header reader saw it + + private ImageDecoder(StreamTap tap, bool forwardOnly) + { + _tap = tap; + _forwardOnly = forwardOnly; + _codec = null!; // set by Start or SetData before the session is handed out + } + + /// + /// Opens an image from , positioned at its start, reading only as much as the codec's + /// header takes. When the codec decodes from a stream, frame 0's first full-size decode reads its rows from the + /// stream as they arrive; any other operation reads the whole file first (see ). A codec + /// that does not decode from a stream has the whole file read here. + /// + /// The stream. A seekable one is read where needed by seeking and never held in memory whole + /// for a streamed decode. + /// Keep open when the session is disposed. + /// For a non-seekable stream: do not keep the bytes a streamed decode reads, so the session + /// never holds the whole file. Once that decode has started, an operation that needs the file again (another decode, + /// , a thumbnail, another frame) throws , and the decoded + /// image's holds only the blocks before the pixels. No effect on a seekable + /// stream. + /// No registered codec recognises the data (the message names the format detects, as does), or the file is malformed (the message gives the codec's reason). + public static ImageDecoder Open(Stream stream, bool leaveOpen, bool forwardOnly) + { + var decoder = new ImageDecoder(CreateTap(stream, leaveOpen, asyncOnly: false), forwardOnly); + try + { + decoder.Start(); + return decoder; + } + catch + { + decoder.Dispose(); + throw; + } + } + + /// + /// Opens an image from , reading its header asynchronously, and never reads the stream + /// synchronously afterwards. A non-seekable stream (an HTTP request body, a network stream) is then read on in the + /// background into memory the session keeps, unless : + /// and take over from that read and decode the rows as they arrive, while the + /// synchronous and wait for it and decode from + /// memory. Disposing the session stops the background read. + /// + /// The stream. + /// Keep open when the session is disposed. + /// As for ; there is no background read then, and a + /// synchronous call blocks on the asynchronous reads it needs. + /// Cancels the header read (not the background read, which the session's disposal stops). + /// No registered codec recognises the data (the message names the format detects, as does), or the file is malformed (the message gives the codec's reason). + /// was cancelled while reading. + public static async ValueTask OpenAsync(Stream stream, bool leaveOpen, bool forwardOnly, + CancellationToken cancellationToken = default) + { + var decoder = new ImageDecoder(CreateTap(stream, leaveOpen, asyncOnly: true), forwardOnly); + try + { + await decoder.StartAsync(cancellationToken).ConfigureAwait(false); + return decoder; + } + catch + { + decoder.Dispose(); + throw; + } + } + + private static StreamTap CreateTap(Stream stream, bool leaveOpen, bool asyncOnly) + { + ArgumentNullException.ThrowIfNull(stream); + try + { + return new StreamTap(stream, leaveOpen, asyncOnly); + } + catch + { + if (!leaveOpen) stream.Dispose(); + throw; + } + } + + private void Start() + { + _tap!.Sniff(); + if (Probe() is { } codec) + { + var reader = codec.CreateRowReader!(HeaderInput(), PixelFormat.Rgba32, null); + try + { + reader.Initialize(); + } + catch (InvalidDataException) + { + // The span path decides, so a malformed file fails (or a lenient codec succeeds) as from memory. + reader.Dispose(); + reader = null; + } + catch + { + reader.Dispose(); + throw; + } + if (KeepHeader(codec, reader)) + return; + } + SetData(_tap.ReadAll()); + } + + private async ValueTask StartAsync(CancellationToken cancellationToken) + { + await _tap!.SniffAsync(cancellationToken).ConfigureAwait(false); + if (Probe() is { } codec) + { + var reader = codec.CreateRowReader!(HeaderInput(), PixelFormat.Rgba32, null); + try + { + await reader.InitializeAsync(cancellationToken).ConfigureAwait(false); + } + catch (InvalidDataException) + { + reader.Dispose(); + reader = null; + } + catch + { + reader.Dispose(); + throw; + } + if (KeepHeader(codec, reader)) + { + // Without threads a synchronous call could not block on an asynchronous read: read it all now. + if (OperatingSystem.IsBrowser() || OperatingSystem.IsWasi()) + await EnsureDataAsync(cancellationToken).ConfigureAwait(false); + else if (!_tap.CanSeek && !_forwardOnly) + _tap.StartPrefetch(); + return; + } + } + SetData(await _tap.ReadAllAsync(cancellationToken).ConfigureAwait(false)); + } + + // The codec whose streaming reader takes the stream, judged from the sniffed bytes: the first that claims them, if + // it has a row reader and no earlier codec has its format. Two codecs of one format (a gain-map JPEG before the + // plain one) tell their files apart by what lies beyond the sniffed bytes, so that file is sniffed whole instead. + private ImageDecoderRegistration? Probe() + { + var prefix = _tap!.Recorded; + var registry = ImageCodecs.RegistrySnapshot; + for (var i = 0; i < registry.Length; i++) + { + if (!registry[i].CanDecode(prefix)) + continue; + if (registry[i].CreateRowReader is null) + return null; + for (var j = 0; j < i; j++) + { + if (registry[j].Format == registry[i].Format) + return null; + } + return registry[i]; + } + return null; + } + + // Keeps a header reader that streams a file of one frame; false (and the reader disposed) otherwise. + private bool KeepHeader(ImageDecoderRegistration codec, StreamingRowReader? reader) + { + if (reader is null) + return false; + // A reader that fell back has read and decoded the whole file already; the span path takes it from there. + if (!reader.IsStreaming || (codec.TryOpenFrames is not null && reader.Info.FrameCount != 1)) + { + reader.Dispose(); + return false; + } + _codec = codec; + _header = reader; + _streamFrame = new ImageFrameInfo(codec.TryOpenFrames is null ? reader.Info with { FrameCount = 1 } : reader.Info, null); + return true; + } + + private StreamInput HeaderInput() => new(new TapStream(_tap!), initialCapacity: StreamTap.SniffLength); + + private void EnsureData() => EnsureData(CancellationToken.None); + + /// Makes the whole file available for the span path (on an async-opened session, by waiting for the + /// asynchronous reads, observing ). + internal void EnsureData(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_frames is not null) + return; + _tap!.SyncCancellation = cancellationToken; + try + { + SetData(_tap.ReadAll()); + } + finally + { + _tap.SyncCancellation = default; + } + } + + /// Frame 's info from the whole file, when it may differ from the header's (frame 0 of + /// a stream session); null otherwise. + internal ImageInfo? FileFrameInfo(int index, CancellationToken cancellationToken) + { + if (index != 0 || _streamFrame is null) + return null; + EnsureData(cancellationToken); + return _frames!.TryGetFrameInfo(0, out var frame) ? frame.Info : null; + } + + /// Makes the whole file available (reading the rest of the stream asynchronously) for the span path. + internal async ValueTask EnsureDataAsync(CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_frames is null) + SetData(await _tap!.ReadAllAsync(cancellationToken).ConfigureAwait(false)); + } + + private void SetData(ReadOnlyMemory data) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var (codec, frames) = OpenFrames(data); + _header?.Dispose(); + _header = null; + _codec = codec; + _data = data; + _frames = frames; + _source = ByteSource.FromMemory(data); + } + + // Frame 0, the whole image at full size, before any other decode, from a codec that streams this file. + private bool CanStream(int index, DecodeOptions? options) + { + ObjectDisposedException.ThrowIf(_disposed, this); + return index == 0 && _frames is null && _header is not null && StreamingRowReader.IsFullImage(options); + } + + /// Streams frame 0 into ; false when the span path must decode it. + internal bool TryStreamInto(int index, Span destination, int stride, PixelFormat format, DecodeOptions? options, + CancellationToken cancellationToken) + { + // An async-opened session's synchronous call waits for the background read instead (EnsureData). + if (!CanStream(index, options) || _tap!.HasPrefetch) + return false; + StreamingRowReader? reader = null; + _tap.SyncCancellation = cancellationToken; + try + { + reader = TakeReader(format, cancellationToken); + reader.ReadRows(destination, reader.Height, stride, cancellationToken); + return true; + } + catch (InvalidDataException e) + { + return _tap.CanRevisit ? false : throw StreamFailure(e); + } + finally + { + reader?.Dispose(); + _tap.SyncCancellation = default; + } + } + + /// , reading the stream asynchronously. + internal async ValueTask TryStreamIntoAsync(int index, Memory destination, int stride, PixelFormat format, + DecodeOptions? options, CancellationToken cancellationToken) + { + if (!CanStream(index, options)) + return false; + StreamingRowReader? reader = null; + try + { + reader = await TakeReaderAsync(format, cancellationToken).ConfigureAwait(false); + await reader.ReadRowsAsync(destination, reader.Height, stride, cancellationToken).ConfigureAwait(false); + return true; + } + catch (InvalidDataException e) + { + return _tap!.CanRevisit ? false : throw StreamFailure(e); + } + finally + { + reader?.Dispose(); + } + } + + /// + /// Streams frame 0 into a new image in the codec's own layout, equal to what + /// returns; null when the span path must decode it. Not for a seekable stream: the image's metadata needs the + /// whole file, which the span path reads once instead of twice. + /// + internal IDecodedImage? TryStreamDecode(int index, DecodeOptions? options, CancellationToken cancellationToken) + { + if (!CanStream(index, options) || _tap!.HasPrefetch || _tap.CanSeek || !TryGetLayout(out var info, out var format, out var length)) + return null; + var pool = options?.Pool; + var pixels = pool is null ? GC.AllocateUninitializedArray(length) : pool.Rent(length); + StreamingRowReader? reader = null; + var decoded = false; + IDecodedImage? image = null; + _tap.SyncCancellation = cancellationToken; + try + { + reader = TakeReader(format, cancellationToken); + reader.ReadRows(pixels.AsSpan(0, length), reader.Height, 0, cancellationToken); + reader.Dispose(); + reader = null; + ImageMetadata metadata; + if (_tap.CanRevisit) + { + EnsureData(cancellationToken); + metadata = Metadata; + } + else + { + metadata = HeaderMetadata(); + } + decoded = true; + return image = Wrap(info, pixels, length, pool, metadata); + } + catch (InvalidDataException e) when (!decoded) + { + return _tap.CanRevisit ? null : throw StreamFailure(e); + } + finally + { + reader?.Dispose(); + if (image is null) + pool?.Return(pixels); + _tap.SyncCancellation = default; + } + } + + /// , reading the stream asynchronously. + internal async ValueTask TryStreamDecodeAsync(int index, DecodeOptions? options, CancellationToken cancellationToken) + { + if (!CanStream(index, options) || _tap!.CanSeek || !TryGetLayout(out var info, out var format, out var length)) + return null; + var pool = options?.Pool; + var pixels = pool is null ? GC.AllocateUninitializedArray(length) : pool.Rent(length); + StreamingRowReader? reader = null; + var decoded = false; + IDecodedImage? image = null; + try + { + reader = await TakeReaderAsync(format, cancellationToken).ConfigureAwait(false); + await reader.ReadRowsAsync(pixels.AsMemory(0, length), reader.Height, 0, cancellationToken).ConfigureAwait(false); + reader.Dispose(); + reader = null; + ImageMetadata metadata; + if (_tap.CanRevisit) + { + await EnsureDataAsync(cancellationToken).ConfigureAwait(false); + metadata = Metadata; + } + else + { + metadata = HeaderMetadata(); + } + decoded = true; + return image = Wrap(info, pixels, length, pool, metadata); + } + catch (InvalidDataException e) when (!decoded) + { + return _tap.CanRevisit ? null : throw StreamFailure(e); + } + finally + { + reader?.Dispose(); + if (image is null) + pool?.Return(pixels); + } + } + + // Frame 0's own layout (what TryDecode returns): its channels at its sample width. False for float samples, which + // no row reader writes, and for a raster too large for one array (the span path says so). + private bool TryGetLayout(out ImageInfo info, out PixelFormat format, out int length) + { + info = _streamFrame!.Value.Info; + format = default; + length = 0; + if (info.SampleFormat is not (SampleFormat.UInt8 or SampleFormat.UInt16) || info.Channels is < 1 or > 4) + return false; + format = PixelFormat.ForChannels(info.Channels, info.SampleFormat); + var bytes = (long)info.Width * info.Height * format.BytesPerPixel; + if (bytes > Array.MaxLength) + return false; + length = (int)bytes; + return true; + } + + private static RasterImage Wrap(in ImageInfo info, byte[] pixels, int length, ArrayPool? pool, ImageMetadata metadata) + { + var bitDepth = info.BitDepth == RasterImage.BytesPerSample(info.SampleFormat) * 8 ? 0 : info.BitDepth; + return pool is null + ? RasterImage.Wrap(info.Width, info.Height, info.Channels, info.SampleFormat, pixels, info.ColorEncoding, bitDepth, metadata) + : RasterImage.Wrap(info.Width, info.Height, info.Channels, info.SampleFormat, new PooledPixels(pool, pixels, length), + info.ColorEncoding, bitDepth, metadata); + } + + // A forward-only decode's metadata: what the codec finds in the bytes read before the pixels. + private ImageMetadata HeaderMetadata() + { + try + { + return _codec.TryReadMetadata(_tap!.Recorded, out var metadata) ? metadata : ImageMetadata.Empty; + } + catch (InvalidDataException) + { + return ImageMetadata.Empty; + } + } + + // The reader a decode in `format` uses: the header reader when it writes that format, otherwise a new one that + // reads the header again (from the record, or by seeking). The header reader is used up either way. + private StreamingRowReader TakeReader(PixelFormat format, CancellationToken cancellationToken) + { + if (TakeHeader(format) is { } header) + return header; + var reader = _codec.CreateRowReader!(new StreamInput(new TapStream(_tap!)), format, null); + try + { + reader.Initialize(cancellationToken); + return CheckSize(reader); + } + catch + { + reader.Dispose(); + throw; + } + } + + private async ValueTask TakeReaderAsync(PixelFormat format, CancellationToken cancellationToken) + { + if (TakeHeader(format) is { } header) + return header; + var reader = _codec.CreateRowReader!(new StreamInput(new TapStream(_tap!)), format, null); + try + { + await reader.InitializeAsync(cancellationToken).ConfigureAwait(false); + return CheckSize(reader); + } + catch + { + reader.Dispose(); + throw; + } + } + + private StreamingRowReader? TakeHeader(PixelFormat format) + { + var header = _header!; + _header = null; + if (_forwardOnly) + _tap!.StopRecording(); // what is recorded so far (the header) stays readable for a new reader + if (header.Format == format && header.RowsRead == 0) + return header; + header.Dispose(); + return null; + } + + private StreamingRowReader CheckSize(StreamingRowReader reader) + { + var info = _streamFrame!.Value.Info; + if (!reader.IsStreaming || reader.Width != info.Width || reader.Height != info.Height) + throw new InvalidDataException($"The {ImageCodecs.FormatName(_codec.Format)} header reads differently the second time."); + return reader; + } + + private InvalidDataException StreamFailure(InvalidDataException e) => + new($"The {ImageCodecs.FormatName(_codec.Format)} file cannot be decoded: {e.Message}", e); + + // Pixels rented from a decode's pool, returned when the image is disposed. + private sealed class PooledPixels(ArrayPool pool, byte[] array, int length) : IMemoryOwner + { + private byte[]? _array = array; + + public Memory Memory => (_array ?? throw new ObjectDisposedException(nameof(PooledPixels))).AsMemory(0, length); + + public void Dispose() + { + if (Interlocked.Exchange(ref _array, null) is { } a) + pool.Return(a); + } + } +} + +/// A forward-only view of a from offset 0: what a row reader's input reads. +internal sealed class TapStream(StreamTap tap) : Stream +{ + private long _position; + + 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 => _position; set => throw new NotSupportedException(); } + public override void Flush() { } + 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(); + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var n = tap.Read(_position, buffer); + _position += n; + return n; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var n = await tap.ReadAsync(_position, buffer, cancellationToken).ConfigureAwait(false); + _position += n; + return n; + } +} diff --git a/src/Sdcb.SimdCodecs/ImageDecoder.cs b/src/Sdcb.SimdCodecs/ImageDecoder.cs index fb16f78..e97289e 100644 --- a/src/Sdcb.SimdCodecs/ImageDecoder.cs +++ b/src/Sdcb.SimdCodecs/ImageDecoder.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; namespace Sdcb.SimdCodecs; @@ -17,16 +18,22 @@ namespace Sdcb.SimdCodecs; /// frame reader, it is not safe to share between threads. Dispose it to release the file and that state. /// /// -/// In 2.0 the file is read into memory once at (memory and mapped files are used in -/// place); codecs that can decode incrementally from the source will do so in a later release, behind the same API. +/// Memory and mapped files are decoded in place. A stream is read only as far as its header at +/// : when the codec decodes from a stream (), +/// the first full-size decode of frame 0 (, and +/// their async forms) reads its rows straight from the stream as it arrives. Everything else — another decode, a region, +/// a scale, orientation, other frames, the metadata, a thumbnail — needs the whole file and reads it first (a +/// seekable stream by seeking, a non-seekable one from the bytes the session kept as it read them), so every result +/// equals what over the same bytes gives. A codec that does not decode from a +/// stream reads the whole file at open, as before. /// /// -public sealed class ImageDecoder : IDisposable +public sealed partial class ImageDecoder : IDisposable { - private readonly IByteSource _source; - private readonly ReadOnlyMemory _data; - private readonly ImageDecoderRegistration _codec; - private readonly IImageFrameReader _frames; + private IByteSource? _source; + private ReadOnlyMemory _data; + private ImageDecoderRegistration _codec; + private IImageFrameReader? _frames; private ImageMetadata? _metadata; private bool _disposed; @@ -38,11 +45,13 @@ private ImageDecoder(IByteSource source, ReadOnlyMemory data, ImageDecoder _frames = frames; } - /// Opens an image from , positioned at its start. - /// The stream; a non-seekable one is buffered whole. + /// Opens an image from , positioned at its start, reading only its header (see + /// ); a non-seekable stream's bytes are kept as they are read, so every + /// operation works. + /// The stream. /// Keep open when the session is disposed. /// No registered codec recognises the data (the message names the format detects, as does), or the file is malformed (the message gives the codec's reason). - public static ImageDecoder Open(Stream stream, bool leaveOpen = false) => Open(ByteSource.FromStream(stream, leaveOpen)); + public static ImageDecoder Open(Stream stream, bool leaveOpen = false) => Open(stream, leaveOpen, forwardOnly: false); /// Opens an image held in memory, which the caller keeps unchanged while the session is used. /// No registered codec recognises the data (the message names the format detects, as does), or the file is malformed (the message gives the codec's reason). @@ -60,14 +69,7 @@ public static ImageDecoder Open(IByteSource source) try { var data = source.GetMemory(); - if (ImageCodecs.Find(data.Span) is not { } codec) - throw new InvalidDataException(ImageCodecs.NoCodecMessage(data.Span)); - if (!ImageCodecs.TryOpenFrames(data, out var frames)) - { - // The frame reader gives no reason; the codec's Decode does (only on this failure path). - throw ImageCodecs.DecodeFailure(codec, data.Span, null, default, - $"The {ImageCodecs.FormatName(codec.Format)} file is malformed: its frames cannot be read.")!; - } + var (codec, frames) = OpenFrames(data); return new ImageDecoder(source, data, codec, frames); } catch @@ -78,40 +80,27 @@ public static ImageDecoder Open(IByteSource source) } /// - /// Opens an image from , reading a non-seekable stream (an HTTP request body, a network - /// stream) asynchronously into memory first. + /// Opens an image from , reading its header asynchronously; a non-seekable stream (an HTTP + /// request body, a network stream) is then read on in the background into memory the session keeps (see + /// ). /// /// No registered codec recognises the data (the message names the format detects, as does), or the file is malformed (the message gives the codec's reason). /// was cancelled while reading. - public static async ValueTask OpenAsync(Stream stream, bool leaveOpen = false, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(stream); - if (stream.CanSeek) - return Open(stream, leaveOpen); - var buffer = new MemoryStream(); - try - { - await stream.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); - } - finally - { - if (!leaveOpen) - await stream.DisposeAsync().ConfigureAwait(false); - } - return Open(buffer.GetBuffer().AsMemory(0, (int)buffer.Length)); - } + public static ValueTask OpenAsync(Stream stream, bool leaveOpen = false, CancellationToken cancellationToken = default) => + OpenAsync(stream, leaveOpen, forwardOnly: false, cancellationToken); /// The file's format. public ImageFormat Format => _codec.Format; /// The frames the session decodes: 1 for a still image. - public int FrameCount => _frames.FrameCount; + public int FrameCount => _frames?.FrameCount ?? (_codec.TryOpenFrames is null || _streamFrame is not null ? 1 : Frames.FrameCount); /// For an animation, how many times it plays (0: forever); null for pages and stills. - public int? LoopCount => _frames.LoopCount; + public int? LoopCount => _frames is null && _codec.TryOpenFrames is null ? null : Frames.LoopCount; /// The file's metadata blocks (Exif, XMP, ICC); when it has none. Read /// from the file once, on first use. + /// A forward-only session's decode has read past bytes it did not keep. public ImageMetadata Metadata { get @@ -128,8 +117,10 @@ public ImageFrame GetFrame(int index) { ObjectDisposedException.ThrowIf(_disposed, this); ArgumentOutOfRangeException.ThrowIfNegative(index); + if (index == 0 && _frames is null && _streamFrame is { } streamed) + return new ImageFrame(this, 0, streamed); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, FrameCount); - if (!_frames.TryGetFrameInfo(index, out var frame)) + if (!Frames.TryGetFrameInfo(index, out var frame)) throw FrameFailure(index, null, default, $"Frame {index} cannot be read."); return new ImageFrame(this, index, frame); } @@ -144,11 +135,12 @@ internal InvalidDataException FrameFailure(int index, DecodeOptions? options, Ca ? ImageCodecs.DecodeFailure(_codec, Data, options, cancellationToken, fallback)! : new InvalidDataException(fallback); + /// The whole file, read first when the session was opened over a stream. internal ReadOnlySpan Data { get { - ObjectDisposedException.ThrowIf(_disposed, this); + EnsureData(); return _data.Span; } } @@ -159,18 +151,37 @@ internal IImageFrameReader Frames { get { - ObjectDisposedException.ThrowIf(_disposed, this); - return _frames; + EnsureData(); + return _frames!; } } - /// Releases the file and the decoding state. + /// Releases the file and the decoding state; a session over a stream stops reading it and, unless told to + /// leave it open, disposes it. public void Dispose() { if (_disposed) return; _disposed = true; - _frames.Dispose(); - _source.Dispose(); + _header?.Dispose(); + _header = null; + _frames?.Dispose(); + _source?.Dispose(); + _tap?.Dispose(); + _data = default; + } + + // The codec that claims the whole file and its frame reader, or the exception Open throws. + private static (ImageDecoderRegistration Codec, IImageFrameReader Frames) OpenFrames(ReadOnlyMemory data) + { + if (ImageCodecs.Find(data.Span) is not { } codec) + throw new InvalidDataException(ImageCodecs.NoCodecMessage(data.Span)); + if (!ImageCodecs.TryOpenFrames(data, out var frames)) + { + // The frame reader gives no reason; the codec's Decode does (only on this failure path). + throw ImageCodecs.DecodeFailure(codec, data.Span, null, default, + $"The {ImageCodecs.FormatName(codec.Format)} file is malformed: its frames cannot be read.")!; + } + return (codec, frames); } } @@ -194,7 +205,9 @@ internal ImageFrame(ImageDecoder decoder, int index, ImageFrameInfo frame) /// The frame's index in the session. public int Index => _index; - /// The frame's layout, colour encoding and resolution, as reports. + /// The frame's layout, colour encoding and resolution, as reports. For + /// frame 0 of a session over a stream, before the whole file has been read, it is what the codec's header reader + /// reports: a value the file stores after the pixels (such as an orientation in a trailing Exif block) is not in it. public ImageInfo Info { get; } /// How long an animation shows the frame; null for a page or a still. @@ -221,12 +234,21 @@ public bool TryGetClosestSize(int width, int height, out int closestWidth, out i return true; } - /// Decodes the frame at its full fidelity (see ). Dispose the result. + /// + /// Decodes the frame at its full fidelity (see ). Dispose the result. The first + /// full-size decode of frame 0 of a session over a stream reads its rows from the stream as it arrives (see + /// ); on a session from + /// this call instead waits for the background read and decodes from memory, never reading the stream synchronously. + /// /// The frame is undecodable. /// does not lie inside the frame. /// was cancelled. + /// A forward-only session has already streamed its decode. public IDecodedImage Decode(DecodeOptions? options = null, CancellationToken cancellationToken = default) { + if (_decoder.TryStreamDecode(_index, options, cancellationToken) is { } streamed) + return streamed; + _decoder.EnsureData(cancellationToken); if (!_decoder.Frames.TryDecodeFrame(_index, out var image, options, cancellationToken)) { // A codec returns false for an image whose raster does not fit one array; say so, and what to do instead. @@ -245,23 +267,70 @@ public IDecodedImage Decode(DecodeOptions? options = null, CancellationToken can return image; } + /// + /// , reading the stream asynchronously: the first full-size decode of frame 0 of a session over a + /// stream reads its rows as they arrive (taking over from the background read of + /// where it has got to); anything else first + /// reads the whole file asynchronously. + /// + /// + public async ValueTask DecodeAsync(DecodeOptions? options = null, CancellationToken cancellationToken = default) + { + if (await _decoder.TryStreamDecodeAsync(_index, options, cancellationToken).ConfigureAwait(false) is { } streamed) + return streamed; + await _decoder.EnsureDataAsync(cancellationToken).ConfigureAwait(false); + return Decode(options, cancellationToken); + } + /// /// Decodes the frame into in , rows /// bytes apart (0: tightly packed): of it (null: all of it), at - /// ' scale. Size the buffer from and the region. + /// ' scale. Size the buffer from and the region. A session over a stream + /// streams the first full-size copy of frame 0 as does. /// /// The destination does not fit, or the region does not lie inside the frame. /// The frame is undecodable, or has no integer projection (float samples, /// or an HDR transfer a codec refuses to project). /// was cancelled. + /// A forward-only session has already streamed its decode. public void CopyPixels(PixelRect? region, PixelFormat format, Span destination, int stride, DecodeOptions? options = null, CancellationToken cancellationToken = default) { - var effective = region is null ? options : (options ?? DecodeOptions.Default) with { Region = region }; - var (w, h) = (effective ?? DecodeOptions.Default).GetOutputSize(Info); - if (!PixelConverter.TryGetLayout(w, h, format, stride, destination.Length, out _)) - throw new ArgumentException($"The destination does not hold a {w}x{h} {format} image at stride {stride}.", nameof(destination)); + var effective = CheckDestination(region, format, destination.Length, stride, options, cancellationToken); + if (_decoder.TryStreamInto(_index, destination, stride, format, effective, cancellationToken)) + return; + _decoder.EnsureData(cancellationToken); if (!_decoder.Frames.TryDecodeFrameInto(_index, destination, stride, format, effective, cancellationToken)) throw _decoder.FrameFailure(_index, effective, cancellationToken, $"Frame {_index} could not be decoded to {format}."); } + + /// , reading the stream asynchronously (see ). + /// + public async ValueTask CopyPixelsAsync(PixelRect? region, PixelFormat format, Memory destination, int stride, + DecodeOptions? options = null, CancellationToken cancellationToken = default) + { + if (!StreamingRowReader.IsFullImage(Effective(region, options))) + await _decoder.EnsureDataAsync(cancellationToken).ConfigureAwait(false); + var effective = CheckDestination(region, format, destination.Length, stride, options, cancellationToken); + if (await _decoder.TryStreamIntoAsync(_index, destination, stride, format, effective, cancellationToken).ConfigureAwait(false)) + return; + await _decoder.EnsureDataAsync(cancellationToken).ConfigureAwait(false); + CopyPixels(region, format, destination.Span, stride, options, cancellationToken); + } + + private static DecodeOptions? Effective(PixelRect? region, DecodeOptions? options) => + region is null ? options : (options ?? DecodeOptions.Default) with { Region = region }; + + private DecodeOptions? CheckDestination(PixelRect? region, PixelFormat format, int length, int stride, DecodeOptions? options, + CancellationToken cancellationToken) + { + var effective = Effective(region, options); + // A streamed copy is the header's size. Anything else is sized from the whole file's frame info, which a value + // stored after the pixels (an orientation in a trailing Exif block) can change. + var info = StreamingRowReader.IsFullImage(effective) ? Info : _decoder.FileFrameInfo(_index, cancellationToken) ?? Info; + var (w, h) = (effective ?? DecodeOptions.Default).GetOutputSize(info); + if (!PixelConverter.TryGetLayout(w, h, format, stride, length, out _)) + throw new ArgumentException($"The destination does not hold a {w}x{h} {format} image at stride {stride}.", "destination"); + return effective; + } } diff --git a/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt index 7dc5c58..ecbad6a 100644 --- a/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt @@ -1 +1,5 @@ #nullable enable +Sdcb.SimdCodecs.ImageFrame.CopyPixelsAsync(Sdcb.SimdCodecs.Abstractions.PixelRect? region, Sdcb.SimdCodecs.Abstractions.PixelFormat format, System.Memory destination, int stride, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Sdcb.SimdCodecs.ImageFrame.DecodeAsync(Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static Sdcb.SimdCodecs.ImageDecoder.Open(System.IO.Stream! stream, bool leaveOpen, bool forwardOnly) -> Sdcb.SimdCodecs.ImageDecoder! +static Sdcb.SimdCodecs.ImageDecoder.OpenAsync(System.IO.Stream! stream, bool leaveOpen, bool forwardOnly, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/Sdcb.SimdCodecs/StreamTap.cs b/src/Sdcb.SimdCodecs/StreamTap.cs new file mode 100644 index 0000000..49db277 --- /dev/null +++ b/src/Sdcb.SimdCodecs/StreamTap.cs @@ -0,0 +1,446 @@ +using System; +using System.Buffers; +using System.IO; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Sdcb.SimdCodecs; + +/// +/// An session's one hold on its stream: every read of the stream goes through it, by offset +/// from the start of the image, so the header reader, a decode's row reader and the whole-file fallback can each read +/// from offset 0 without the stream being able to seek. +/// +/// A seekable stream is read where asked by seeking. A non-seekable one is read forward only; while the tap +/// records, every byte read is kept () and an earlier offset is served from the record. +/// A session that retains its input records for its whole life; a forward-only one stops when its decode starts +/// streaming (), and from then on only the live position and what was recorded before can be +/// read ( is false). +/// +/// +/// Concurrency: an async-opened session runs a background prefetch () beside the session's +/// own reads. One stream read is in flight at a time (); the record and the counters change only +/// under , and a read copies out of the record under it too. The record only grows by reallocating, +/// never in place, so a reader never sees a half-copied buffer. With asyncOnly (a session from +/// OpenAsync) a synchronous read is served by the asynchronous path, so the stream is never read synchronously. +/// +/// +internal sealed class StreamTap : IDisposable +{ + /// How many leading bytes the session reads before it picks a codec. + public const int SniffLength = 4096; + + private const int ChunkLength = 64 * 1024; + + private readonly Stream _stream; + private readonly bool _leaveOpen; + private readonly long _origin; + private readonly object _gate = new(); + private readonly SemaphoreSlim _reading = new(1, 1); + private readonly CancellationTokenSource _lifetime = new(); + private byte[] _record = []; // non-seekable: the bytes recorded, from offset 0 + private int _length; // bytes in _record + private long _live; // non-seekable: bytes read from the stream so far + private bool _recording; + private bool _ended; // non-seekable: the stream has returned 0 + private ExceptionDispatchInfo? _fault; // the prefetch's failure, rethrown to whoever needs bytes it did not get + private byte[] _prefix = []; // seekable: the sniffed bytes + private Task? _prefetch; + private bool _disposed; + + /// The stream, positioned at the start of the image. + /// Keep open when the tap is disposed. + /// Never read synchronously. + public StreamTap(Stream stream, bool leaveOpen, bool asyncOnly) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead) + throw new ArgumentException("The stream cannot be read.", nameof(stream)); + _stream = stream; + _leaveOpen = leaveOpen; + AsyncOnly = asyncOnly; + CanSeek = stream.CanSeek; + _origin = CanSeek ? stream.Position : 0; + _recording = !CanSeek; + } + + /// True when the stream seeks: every offset can be read again, nothing is recorded. + public bool CanSeek { get; } + + /// True for a session from OpenAsync: the stream is only read asynchronously. + public bool AsyncOnly { get; } + + /// True while every byte from offset 0 can be read again (the stream seeks, or the tap still records). + public bool CanRevisit + { + get + { + lock (_gate) + return CanSeek || _recording; + } + } + + /// The token a synchronous call on an async-only tap waits with (the caller's, set around the call). + public CancellationToken SyncCancellation { get; set; } + + /// True when a background prefetch has been started. + public bool HasPrefetch => _prefetch is not null; + + /// The leading bytes read so far (at least after a sniff, unless the stream is shorter). + /// For a non-seekable stream, everything recorded. + public ReadOnlySpan Recorded + { + get + { + lock (_gate) + return CanSeek ? _prefix : _record.AsSpan(0, _length); + } + } + + /// Stops recording a non-seekable stream: what is recorded stays readable, later bytes are not kept. + public void StopRecording() + { + lock (_gate) + _recording = false; + } + + /// Reads the first bytes (fewer when the stream is shorter). + public void Sniff() + { + if (AsyncOnly) + { + Wait(SniffAsync(CancellationToken.None)); + return; + } + if (CanSeek) + { + _prefix = ReadPrefix(sync: true, CancellationToken.None).GetAwaiter().GetResult(); + return; + } + var chunk = new byte[SniffLength]; + while (RecordedLength < SniffLength && Read(LivePosition, chunk) > 0) + { + } + } + + /// , reading asynchronously. + public async ValueTask SniffAsync(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (CanSeek) + { + _prefix = await ReadPrefix(sync: false, cancellationToken).ConfigureAwait(false); + return; + } + var chunk = new byte[SniffLength]; + while (RecordedLength < SniffLength && await ReadAsync(LivePosition, chunk, cancellationToken).ConfigureAwait(false) > 0) + { + } + } + + /// + /// Reads up to destination.Length bytes at ; 0 at the end of the stream. + /// + /// The bytes at were read and not kept. + public int Read(long offset, Span destination) + { + if (destination.IsEmpty) + return 0; + if (AsyncOnly) + { + // Served by the asynchronous path, so the stream is never read synchronously: a request body that forbids it + // still works behind the synchronous API. + var rented = ArrayPool.Shared.Rent(destination.Length); + try + { + var n = Wait(ReadAsync(offset, rented.AsMemory(0, destination.Length), SyncCancellation)); + rented.AsSpan(0, n).CopyTo(destination); + return n; + } + finally + { + ArrayPool.Shared.Return(rented); + } + } + if (CanSeek) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _stream.Position = _origin + offset; + return _stream.Read(destination); + } + if (TryServe(offset, destination, out var served)) + return served; + // Synchronous sessions have no prefetch, so nothing else reads the stream. + var read = _stream.Read(destination); + Complete(destination[..read]); + return read; + } + + /// , reading the stream asynchronously. + public async ValueTask ReadAsync(long offset, Memory destination, CancellationToken cancellationToken) + { + if (destination.IsEmpty) + return 0; + if (CanSeek) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _stream.Position = _origin + offset; + return await _stream.ReadAsync(destination, cancellationToken).ConfigureAwait(false); + } + while (true) + { + if (TryServe(offset, destination.Span, out var served)) + return served; + await _reading.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // The prefetch may have read past the offset while this read waited. + if (TryServe(offset, destination.Span, out served)) + return served; + var read = await _stream.ReadAsync(destination, cancellationToken).ConfigureAwait(false); + Complete(destination.Span[..read]); + return read; + } + finally + { + _reading.Release(); + } + } + } + + /// + /// Starts reading the rest of a non-seekable stream into the record in the background. It stops at the end of the + /// stream, on a failure (rethrown to whoever later needs the bytes it did not get) or when the tap is disposed. + /// + public void StartPrefetch() + { + if (CanSeek || _prefetch is not null) + throw new InvalidOperationException("Only a non-seekable stream is prefetched, once."); + var token = _lifetime.Token; + _prefetch = Task.Run(() => PrefetchAsync(token), CancellationToken.None); + } + + /// The whole image, reading what is left of the stream (or waiting for the prefetch to have read it). + /// The tap has stopped recording a non-seekable stream. + /// The image is longer than an array can hold. + public ReadOnlyMemory ReadAll() + { + if (AsyncOnly) + return Wait(ReadAllAsync(SyncCancellation)); + if (CanSeek) + return ReadSeekable(sync: true, CancellationToken.None).GetAwaiter().GetResult(); + CheckRevisit(); + var chunk = new byte[ChunkLength]; + while (Read(LivePosition, chunk) > 0) + { + } + return RecordedMemory(); + } + + /// , reading asynchronously. + public async ValueTask> ReadAllAsync(CancellationToken cancellationToken) + { + if (CanSeek) + return await ReadSeekable(sync: false, cancellationToken).ConfigureAwait(false); + CheckRevisit(); + if (_prefetch is { } prefetch) + { + await prefetch.WaitAsync(cancellationToken).ConfigureAwait(false); + } + else + { + var chunk = new byte[ChunkLength]; + while (await ReadAsync(LivePosition, chunk, cancellationToken).ConfigureAwait(false) > 0) + { + } + } + return RecordedMemory(); + } + + /// Cancels the prefetch and, unless asked to leave it open, disposes the stream (otherwise waits for the cancelled prefetch to stop). + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + _record = []; + _length = 0; + } + _lifetime.Cancel(); + if (!_leaveOpen) + { + // Disposing the stream ends a read in flight; the prefetch then stops on its own. + _stream.Dispose(); + } + else if (_prefetch is { } prefetch) + { + // The caller keeps the stream: let the cancelled read finish before handing it back, so the prefetch never + // reads it concurrently with the caller. The prefetch catches everything, so this does not throw. + prefetch.GetAwaiter().GetResult(); + } + } + + private int RecordedLength + { + get + { + lock (_gate) + return _length; + } + } + + private long LivePosition + { + get + { + lock (_gate) + return _live; + } + } + + private void CheckRevisit() + { + if (!CanRevisit) + throw new InvalidOperationException(ImageDecoder.ForwardOnlyMessage); + } + + private ReadOnlyMemory RecordedMemory() + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _fault?.Throw(); + return _record.AsMemory(0, _length); + } + } + + // Serves a read from the record, or the end of the stream; false when the stream must be read at the live position. + private bool TryServe(long offset, Span destination, out int count) + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (offset < _length) + { + count = (int)Math.Min(destination.Length, _length - offset); + _record.AsSpan((int)offset, count).CopyTo(destination); + return true; + } + _fault?.Throw(); + if (offset != _live) + throw new InvalidOperationException(ImageDecoder.ForwardOnlyMessage); + count = 0; + return _ended; + } + } + + // Accounts for bytes just read from the stream (none: its end). + private void Complete(ReadOnlySpan read) + { + lock (_gate) + { + if (_disposed) + return; + if (read.IsEmpty) + { + _ended = true; + return; + } + if (_recording) + { + if (read.Length > Array.MaxLength - _length) + throw new InvalidDataException("The image is longer than an array can hold."); + if (_length + read.Length > _record.Length) + { + // Doubling, in new memory rather than a pool's: the record becomes the session's data, which its + // frame reader keeps, so it is never handed back for reuse. + var capacity = (int)Math.Min(Array.MaxLength, Math.Max((long)_length + read.Length, Math.Max(2L * _record.Length, SniffLength))); + var grown = GC.AllocateUninitializedArray(capacity); + _record.AsSpan(0, _length).CopyTo(grown); + _record = grown; + } + read.CopyTo(_record.AsSpan(_length)); + _length += read.Length; + } + _live += read.Length; + } + } + + private async Task PrefetchAsync(CancellationToken cancellationToken) + { + var chunk = new byte[ChunkLength]; + try + { + while (true) + { + await _reading.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + lock (_gate) + { + if (_ended || _disposed) + return; + } + var read = await _stream.ReadAsync(chunk, cancellationToken).ConfigureAwait(false); + Complete(chunk.AsSpan(0, read)); + if (read == 0) + return; + } + finally + { + _reading.Release(); + } + } + } + catch (Exception e) + { + // Kept for whoever needs the bytes; a prefetch stopped by Dispose is never asked. + lock (_gate) + _fault ??= ExceptionDispatchInfo.Capture(e); + } + } + + private async ValueTask ReadPrefix(bool sync, CancellationToken cancellationToken) + { + var prefix = new byte[(int)Math.Clamp(_stream.Length - _origin, 0, SniffLength)]; + var n = await FillSeekable(prefix, sync, cancellationToken).ConfigureAwait(false); + return n == prefix.Length ? prefix : prefix[..n]; + } + + private async ValueTask> ReadSeekable(bool sync, CancellationToken cancellationToken) + { + var length = _stream.Length - _origin; + if (length > Array.MaxLength) + throw new InvalidDataException($"The image is {length} bytes, more than an array can hold."); + var all = new byte[Math.Max(0, length)]; + if (await FillSeekable(all, sync, cancellationToken).ConfigureAwait(false) != all.Length) + throw new InvalidDataException("The stream ended before its declared length."); + return all; + } + + private async ValueTask FillSeekable(byte[] buffer, bool sync, CancellationToken cancellationToken) + { + var total = 0; + while (total < buffer.Length) + { + var n = sync + ? Read(total, buffer.AsSpan(total)) + : await ReadAsync(total, buffer.AsMemory(total), cancellationToken).ConfigureAwait(false); + if (n == 0) break; + total += n; + } + return total; + } + + // Blocks on an asynchronous read already in flight: how a synchronous call on an async-opened session waits without + // reading the stream synchronously. + private static T Wait(ValueTask task) => task.IsCompletedSuccessfully ? task.Result : task.AsTask().GetAwaiter().GetResult(); + + private static void Wait(ValueTask task) + { + if (!task.IsCompletedSuccessfully) + task.AsTask().GetAwaiter().GetResult(); + } +} diff --git a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs index f80139a..2467b6f 100644 --- a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs +++ b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs @@ -33,14 +33,14 @@ public static async Task RunAsync() } Check(!ImageCodecs.CanDecode("not an image"u8), "garbage", "CanDecode"); - return count + Heif() + V2(); + return count + Heif() + await V2Async(); } /// /// The 2.0 entry points, each through its registry delegate: options, metadata, thumbnail, closest size, the /// session API, 16-bit and premultiplied output, and every built-in encoder through the encoder registry. /// - private static int V2() + private static async Task V2Async() { const int w = 37, h = 23; var rgb = Program.Pattern(w, h); @@ -65,6 +65,17 @@ private static int V2() var crop = new byte[5 * 5 * 3]; session.GetFrame(0).CopyPixels(new PixelRect(1, 1, 5, 5), PixelFormat.Bgr24, crop, 0); + // A session over a non-seekable stream: opened asynchronously, decoded asynchronously; forward-only, copied. + using (var piped = await ImageDecoder.OpenAsync(new ForwardStream(png), leaveOpen: false, forwardOnly: false)) + using (var streamed = await piped.GetFrame(0).DecodeAsync()) + Check(streamed.Pixels.SequenceEqual(frame.Pixels), "v2", "ImageDecoder.OpenAsync + DecodeAsync"); + var copied = new byte[w * h * 4]; + var expectedCopy = new byte[w * h * 4]; + await session.GetFrame(0).CopyPixelsAsync(null, PixelFormat.Rgba32, expectedCopy, 0); + using (var forward = ImageDecoder.Open(new ForwardStream(png), leaveOpen: false, forwardOnly: true)) + forward.GetFrame(0).CopyPixels(null, PixelFormat.Rgba32, copied, 0); + Check(copied.AsSpan().SequenceEqual(expectedCopy), "v2", "ImageDecoder.Open forward-only + CopyPixels"); + var oriented = Oriented(rgb, w, h); var encoded = new List(); @@ -368,3 +379,20 @@ private static void Check([DoesNotReturnIf(false)] bool ok, string label, string throw new InvalidOperationException($"facade {label}: {call} failed"); } } + +/// A stream that cannot seek: an upload or a pipe. +internal sealed class ForwardStream(byte[] data) : Stream +{ + private readonly MemoryStream _inner = new(data); + + 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, Math.Min(count, 100)); + 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(); +} \ No newline at end of file diff --git a/tests/Sdcb.SimdCodecs.Tests/Streaming/ImageDecoderStreamingTests.cs b/tests/Sdcb.SimdCodecs.Tests/Streaming/ImageDecoderStreamingTests.cs new file mode 100644 index 0000000..02bc151 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/Streaming/ImageDecoderStreamingTests.cs @@ -0,0 +1,571 @@ +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Jpeg; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests.Streaming; + +/// +/// and +/// over every kind of stream: frame 0's first full-size decode streams through the codec's row reader (the fake +/// ; real codecs take the whole-file path until they have one), and every operation +/// sequence gives exactly what over the same bytes gives. +/// +[Collection(FacadeRegistryCollection.Name)] +public sealed class ImageDecoderStreamingTests : IDisposable +{ + private const int W = 37, H = 23; + + private readonly ImageDecoderRegistration[] _builtIn = ImageCodecs.RegistrySnapshot; + + public ImageDecoderStreamingTests() => ImageCodecs.ExchangeRegistry([RawStreamCodec.Registration, .. _builtIn]); + + public void Dispose() => ImageCodecs.ExchangeRegistry(_builtIn); + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + private static readonly byte[] Raw = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(W, H, 7), W, H); + private static readonly byte[] Big = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(256, 64, 11), 256, 64); + private static readonly byte[] RawFallback = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(W, H, 8), W, H, fallback: true); + + public enum Source { OneByte, Chunks, Seekable, File } + + private string? _file; + + private Stream Make(Source source, byte[] data, int seed = 1) => source switch + { + Source.OneByte => new ChunkedStream(data, maxChunk: 1, seed), + Source.Chunks => new ChunkedStream(data, maxChunk: 4096, seed), + Source.Seekable => new MemoryStream(data, writable: false), + _ => new FileStream(_file = WriteTemp(data), FileMode.Open, FileAccess.Read, FileShare.Read), + }; + + private static string WriteTemp(byte[] data) + { + var directory = Path.Combine(AppContext.BaseDirectory, "streaming-tmp"); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".bin"); + File.WriteAllBytes(path, data); + return path; + } + + // ---- what a session over memory gives ------------------------------------------------------------------------ + + private static void ShouldBeSame(IDecodedImage actual, IDecodedImage expected) + { + (actual.Width, actual.Height, actual.Channels, actual.SampleFormat, actual.BitDepth) + .ShouldBe((expected.Width, expected.Height, expected.Channels, expected.SampleFormat, expected.BitDepth)); + actual.ColorEncoding.ShouldBe(expected.ColorEncoding); + actual.Metadata.Exif.ToArray().ShouldBe(expected.Metadata.Exif.ToArray()); + actual.Metadata.Xmp.ToArray().ShouldBe(expected.Metadata.Xmp.ToArray()); + actual.Metadata.Icc.ToArray().ShouldBe(expected.Metadata.Icc.ToArray()); + actual.Pixels.SequenceEqual(expected.Pixels).ShouldBeTrue("pixels"); + } + + // Every operation a caller makes, in an order that has the first decode stream and the rest revisit. + private static List Sequence(ImageDecoder decoder, PixelFormat first) + { + var results = new List { decoder.Format, decoder.FrameCount }; + var frame = decoder.GetFrame(0); + results.Add(frame.Info); + var w = frame.Info.Width; + var h = frame.Info.Height; + var pixels = new byte[w * h * first.BytesPerPixel]; + frame.CopyPixels(null, first, pixels, 0, cancellationToken: Token); + results.Add(pixels); + using (var image = frame.Decode(cancellationToken: Token)) + results.Add(image.Pixels.ToArray()); + using (var image = frame.Decode(cancellationToken: Token)) + results.Add(image.Pixels.ToArray()); + // The fake codec decodes no regions: then the failure is what must match. + results.Add(Outcome(() => + { + var region = new byte[5 * 4 * 3]; + frame.CopyPixels(new PixelRect(3, 2, 5, 4), PixelFormat.Bgr24, region, 0, cancellationToken: Token); + return region; + })); + results.Add(decoder.Metadata.IsEmpty); + results.Add(decoder.LoopCount ?? -1); + results.Add(frame.TryGetThumbnail(out var thumbnail)); + thumbnail?.Dispose(); + results.Add(frame.TryGetClosestSize(w / 2, h / 2, out var cw, out var ch, out var scale)); + results.Add((cw, ch, scale)); + return results; + } + + private static object Outcome(Func step) + { + try + { + return step(); + } + catch (Exception e) + { + return $"{e.GetType().Name}: {e.Message}"; + } + } + + private static void ShouldMatchMemory(ImageDecoder decoder, byte[] data, PixelFormat first) + { + using var expected = ImageDecoder.Open(data.AsMemory()); + var actual = Sequence(decoder, first); + var wanted = Sequence(expected, first); + actual.Count.ShouldBe(wanted.Count); + for (var i = 0; i < actual.Count; i++) + { + if (wanted[i] is byte[] bytes) + ((byte[])actual[i]).ShouldBe(bytes, $"step {i}"); + else + actual[i].ShouldBe(wanted[i], $"step {i}"); + } + } + + public static TheoryData Sources() + { + var data = new TheoryData(); + foreach (var source in Enum.GetValues()) + { + data.Add(source, false); + data.Add(source, true); + } + return data; + } + + [Theory] + [MemberData(nameof(Sources))] + public void EveryOperationEqualsMemory_Streaming(Source source, bool fallbackVariant) + { + var data = fallbackVariant ? RawFallback : Raw; + foreach (var first in new[] { PixelFormat.Rgba32, PixelFormat.Gray8, PixelFormat.Bgra32Premultiplied, PixelFormat.Rgba64 }) + { + using var decoder = ImageDecoder.Open(Make(source, data)); + ShouldMatchMemory(decoder, data, first); + } + } + + [Theory] + [MemberData(nameof(Sources))] + public void DecodeFirstEqualsMemory(Source source, bool fallbackVariant) + { + var data = fallbackVariant ? RawFallback : Raw; + using var expected = ImageDecoder.Open(data.AsMemory()); + using var wanted = expected.GetFrame(0).Decode(cancellationToken: Token); + using var decoder = ImageDecoder.Open(Make(source, data)); + using (var image = decoder.GetFrame(0).Decode(cancellationToken: Token)) + ShouldBeSame(image, wanted); + using (var again = decoder.GetFrame(0).Decode(cancellationToken: Token)) + ShouldBeSame(again, wanted); + } + + [Fact] + public void APooledDecodeReturnsItsPixels() + { + var pool = new CountingPool(); + using var decoder = ImageDecoder.Open(new ChunkedStream(Raw, maxChunk: 300)); + var image = decoder.GetFrame(0).Decode(new DecodeOptions { Pool = pool }, Token); + using var expected = ImageDecoder.Open(Raw.AsMemory()); + using (var wanted = expected.GetFrame(0).Decode(cancellationToken: Token)) + ShouldBeSame(image, wanted); + pool.Rented.ShouldBe(1); + image.Dispose(); + pool.Returned.ShouldBe(1); + } + + private sealed class CountingPool : System.Buffers.ArrayPool + { + public int Rented, Returned; + public override byte[] Rent(int minimumLength) { Rented++; return new byte[minimumLength]; } + public override void Return(byte[] array, bool clearArray = false) => Returned++; + } + + [Fact] + public void ANonStreamingCodecIsReadWholeAtOpen() + { + ImageCodecs.ExchangeRegistry([RawStreamCodec.NonStreamingRegistration, .. _builtIn]); + var stream = new ChunkedStream(Raw, maxChunk: 64); + using var decoder = ImageDecoder.Open(stream, leaveOpen: true, forwardOnly: true); + stream.BytesRead.ShouldBe(Raw.Length); + ShouldMatchMemory(decoder, Raw, PixelFormat.Rgba32); + } + + [Fact] + public void OpenReadsOnlyTheHeader() + { + var large = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(512, 512, 3), 512, 512); + var stream = new ChunkedStream(large, maxChunk: 1000); + using var decoder = ImageDecoder.Open(stream, leaveOpen: true); + stream.BytesRead.ShouldBeLessThan(64 * 1024); + decoder.GetFrame(0).Info.Width.ShouldBe(512); + stream.BytesRead.ShouldBeLessThan(64 * 1024); + } + + // ---- real codecs: the whole-file path behind the same API --------------------------------------------------- + + private static byte[] Rgb(int seed) + { + var pixels = new byte[W * H * 3]; + new Random(seed).NextBytes(pixels); + return pixels; + } + + public static TheoryData RealFiles() => ["png", "jpeg", "jpeg-gray"]; + + private static byte[] Real(string name) => name switch + { + "png" => Sdcb.SimdCodecs.Png.PngWriter.Encode(RawStreamCodec.RandomRgba(W, H, 4), W, H), + "jpeg" => JpegEncoder.Encode(Rgb(5), W, H, 3, new JpegEncodeOptions { Quality = 90 }), + _ => JpegEncoder.Encode(Rgb(6)[..(W * H)], W, H, 1, new JpegEncodeOptions { Quality = 90 }), + }; + + [Theory] + [MemberData(nameof(RealFiles))] + public void RealCodecsEqualMemory(string name) + { + var data = Real(name); + foreach (var source in Enum.GetValues()) + { + foreach (var forwardOnly in new[] { false, true }) + { + using var decoder = ImageDecoder.Open(Make(source, data), leaveOpen: false, forwardOnly); + ShouldMatchMemory(decoder, data, PixelFormat.Rgba32); + } + } + } + + /// + /// The layout a streamed Decode asks the row reader for, of the header's + /// channels and sample format, is the one returns, and TryDecodeInto in it + /// writes TryDecode's pixels; the header's bit depth and colour encoding are the image's. + /// + [Theory] + [MemberData(nameof(RealFiles))] + public void TheNativeLayoutIsTryDecodes(string name) + { + var data = Real(name); + var codec = ImageCodecs.Find(data)!; + codec.TryReadInfo(data, out var info).ShouldBeTrue(); + codec.TryDecode(data, out var image, null, Token).ShouldBeTrue(); + using (image) + { + var format = PixelFormat.ForChannels(info.Channels, info.SampleFormat); + (image!.Channels, image.SampleFormat, image.BitDepth).ShouldBe((info.Channels, info.SampleFormat, info.BitDepth)); + image.ColorEncoding.ShouldBe(info.ColorEncoding); + var pixels = new byte[info.Width * info.Height * format.BytesPerPixel]; + codec.TryDecodeInto(data, pixels, 0, format, null, Token).ShouldBeTrue(); + pixels.ShouldBe(image.Pixels.ToArray()); + if (!codec.TryReadMetadata(data, out var metadata)) metadata = ImageMetadata.Empty; + image.Metadata.Exif.ToArray().ShouldBe(metadata!.Exif.ToArray()); + image.Metadata.Icc.ToArray().ShouldBe(metadata.Icc.ToArray()); + image.Metadata.Xmp.ToArray().ShouldBe(metadata.Xmp.ToArray()); + } + } + + // ---- forward-only -------------------------------------------------------------------------------------------- + + [Fact] + public void ForwardOnlyRefusesToRevisitAfterItsStreamedDecode() + { + using var expected = ImageDecoder.Open(Raw.AsMemory()); + using var wanted = expected.GetFrame(0).Decode(cancellationToken: Token); + using var decoder = ImageDecoder.Open(new ChunkedStream(Raw, maxChunk: 100), leaveOpen: false, forwardOnly: true); + var frame = decoder.GetFrame(0); + using (var image = frame.Decode(cancellationToken: Token)) + ShouldBeSame(image, wanted); + Should.Throw(() => frame.Decode(cancellationToken: Token)); + Should.Throw(() => _ = decoder.Metadata); + Should.Throw(() => frame.CopyPixels(null, PixelFormat.Rgba32, new byte[W * H * 4], 0, cancellationToken: Token)); + decoder.GetFrame(0).Info.ShouldBe(frame.Info); // the header is still known + } + + [Fact] + public void ForwardOnlyReadsTheWholeFileForAnOperationBeforeItsDecode() + { + using var decoder = ImageDecoder.Open(new ChunkedStream(Raw, maxChunk: 100), leaveOpen: false, forwardOnly: true); + decoder.Metadata.IsEmpty.ShouldBeTrue(); + ShouldMatchMemory(decoder, Raw, PixelFormat.Bgr24); + } + + [Fact] + public void ForwardOnlyOverASeekableStreamStillRevisits() + { + using var decoder = ImageDecoder.Open(new MemoryStream(Raw), leaveOpen: false, forwardOnly: true); + ShouldMatchMemory(decoder, Raw, PixelFormat.Rgba32); + } + + [Fact] + public async Task ForwardOnlyAsyncStreamsWithoutASyncRead() + { + using var expected = ImageDecoder.Open(Raw.AsMemory()); + using var wanted = expected.GetFrame(0).Decode(cancellationToken: Token); + using (var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(Raw, 97, asyncOnly: true), false, true, Token)) + { + using var image = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token); + ShouldBeSame(image, wanted); + await Should.ThrowAsync(async () => await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token)); + } + // The synchronous call blocks on asynchronous reads. + using (var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(Raw, 97, asyncOnly: true), false, true, Token)) + using (var image = decoder.GetFrame(0).Decode(cancellationToken: Token)) + ShouldBeSame(image, wanted); + } + + // ---- memory ---------------------------------------------------------------------------------------------------- + + [Fact] + public void AStreamedCopyDoesNotHoldTheFile() + { + const int size = 1024; + var large = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(size, size, 9), size, size); + var destination = new byte[size * size * 4]; + var expected = new byte[destination.Length]; + using (var memory = ImageDecoder.Open(large.AsMemory())) + memory.GetFrame(0).CopyPixels(null, PixelFormat.Bgra32, expected, 0, cancellationToken: Token); + + var seekable = new MemoryStream(large, writable: false); + StreamingAssert.AllocatesLessThan(large.Length / 8, () => + { + seekable.Position = 0; + using var decoder = ImageDecoder.Open(seekable, leaveOpen: true); + decoder.GetFrame(0).CopyPixels(null, PixelFormat.Bgra32, destination, 0, cancellationToken: Token); + }, "seekable"); + destination.ShouldBe(expected); + + Array.Clear(destination); + StreamingAssert.AllocatesLessThan(large.Length / 8, () => + { + using var decoder = ImageDecoder.Open(new ChunkedStream(large, maxChunk: 65536), leaveOpen: false, forwardOnly: true); + decoder.GetFrame(0).CopyPixels(null, PixelFormat.Bgra32, destination, 0, cancellationToken: Token); + }, "forward-only"); + destination.ShouldBe(expected); + } + + // ---- OpenAsync ------------------------------------------------------------------------------------------------- + + /// An ASP.NET request body: async reads only. Both the new async decode and the legacy one give the + /// memory session's image, and neither reads the stream synchronously (it would throw). + [Fact] + public async Task ARequestBodyDecodesAsyncAndLegacy() + { + using var expected = ImageDecoder.Open(Raw.AsMemory()); + using var wanted = expected.GetFrame(0).Decode(cancellationToken: Token); + + using (var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(Raw, 997, asyncOnly: true), cancellationToken: Token)) + using (var image = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token)) + ShouldBeSame(image, wanted); + + using (var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(Raw, 997, asyncOnly: true), cancellationToken: Token)) + using (var image = decoder.GetFrame(0).Decode(cancellationToken: Token)) + ShouldBeSame(image, wanted); + + using (var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(Raw, 997, asyncOnly: true), cancellationToken: Token)) + ShouldMatchMemory(decoder, Raw, PixelFormat.Rgb24); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AsyncSequencesEqualMemory(bool fallbackVariant) + { + var data = fallbackVariant ? RawFallback : Raw; + using var expected = ImageDecoder.Open(data.AsMemory()); + var wanted = new byte[W * H * 2]; + expected.GetFrame(0).CopyPixels(null, PixelFormat.GrayAlpha16, wanted, 0, cancellationToken: Token); + using var wantedImage = expected.GetFrame(0).Decode(cancellationToken: Token); + foreach (var source in Enum.GetValues()) + { + var stream = source is Source.OneByte or Source.Chunks + ? new ChunkedStream(data, source == Source.OneByte ? 1 : 4096, asyncOnly: true) + : Make(source, data); + using var decoder = await ImageDecoder.OpenAsync(stream, cancellationToken: Token); + var frame = decoder.GetFrame(0); + var pixels = new byte[wanted.Length]; + await frame.CopyPixelsAsync(null, PixelFormat.GrayAlpha16, pixels, 0, cancellationToken: Token); + pixels.ShouldBe(wanted, source.ToString()); + using (var image = await frame.DecodeAsync(cancellationToken: Token)) + ShouldBeSame(image, wantedImage); + var region = new byte[4 * 4 * 4]; + var message = (await Should.ThrowAsync(async () => + await frame.CopyPixelsAsync(new PixelRect(1, 1, 4, 4), PixelFormat.Rgba32, region, 0, cancellationToken: Token))).Message; + message.ShouldBe(Should.Throw(() => + expected.GetFrame(0).CopyPixels(new PixelRect(1, 1, 4, 4), PixelFormat.Rgba32, region, 0, cancellationToken: Token)).Message); + using (var again = await frame.DecodeAsync(cancellationToken: Token)) + ShouldBeSame(again, wantedImage); + } + } + + [Fact] + public async Task ThePrefetchRacesAStreamedDecode() + { + for (var seed = 1; seed <= 20; seed++) + { + var data = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(W, H, seed), W, H); + using var expected = ImageDecoder.Open(data.AsMemory()); + using var wanted = expected.GetFrame(0).Decode(cancellationToken: Token); + using var decoder = await ImageDecoder.OpenAsync(new ChunkedStream(data, 1 + seed * 13, seed, asyncOnly: true), cancellationToken: Token); + if (seed % 2 == 0) + await Task.Delay(seed % 4, Token); + using (var image = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token)) + ShouldBeSame(image, wanted); + using (var again = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token)) + ShouldBeSame(again, wanted); + decoder.Metadata.IsEmpty.ShouldBeTrue(); + } + } + + /// Serves the header, then blocks every read until it is cancelled or the stream is disposed. + private sealed class StallingStream(byte[] data, int serve) : Stream + { + private int _position; + private readonly TaskCompletionSource _disposed = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool WasDisposed => _disposed.Task.IsCompleted; + private int _stalled; + public int Stalled => Volatile.Read(ref _stalled); + + 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) => throw new InvalidOperationException("Synchronous operations are disallowed."); + 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(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_position < serve) + { + var n = Math.Min(buffer.Length, serve - _position); + data.AsMemory(_position, n).CopyTo(buffer); + _position += n; + return n; + } + Interlocked.Increment(ref _stalled); + await _disposed.Task.WaitAsync(cancellationToken); + throw new ObjectDisposedException(nameof(StallingStream)); + } + + protected override void Dispose(bool disposing) + { + _disposed.TrySetResult(); + base.Dispose(disposing); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DisposingDuringThePrefetchStopsIt(bool leaveOpen) + { + var stream = new StallingStream(Big, 8192); + var decoder = await ImageDecoder.OpenAsync(stream, leaveOpen, Token); + decoder.GetFrame(0).Info.Width.ShouldBe(256); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (stream.Stalled == 0 && DateTime.UtcNow < deadline) + await Task.Delay(1, Token); + stream.Stalled.ShouldBeGreaterThan(0, "the prefetch reads on in the background"); + decoder.Dispose(); + stream.WasDisposed.ShouldBe(!leaveOpen); + Should.Throw(() => decoder.GetFrame(0)); + } + + [Fact] + public async Task ADecodeWaitingOnAStalledStreamIsCancelled() + { + var stream = new StallingStream(Big, 8192); + using var decoder = await ImageDecoder.OpenAsync(stream, leaveOpen: false, forwardOnly: true, Token); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + await Should.ThrowAsync(async () => await decoder.GetFrame(0).DecodeAsync(cancellationToken: cancel.Token)); + + using var retained = await ImageDecoder.OpenAsync(new StallingStream(Big, 8192), cancellationToken: Token); + using var cancel2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + await Should.ThrowAsync(async () => + await retained.GetFrame(0).CopyPixelsAsync(null, PixelFormat.Rgba32, new byte[256 * 64 * 4], 0, cancellationToken: cancel2.Token)); + await Should.ThrowAsync(async () => + await ImageDecoder.OpenAsync(new ChunkedStream(Raw, asyncOnly: true), false, false, new CancellationToken(canceled: true))); + + // A synchronous call on an async-opened session blocks on asynchronous reads, and its token still cancels them. + foreach (var forwardOnly in new[] { false, true }) + { + using var session = await ImageDecoder.OpenAsync(new StallingStream(Big, 8192), false, forwardOnly, Token); + using var cancel3 = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + Should.Throw(() => session.GetFrame(0).Decode(cancellationToken: cancel3.Token)); + } + } + + // ---- bad data and ownership ------------------------------------------------------------------------------------ + + [Theory] + [MemberData(nameof(Sources))] + public async Task ATruncatedStreamThrowsInvalidDataException(Source source, bool forwardOnly) + { + foreach (var cut in new[] { 3, RawStreamCodec.HeaderLength - 1, RawStreamCodec.HeaderLength + W * 4 * 5 + 3, Raw.Length - 2 }) + { + var data = Raw[..cut]; + Should.Throw(() => + { + using var decoder = ImageDecoder.Open(Make(source, data), leaveOpen: false, forwardOnly); + decoder.GetFrame(0).CopyPixels(null, PixelFormat.Rgba32, new byte[W * H * 4], 0, cancellationToken: Token); + }, $"{cut}"); + Should.Throw(() => + { + using var decoder = ImageDecoder.Open(Make(source, data), leaveOpen: false, forwardOnly); + using var image = decoder.GetFrame(0).Decode(cancellationToken: Token); + }, $"{cut}"); + await Should.ThrowAsync(async () => + { + var stream = source is Source.OneByte or Source.Chunks ? new ChunkedStream(data, 50, asyncOnly: true) : Make(source, data); + using var decoder = await ImageDecoder.OpenAsync(stream, false, forwardOnly, Token); + using var image = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token); + }, $"{cut}"); + } + } + + [Fact] + public void ACorruptStreamFailsAsFromMemory() + { + var corrupt = (byte[])Raw.Clone(); + corrupt[^1] ^= 0xFF; // the trailer + var fromMemory = Should.Throw(() => + { + using var decoder = ImageDecoder.Open(corrupt.AsMemory()); + using var image = decoder.GetFrame(0).Decode(cancellationToken: Token); + }); + var fromStream = Should.Throw(() => + { + using var decoder = ImageDecoder.Open(new ChunkedStream(corrupt, 40)); + using var image = decoder.GetFrame(0).Decode(cancellationToken: Token); + }); + fromStream.Message.ShouldBe(fromMemory.Message); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public async Task LeaveOpenDecidesWhoClosesTheStream(bool leaveOpen, bool streaming) + { + if (!streaming) + ImageCodecs.ExchangeRegistry([RawStreamCodec.NonStreamingRegistration, .. _builtIn]); + var stream = new ChunkedStream(Raw, 500); + using (var decoder = ImageDecoder.Open(stream, leaveOpen)) + { + using var image = decoder.GetFrame(0).Decode(cancellationToken: Token); + stream.WasDisposed.ShouldBeFalse(); + } + stream.WasDisposed.ShouldBe(!leaveOpen); + + var asyncStream = new ChunkedStream(Raw, 500, asyncOnly: true); + using (var decoder = await ImageDecoder.OpenAsync(asyncStream, leaveOpen, Token)) + { + using var image = await decoder.GetFrame(0).DecodeAsync(cancellationToken: Token); + } + asyncStream.WasDisposed.ShouldBe(!leaveOpen); + + var failed = new ChunkedStream("SRAW"u8.ToArray(), 2); + Should.Throw(() => ImageDecoder.Open(failed, leaveOpen)); + failed.WasDisposed.ShouldBe(!leaveOpen); + } +}