diff --git a/README.md b/README.md index ae4e09e..da79603 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,20 @@ The facade covers what every format has in common. Each format package has a ric +### Streaming + +`ImageCodecs.OpenRowReader(stream, format, options)` / `OpenRowReaderAsync(…)` decode a stream that need not seek (a request body, a pipe) a band of rows at a time, top to bottom; the rows are exactly `TryDecodeInto`'s. `ImageCodecs.CreateEncoder(format, stream)` writes a file to a stream about every 64 KiB as the encoder produces it; its frames take `WriteRowsAsync` and the session `CommitAsync`, which never write synchronously. `IsStreaming` says whether the codec really works as the data flows: when it is false (a format, variant or option that needs the whole image, such as an interlaced PNG, a progressive JPEG, a scaled decode or palette quantisation) the reader reads the stream whole and decodes it first, and the encoder writes the file at `Commit`, behind the same API. + +```csharp +// An upload re-encoded as PNG, stream to stream: rows in, bytes out, no synchronous I/O. +await using IImageRowReader reader = await ImageCodecs.OpenRowReaderAsync(request.Body, PixelFormat.Rgba32); +await using StreamEncoderSession png = ImageCodecs.CreateEncoder(ImageFormat.Png, response.Body); +StreamFrameEncoder frame = png.AddFrame(reader.Width, reader.Height, PixelFormat.Rgba32); +byte[] band = new byte[reader.Width * 4 * 16]; +for (int n; (n = await reader.ReadRowsAsync(band, 16)) > 0;) + await frame.WriteRowsAsync(band.AsMemory(0, n * reader.Width * 4), n); +await png.CommitAsync(); +``` Upgrading from 1.x: [docs/migrating-to-2.0.md](docs/migrating-to-2.0.md). ## Formats diff --git a/README.zh-CN.md b/README.zh-CN.md index f2a1bd7..e3b3bb7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -75,6 +75,20 @@ ImageCodecs.Register(HeifImageDecoder.Registration); +### 流式读写 + +`ImageCodecs.OpenRowReader(stream, format, options)` / `OpenRowReaderAsync(…)` 从不必可寻址的流(请求体、管道)自上而下逐个行带解码,行数据与 `TryDecodeInto` 完全一致。`ImageCodecs.CreateEncoder(format, stream)` 在编码器产出字节时大约每 64 KiB 写一次流;它的帧有 `WriteRowsAsync`,会话有 `CommitAsync`,二者都不做同步写入。`IsStreaming` 表示 codec 是否真的边读边解、边编边写:为 false 时(需要整幅图像的格式、变体或选项,比如隔行 PNG、渐进式 JPEG、缩放解码、调色板量化),读取器先读完整个流再解码,编码器在 `Commit` 时写出文件,API 不变。 + +```csharp +// 把上传的图片转成 PNG,流到流:行进,字节出,没有同步 I/O。 +await using IImageRowReader reader = await ImageCodecs.OpenRowReaderAsync(request.Body, PixelFormat.Rgba32); +await using StreamEncoderSession png = ImageCodecs.CreateEncoder(ImageFormat.Png, response.Body); +StreamFrameEncoder frame = png.AddFrame(reader.Width, reader.Height, PixelFormat.Rgba32); +byte[] band = new byte[reader.Width * 4 * 16]; +for (int n; (n = await reader.ReadRowsAsync(band, 16)) > 0;) + await frame.WriteRowsAsync(band.AsMemory(0, n * reader.Width * 4), n); +await png.CommitAsync(); +``` 从 1.x 升级:见 [docs/migrating-to-2.0.md](docs/migrating-to-2.0.md)。 ## 支持的格式 diff --git a/src/Sdcb.SimdCodecs/ImageCodecs.Encode.cs b/src/Sdcb.SimdCodecs/ImageCodecs.Encode.cs index 559c871..04e77fc 100644 --- a/src/Sdcb.SimdCodecs/ImageCodecs.Encode.cs +++ b/src/Sdcb.SimdCodecs/ImageCodecs.Encode.cs @@ -33,6 +33,20 @@ public static partial class ImageCodecs ]; private static readonly Lock s_encoderLock = new(); + /// The encoder registry as it stands (for tests, to put it back with ). + internal static ImageEncoderRegistration[] EncoderSnapshot => Volatile.Read(ref s_encoders); + + /// Replaces the encoder registry and returns the one it replaced (for tests, as ). + internal static ImageEncoderRegistration[] ExchangeEncoders(ImageEncoderRegistration[] encoders) + { + lock (s_encoderLock) + { + var previous = s_encoders; + Volatile.Write(ref s_encoders, encoders); + return previous; + } + } + /// /// Enables encoding to a format the facade does not encode out of the box, or replaces the encoder for one /// (ImageCodecs.RegisterEncoder(MyEncoder.Registration)). PNG, JPEG, TIFF, WebP, GIF, BMP, ICO, QOI and Netpbm @@ -83,6 +97,12 @@ public static IImageEncoderSession CreateEncoder(ImageFormat format, IBufferWrit /// 8-bit-only format receives them narrowed, v >> 8), its and /// its (Exif, XMP, ICC), so a transcode keeps the capture time, GPS position and /// colour profile. Float images cannot be encoded this way (no integer projection). + /// + /// The file is written to the stream about every 64 KiB as the encoder produces it, synchronously; the stream is not + /// flushed. An encode that fails or is cancelled may leave the first part of the file in the stream. To write it + /// asynchronously, or row band by row band, use + /// . + /// /// /// No registered encoder writes , or the image has /// float samples. @@ -92,13 +112,13 @@ public static void Encode(IDecodedImage image, ImageFormat format, Stream destin CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(destination); - var buffer = new ArrayBufferWriter(); - Encode(image, format, buffer, options, cancellationToken); - destination.Write(buffer.WrittenSpan); + using var writer = new StreamBufferWriter(destination); + Encode(image, format, writer, options, cancellationToken); + writer.Flush(); } /// into a buffer - /// writer (for a Stream with no copy: PipeWriter.Create(stream)). + /// writer (a PipeWriter, an ArrayBufferWriter). public static void Encode(IDecodedImage image, ImageFormat format, IBufferWriter destination, EncodeOptions? options = null, CancellationToken cancellationToken = default) { @@ -130,7 +150,7 @@ public static byte[] Encode(ReadOnlySpan pixels, int width, int height, Pi /// /// - /// writing the file into (for a Stream with no copy: PipeWriter.Create(stream)). + /// writing the file into (a PipeWriter, an ArrayBufferWriter). /// /// No registered encoder writes . /// is of a type 's encoder does not take. @@ -146,7 +166,10 @@ public static void Encode(ReadOnlySpan pixels, int width, int height, Pixe /// /// - /// writing the file to (buffered, then written in one call). + /// writing the file to , about every 64 KiB as the encoder produces it, synchronously; + /// the stream is not flushed. An encode that fails or is cancelled may leave the first part of the file in the stream. + /// To write it asynchronously, or row band by row band, use + /// . /// /// No registered encoder writes . /// is of a type 's encoder does not take. @@ -155,9 +178,9 @@ public static void Encode(ReadOnlySpan pixels, int width, int height, Pixe CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(destination); - var buffer = new ArrayBufferWriter(); - Encode(pixels, width, height, pixelFormat, format, buffer, stride, options, metadata, cancellationToken); - destination.Write(buffer.WrittenSpan); + using var writer = new StreamBufferWriter(destination); + Encode(pixels, width, height, pixelFormat, format, writer, stride, options, metadata, cancellationToken); + writer.Flush(); } private static ImageEncoderRegistration? FindEncoder(ImageFormat format) diff --git a/src/Sdcb.SimdCodecs/ImageCodecs.Streaming.cs b/src/Sdcb.SimdCodecs/ImageCodecs.Streaming.cs new file mode 100644 index 0000000..4ef539e --- /dev/null +++ b/src/Sdcb.SimdCodecs/ImageCodecs.Streaming.cs @@ -0,0 +1,190 @@ +using System.IO; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs; + +public static partial class ImageCodecs +{ + /// + /// The leading bytes sniffs: the longest fixed signature a codec reads. An ISO-BMFF + /// ftyp box (HEIF, AVIF) lists brands to its end, so for one the sniff takes the whole box, up to + /// . The sniff always sees exactly that many bytes (fewer only for a shorter stream), + /// whatever the stream's reads return, so the codec chosen never depends on how the bytes arrive. + /// + internal const int SniffLength = 64; + + /// The most bytes the sniff reads for an ftyp box (a thousand brands). + internal const int MaxSniffLength = 4096; + + /// + /// Opens a reader that decodes a band of rows at a time, top to bottom, as the stream + /// arrives: a request body, a network or pipe stream, a file too large to read whole. The stream need not seek. The + /// codec is chosen as chooses it, from the first 64 bytes (a leading ISO-BMFF ftyp box whole, up to 4 KiB). A codec that decodes as its input + /// arrives ( true) holds a few rows and a small input buffer, and reads the + /// stream no further than the rows asked for need; any other codec, variant or option (an interlaced PNG, a + /// progressive JPEG, a scaled decode) reads the stream to its end and decodes it first, behind the same API + /// ( false). + /// + /// The rows are exactly those writes for the same bytes, and + /// . The header is read before this returns, so and + /// size the destination. A gain-map JPEG reads as the plain JPEG it carries (its SDR + /// base, which is 's output for it too): the gain map lies past the sniffed bytes. Reads + /// the stream synchronously; never does. Dispose the reader when done. + /// + /// + /// The image, from its current position; it need not seek. + /// The layout of the rows. + /// Scale, region and orientation; null for the whole image at full size, as stored. The pool is ignored. + /// Keep open when the reader is disposed (or when this throws). + /// Checked while the header (or, for a buffered decode, the whole stream) is read. + /// No registered codec decodes the stream (the message names + /// 's answer), or its header is malformed or truncated. + /// The image has no projection to (float samples, an + /// HDR transfer; see ). + /// cannot be read, or + /// does not lie inside the image. + /// was cancelled. + public static IImageRowReader OpenRowReader(Stream stream, PixelFormat format, DecodeOptions? options = null, + bool leaveOpen = false, CancellationToken cancellationToken = default) + { + var input = OpenInput(stream, leaveOpen); + StreamingRowReader? reader = null; + try + { + input.Fill(SniffLength); + if (FtypLength(input.Buffered) is var ftyp and > SniffLength) + input.Fill(ftyp); + reader = CreateRowReader(input, format, options); + reader.Initialize(cancellationToken); + return reader; + } + catch + { + if (reader is not null) reader.Dispose(); + else input.Dispose(); + throw; + } + } + + /// + /// , reading the stream asynchronously only: for a stream that forbids synchronous reads (an + /// ASP.NET Core request body). Read the rows with . + /// + /// + /// + public static async ValueTask OpenRowReaderAsync(Stream stream, PixelFormat format, + DecodeOptions? options = null, bool leaveOpen = false, CancellationToken cancellationToken = default) + { + var input = OpenInput(stream, leaveOpen); + StreamingRowReader? reader = null; + try + { + await input.FillAsync(SniffLength, cancellationToken).ConfigureAwait(false); + if (FtypLength(input.Buffered) is var ftyp and > SniffLength) + await input.FillAsync(ftyp, cancellationToken).ConfigureAwait(false); + reader = CreateRowReader(input, format, options); + await reader.InitializeAsync(cancellationToken).ConfigureAwait(false); + return reader; + } + catch + { + if (reader is not null) await reader.DisposeAsync().ConfigureAwait(false); + else input.Dispose(); + throw; + } + } + + private static StreamInput OpenInput(Stream stream, bool leaveOpen) + { + ArgumentNullException.ThrowIfNull(stream); + return new StreamInput(stream, leaveOpen); + } + + // The bytes to sniff: SniffLength, or a leading ftyp box whole (capped at MaxSniffLength). + private static int FtypLength(ReadOnlySpan header) => + header.Length >= 8 && header[4..8].SequenceEqual("ftyp"u8) + ? (int)Math.Clamp(System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(header), SniffLength, MaxSniffLength) + : SniffLength; + + // The reader for the codec that claims the sniffed bytes: its streaming decoder, or the whole-input fallback. + private static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) + { + var buffered = input.Buffered; + var header = buffered[..Math.Min(buffered.Length, FtypLength(buffered))]; + var entry = Find(header) ?? throw new InvalidDataException(NoCodecMessage(header)); + if (entry.CreateRowReader is { } create) + return create(input, format, options); + return new BufferedRowReader(input, format, options, + (ReadOnlySpan data, out ImageInfo info) => ReadInfoOrThrow(entry, data, out info), + (data, destination, stride, pixelFormat, decodeOptions, cancellationToken) => + DecodeIntoOrThrow(entry, data, destination, stride, pixelFormat, decodeOptions, cancellationToken)); + } + + // The buffered reader's header read, failing as Decode does: with the codec's reason when it has one. + private static bool ReadInfoOrThrow(ImageDecoderRegistration entry, ReadOnlySpan data, out ImageInfo info) + { + if (entry.TryReadInfo(data, out info)) + return true; + throw DecodeFailure(entry, data, null, CancellationToken.None, $"The {FormatName(entry.Format)} header cannot be read.")!; + } + + // The buffered reader's decode, failing as Decode(data, format) does: a corrupt file with the codec's reason, an image + // without an integer projection with NotSupportedException. + private static bool DecodeIntoOrThrow(ImageDecoderRegistration entry, ReadOnlySpan data, Span destination, + int stride, PixelFormat format, DecodeOptions? options, CancellationToken cancellationToken) + { + if (entry.TryDecodeInto(data, destination, stride, format, options, cancellationToken)) + return true; + if (DecodeFailure(entry, data, options, cancellationToken, null) is { } failure) + throw failure; + throw entry.TryReadInfo(data, out var info) + ? NoProjection(entry.Format, info, format) + : new InvalidDataException($"The {FormatName(entry.Format)} file cannot be decoded."); + } + + /// + /// Opens an encoding session for writing to : the session of + /// , its bytes written to + /// the stream about every 64 KiB as the encoder produces them. An encoder that encodes rows as they come + /// ( true) so writes the file while its rows are still arriving, holding + /// a band of rows and about a chunk of output; one that needs the whole image (palette quantisation, WebP lossless) + /// writes it at . The bytes are those the buffer-writer session writes. The + /// synchronous members write a chunk as soon as it fills; the asynchronous ones hold what one call produces (the whole + /// file, for an encoder that is not streaming) until the call ends, then write it. + /// + /// and write the stream + /// synchronously; and + /// only asynchronously (an ASP.NET Core response body). Commit flushes the stream. Disposing a session that was not + /// committed leaves the bytes already written in the stream: an incomplete file. + /// + /// + /// The format to write. + /// Where the file is written, from its current position. + /// The format's options; null for its defaults. + /// Keep open when the session is disposed (or when this throws for + /// the options). + /// No registered encoder writes . + /// cannot be written, or is + /// not null and not an options type 's encoder takes. + public static StreamEncoderSession CreateEncoder(ImageFormat format, Stream output, EncodeOptions? options = null, + bool leaveOpen = false) + { + ArgumentNullException.ThrowIfNull(output); + if (!output.CanWrite) + throw new ArgumentException("The stream cannot be written.", nameof(output)); + var encoder = RequireEncoder(format); + var writer = new StreamBufferWriter(output); + try + { + return new StreamEncoderSession(encoder.Create(writer, options), writer, output, leaveOpen); + } + catch + { + writer.Dispose(); + if (!leaveOpen) + output.Dispose(); + throw; + } + } +} diff --git a/src/Sdcb.SimdCodecs/ImageCodecs.cs b/src/Sdcb.SimdCodecs/ImageCodecs.cs index 72ed15c..a4bd971 100644 --- a/src/Sdcb.SimdCodecs/ImageCodecs.cs +++ b/src/Sdcb.SimdCodecs/ImageCodecs.cs @@ -382,14 +382,20 @@ public static PixelBuffer Decode(ReadOnlySpan data, PixelFormat format, De // reported as one whatever it holds) or has no projection of it to the format. if (DecodeFailure(entry, data, options, cancellationToken, null) is { } failure) throw failure; - var name = FormatName(entry.Format); + throw NoProjection(entry.Format, info, format); + } + + // Why a codec that decodes an image wrote no pixels of it in a format: float samples, or an HDR transfer. + private static NotSupportedException NoProjection(ImageFormat imageFormat, in ImageInfo info, PixelFormat format) + { + var name = FormatName(imageFormat); if (info.SampleFormat == SampleFormat.Float32) { - throw new NotSupportedException( + return new NotSupportedException( $"The {name} image has float samples, which have no {format} form without a tone policy: decode it with " + "ImageCodecs.Decode(data) and use IDecodedImage.ToFloats or PixelConverter.StretchToRgba8."); } - throw new NotSupportedException( + return new NotSupportedException( $"The {name} image decodes, but its codec has no {format} projection of it (an HDR transfer such as PQ " + "or HLG has no display pixels without tone mapping): decode it with ImageCodecs.Decode(data) instead."); } diff --git a/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt index 7dc5c58..3b7c3b6 100644 --- a/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs/PublicAPI.Unshipped.txt @@ -1 +1,16 @@ #nullable enable +Sdcb.SimdCodecs.StreamEncoderSession +Sdcb.SimdCodecs.StreamEncoderSession.AddFrame(int width, int height, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.ColorEncoding? color = null, Sdcb.SimdCodecs.Abstractions.ImageMetadata? metadata = null, System.TimeSpan? duration = null) -> Sdcb.SimdCodecs.StreamFrameEncoder! +Sdcb.SimdCodecs.StreamEncoderSession.Commit(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void +Sdcb.SimdCodecs.StreamEncoderSession.CommitAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +Sdcb.SimdCodecs.StreamEncoderSession.Dispose() -> void +Sdcb.SimdCodecs.StreamEncoderSession.DisposeAsync() -> System.Threading.Tasks.ValueTask +Sdcb.SimdCodecs.StreamEncoderSession.IsStreaming.get -> bool +Sdcb.SimdCodecs.StreamEncoderSession.MaxFrames.get -> int +Sdcb.SimdCodecs.StreamFrameEncoder +Sdcb.SimdCodecs.StreamFrameEncoder.RowsWritten.get -> int +Sdcb.SimdCodecs.StreamFrameEncoder.WriteRows(System.ReadOnlySpan rows, int rowCount, int stride = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void +Sdcb.SimdCodecs.StreamFrameEncoder.WriteRowsAsync(System.ReadOnlyMemory rows, int rowCount, int stride = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask +static Sdcb.SimdCodecs.ImageCodecs.CreateEncoder(Sdcb.SimdCodecs.Abstractions.ImageFormat format, System.IO.Stream! output, Sdcb.SimdCodecs.Abstractions.EncodeOptions? options = null, bool leaveOpen = false) -> Sdcb.SimdCodecs.StreamEncoderSession! +static Sdcb.SimdCodecs.ImageCodecs.OpenRowReader(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Sdcb.SimdCodecs.Abstractions.IImageRowReader! +static Sdcb.SimdCodecs.ImageCodecs.OpenRowReaderAsync(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/src/Sdcb.SimdCodecs/StreamBufferWriter.cs b/src/Sdcb.SimdCodecs/StreamBufferWriter.cs new file mode 100644 index 0000000..00c680f --- /dev/null +++ b/src/Sdcb.SimdCodecs/StreamBufferWriter.cs @@ -0,0 +1,116 @@ +using System.Buffers; +using System.IO; + +namespace Sdcb.SimdCodecs; + +/// +/// The an encoder writes into when its file goes to a : a pooled chunk +/// of bytes that is written to the stream as it fills. With (the +/// synchronous path) a request for more space than is left writes the pending bytes synchronously first, so the buffer +/// stays at one chunk unless a single request is larger. Without it (the asynchronous path, which cannot write from +/// inside ) the buffer grows, and the caller writes the pending bytes with +/// between the encoder's calls. +/// +internal sealed class StreamBufferWriter : IBufferWriter, IDisposable +{ + /// The pending bytes at which a caller writes them to the stream, and the buffer's first size. + public const int ChunkSize = 64 * 1024; + + private readonly Stream _stream; + private byte[] _buffer; + private int _count; + + public StreamBufferWriter(Stream stream) + { + _stream = stream; + _buffer = ArrayPool.Shared.Rent(ChunkSize); + } + + /// Write the pending bytes synchronously when a request does not fit. + public bool FlushWhenFull { get; set; } = true; + + /// Bytes the encoder wrote that have not reached the stream yet. + public int Pending => _count; + + /// True once is a chunk or more: time to write them. + public bool ChunkReady => _count >= ChunkSize; + + public void Advance(int count) + { + ObjectDisposedException.ThrowIf(_buffer.Length == 0, this); + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (count > _buffer.Length - _count) + throw new InvalidOperationException($"Advanced {count} bytes past the {_buffer.Length - _count} the buffer has left."); + _count += count; + } + + public Memory GetMemory(int sizeHint = 0) + { + Reserve(sizeHint); + return _buffer.AsMemory(_count); + } + + public Span GetSpan(int sizeHint = 0) + { + Reserve(sizeHint); + return _buffer.AsSpan(_count); + } + + /// Writes the pending bytes to the stream, synchronously. + public void Flush() + { + if (_count == 0) return; + _stream.Write(_buffer, 0, _count); + _count = 0; + Shrink(); + } + + /// Writes the pending bytes to the stream, asynchronously. + public async ValueTask FlushAsync(CancellationToken cancellationToken) + { + if (_count == 0) return; + await _stream.WriteAsync(_buffer.AsMemory(0, _count), cancellationToken).ConfigureAwait(false); + _count = 0; + Shrink(); + } + + // Once a large call's bytes are written, the buffer goes back to one chunk, so the session holds no more than a + // band's output between calls. + private void Shrink() + { + if (_buffer.Length <= 2 * ChunkSize) return; + ArrayPool.Shared.Return(_buffer); + _buffer = ArrayPool.Shared.Rent(ChunkSize); + } + + /// Returns the buffer to the pool; pending bytes are dropped. + public void Dispose() + { + if (_buffer.Length == 0) return; + ArrayPool.Shared.Return(_buffer); + _buffer = []; + _count = 0; + } + + private void Reserve(int sizeHint) + { + ObjectDisposedException.ThrowIf(_buffer.Length == 0, this); + ArgumentOutOfRangeException.ThrowIfNegative(sizeHint); + var need = Math.Max(sizeHint, 1); + if (_buffer.Length - _count >= need) + return; + if (FlushWhenFull && _count > 0) + { + Flush(); + if (_buffer.Length >= need) + return; + } + var size = Math.Max((long)_buffer.Length * 2, (long)_count + need); + if ((long)_count + need > Array.MaxLength) + throw new InvalidOperationException($"The encoder asked for {need} more bytes than one buffer holds."); + var grown = ArrayPool.Shared.Rent((int)Math.Min(size, Array.MaxLength)); + _buffer.AsSpan(0, _count).CopyTo(grown); + ArrayPool.Shared.Return(_buffer); + _buffer = grown; + } +} diff --git a/src/Sdcb.SimdCodecs/StreamEncoderSession.cs b/src/Sdcb.SimdCodecs/StreamEncoderSession.cs new file mode 100644 index 0000000..11248ce --- /dev/null +++ b/src/Sdcb.SimdCodecs/StreamEncoderSession.cs @@ -0,0 +1,164 @@ +using System.IO; +using Sdcb.SimdCodecs.Abstractions; + +namespace Sdcb.SimdCodecs; + +/// +/// An encoding session writing its file to a (): +/// the format's own session over a buffer of about 64 KiB that is written to the stream whenever it fills, so the file +/// reaches the stream as the encoder produces it. The synchronous members write the stream synchronously; the +/// Async ones (, , ) +/// only asynchronously, for a stream that forbids synchronous writes. +/// +public sealed class StreamEncoderSession : IImageEncoderSession, IAsyncDisposable +{ + private readonly IImageEncoderSession _inner; + private readonly StreamBufferWriter _writer; + private readonly Stream _stream; + private readonly bool _leaveOpen; + private bool _disposed; + + internal StreamEncoderSession(IImageEncoderSession inner, StreamBufferWriter writer, Stream stream, bool leaveOpen) + { + _inner = inner; + _writer = writer; + _stream = stream; + _leaveOpen = leaveOpen; + } + + /// + /// True when the format's encoder encodes rows as they are written, so the file reaches the stream before + /// ; false when it encodes whole frames at (see + /// ). + /// + public bool IsStreaming => _inner.IsStreaming; + + /// + public int MaxFrames => _inner.MaxFrames; + + /// Starts the next frame (see ); push its rows with + /// or . + /// + /// + public StreamFrameEncoder AddFrame(int width, int height, PixelFormat format, ColorEncoding? color = null, + ImageMetadata? metadata = null, TimeSpan? duration = null) + { + ObjectDisposedException.ThrowIf(_disposed, this); + // A header the encoder writes here is written to the stream with the frame's first rows. + _writer.FlushWhenFull = false; + return new StreamFrameEncoder(this, _inner.AddFrame(width, height, format, color, metadata, duration)); + } + + IImageFrameEncoder IImageEncoderSession.AddFrame(int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) => AddFrame(width, height, format, color, metadata, duration); + + /// Finishes the file (see ), writes the rest of it to the stream and + /// flushes the stream, synchronously. + /// No frame was added, or the last one is incomplete. + /// was cancelled. + public void Commit(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _writer.FlushWhenFull = true; + _inner.Commit(cancellationToken); + _writer.Flush(); + _stream.Flush(); + } + + /// , writing and flushing the stream asynchronously. + /// + public async ValueTask CommitAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _writer.FlushWhenFull = false; + _inner.Commit(cancellationToken); + await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + /// Releases the session and, unless it was opened to leave it open, disposes the stream. Bytes of an + /// uncommitted file not yet written are dropped. + public void Dispose() + { + if (!Release()) return; + if (!_leaveOpen) + _stream.Dispose(); + } + + /// , disposing the stream asynchronously. + public async ValueTask DisposeAsync() + { + if (!Release()) return; + if (!_leaveOpen) + await _stream.DisposeAsync().ConfigureAwait(false); + } + + private bool Release() + { + if (_disposed) return false; + _disposed = true; + try + { + _inner.Dispose(); + } + finally + { + _writer.Dispose(); + } + return true; + } + + internal void WriteRows(IImageFrameEncoder frame, ReadOnlySpan rows, int rowCount, int stride, + CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _writer.FlushWhenFull = true; + frame.WriteRows(rows, rowCount, stride, cancellationToken); + if (_writer.ChunkReady) + _writer.Flush(); + } + + internal async ValueTask WriteRowsAsync(IImageFrameEncoder frame, ReadOnlyMemory rows, int rowCount, int stride, + CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(_disposed, this); + _writer.FlushWhenFull = false; + frame.WriteRows(rows.Span, rowCount, stride, cancellationToken); + if (_writer.ChunkReady) + await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); + } +} + +/// +/// The rows of one frame of a , pushed top to bottom; what the encoder makes of them +/// is written to the stream about every 64 KiB. +/// +public sealed class StreamFrameEncoder : IImageFrameEncoder +{ + private readonly StreamEncoderSession _session; + private readonly IImageFrameEncoder _inner; + + internal StreamFrameEncoder(StreamEncoderSession session, IImageFrameEncoder inner) + { + _session = session; + _inner = inner; + } + + /// + public int RowsWritten => _inner.RowsWritten; + + /// + /// Writes the next rows, bytes apart (0: tightly packed), in the + /// frame's format; the encoded bytes are written to the stream synchronously once a chunk is ready. + /// + /// The rows run past the frame or is too short. + /// was cancelled. + public void WriteRows(ReadOnlySpan rows, int rowCount, int stride = 0, CancellationToken cancellationToken = default) => + _session.WriteRows(_inner, rows, rowCount, stride, cancellationToken); + + /// , writing the stream asynchronously (the rows are encoded synchronously, then the + /// ready bytes written). + /// + public ValueTask WriteRowsAsync(ReadOnlyMemory rows, int rowCount, int stride = 0, CancellationToken cancellationToken = default) => + _session.WriteRowsAsync(_inner, rows, rowCount, stride, cancellationToken); +} diff --git a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs index f80139a..20b13d4 100644 --- a/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs +++ b/tests/Sdcb.SimdCodecs.AotSmoke/FacadeSmoke.cs @@ -33,7 +33,7 @@ public static async Task RunAsync() } Check(!ImageCodecs.CanDecode("not an image"u8), "garbage", "CanDecode"); - return count + Heif() + V2(); + return count + Heif() + V2() + await StreamingAsync(); } /// @@ -167,6 +167,9 @@ private static void Exercise(string label, byte[] data) { Check(Throws(() => ImageCodecs.Decode(data, PixelFormat.Rgba32)), label, "Decode Rgba32 refuses float"); } + // The row reader over a stream that cannot seek, in bands of 5 rows: TryDecodeInto's rows. + if (info.SampleFormat != SampleFormat.Float32) + Check(ReadRows(data).AsSpan().SequenceEqual(rgba), label, "OpenRowReader Rgba32"); // Cut short past its header, the file is corrupt: Decode throws why, TryDecode returns false. var cut = data.AsSpan(0, Math.Min(data.Length, 40)).ToArray(); if (!ImageCodecs.TryDecode(cut, out var cutImage)) @@ -240,6 +243,81 @@ private static int Heif() return 2; } + /// + /// The stream entry points asynchronously only: on a few formats, and + /// with WriteRowsAsync / CommitAsync + /// for every built-in encoder, whose bytes must equal the one-call encode's. + /// + private static async Task StreamingAsync() + { + const int w = 37, h = 23; + var rgb = Program.Pattern(w, h); + var hashes = new List(); + foreach (var format in new[] { ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Tiff, ImageFormat.Webp, ImageFormat.Gif, + ImageFormat.Bmp, ImageFormat.Ico, ImageFormat.Qoi, ImageFormat.Pnm }) + { + var label = $"stream {format}"; + var file = ImageCodecs.Encode(rgb, w, h, PixelFormat.Rgb24, format); + using var sink = new MemoryStream(); + await using (var session = ImageCodecs.CreateEncoder(format, sink, leaveOpen: true)) + { + var frame = session.AddFrame(w, h, PixelFormat.Rgb24); + for (var y = 0; y < h; y += 4) + await frame.WriteRowsAsync(rgb.AsMemory(y * w * 3), Math.Min(4, h - y)); + await session.CommitAsync(); + hashes.Add($"{format}={(session.IsStreaming ? 's' : 'b')}"); + } + Check(sink.ToArray().AsSpan().SequenceEqual(file), label, "CreateEncoder(Stream)"); + + await using var reader = await ImageCodecs.OpenRowReaderAsync(new ForwardStream(file), PixelFormat.Bgra32); + var rows = new byte[reader.Width * reader.Height * 4]; + while (reader.RowsRead < reader.Height) + await reader.ReadRowsAsync(rows.AsMemory(reader.RowsRead * reader.Width * 4), 7); + var expected = new byte[rows.Length]; + Check(ImageCodecs.TryDecodeInto(file, expected, 0, PixelFormat.Bgra32), label, "TryDecodeInto Bgra32"); + Check(rows.AsSpan().SequenceEqual(expected), label, "OpenRowReaderAsync Bgra32"); + hashes[^1] += $"/{Hash(rows)}"; + } + Check(Throws(() => ImageCodecs.OpenRowReader(new ForwardStream("not an image"u8.ToArray()), PixelFormat.Rgba32)), + "stream", "OpenRowReader (unknown)"); + Console.WriteLine($"facade streaming\t{string.Join(' ', hashes)}"); + return 1; + } + + // Every row of data through the synchronous row reader, Rgba32, in bands of 5. + private static byte[] ReadRows(byte[] data) + { + using var reader = ImageCodecs.OpenRowReader(new ForwardStream(data), PixelFormat.Rgba32); + var rows = new byte[reader.Width * reader.Height * 4]; + while (reader.RowsRead < reader.Height) + reader.ReadRows(rows.AsSpan(reader.RowsRead * reader.Width * 4), 5); + return rows; + } + + /// A stream that cannot seek and hands out at most 100 bytes per read, as a network stream does. + private sealed class ForwardStream(byte[] data) : Stream + { + private int _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 => throw new NotSupportedException(); 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) + { + var n = Math.Min(Math.Min(count, 100), data.Length - _position); + data.AsSpan(_position, n).CopyTo(buffer.AsSpan(offset)); + _position += n; + return n; + } + } + private static async Task> SamplesAsync() { const int w = 37, h = 23; diff --git a/tests/Sdcb.SimdCodecs.Tests/Streaming/FacadeStreamingTests.cs b/tests/Sdcb.SimdCodecs.Tests/Streaming/FacadeStreamingTests.cs new file mode 100644 index 0000000..18856c3 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/Streaming/FacadeStreamingTests.cs @@ -0,0 +1,504 @@ +using System.Buffers; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests.Streaming; + +/// +/// The facade's stream entry points: / +/// sniff and dispatch to a codec's streaming decoder or the buffered fallback, with 's +/// rows; writes the buffer-writer +/// session's bytes to a stream as they come, synchronously or asynchronously only; Encode(…, Stream) writes the +/// bytes it always wrote. +/// +[Collection(FacadeRegistryCollection.Name)] +public sealed class FacadeStreamingTests : IDisposable +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static readonly ImageFormat[] EncoderFormats = + [ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Tiff, ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Bmp, + ImageFormat.Ico, ImageFormat.Qoi, ImageFormat.Pnm]; + + private readonly ImageDecoderRegistration[] _builtIn = ImageCodecs.RegistrySnapshot; + private readonly ImageEncoderRegistration[] _encoders = ImageCodecs.EncoderSnapshot; + + public void Dispose() + { + ImageCodecs.ExchangeRegistry(_builtIn); + ImageCodecs.ExchangeEncoders(_encoders); + } + + private void UseRegistry(ImageDecoderRegistration first) => ImageCodecs.ExchangeRegistry([first, .. _builtIn]); + + private static byte[] Pattern(int w, int h, int channels, int seed) + { + var pixels = new byte[w * h * channels]; + var random = new Random(seed); + for (var i = 0; i < pixels.Length; i++) + pixels[i] = (byte)((i % (w * channels)) * 3 + (i / (w * channels)) * 5 + random.Next(0, 8)); + return pixels; + } + + private static byte[] Fixture(string directory, string name) => + File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Fixtures", directory, name)); + + private static Stream Feed(byte[] file, StreamingAssert.Feed feed, int seed = 1) => feed switch + { + StreamingAssert.Feed.OneByte => new ChunkedStream(file, maxChunk: 1, seed), + StreamingAssert.Feed.RandomChunks => new ChunkedStream(file, maxChunk: 4096, seed), + StreamingAssert.Feed.AsyncOnly => new ChunkedStream(file, maxChunk: 997, seed, asyncOnly: true), + _ => new MemoryStream(file, writable: false), + }; + + /// Opens through the facade fed as says and reads every row. + private static async Task<(byte[] Rows, bool Streaming, int Width, int Height)> ReadAllAsync(byte[] file, + StreamingAssert.Feed feed, PixelFormat format, DecodeOptions? options = null) + { + var async = feed == StreamingAssert.Feed.AsyncOnly; + await using var reader = async + ? await ImageCodecs.OpenRowReaderAsync(Feed(file, feed), format, options, cancellationToken: Ct) + : ImageCodecs.OpenRowReader(Feed(file, feed), format, options, cancellationToken: Ct); + reader.Format.ShouldBe(format); + var rowBytes = reader.Width * format.BytesPerPixel; + var rows = new byte[rowBytes * reader.Height]; + var random = new Random(7); + while (reader.RowsRead < reader.Height) + { + var band = feed switch + { + StreamingAssert.Feed.OneByte => 1, + StreamingAssert.Feed.Whole => reader.Height, + _ => random.Next(1, 17), + }; + var at = reader.RowsRead * rowBytes; + var n = async + ? await reader.ReadRowsAsync(rows.AsMemory(at), band, 0, Ct) + : reader.ReadRows(rows.AsSpan(at), band, 0, Ct); + n.ShouldBeGreaterThan(0, $"{feed}: no rows at {reader.RowsRead} of {reader.Height}"); + } + (async ? await reader.ReadRowsAsync(Memory.Empty, 1, 0, Ct) : reader.ReadRows([], 1, 0, Ct)).ShouldBe(0); + return (rows, reader.IsStreaming, reader.Width, reader.Height); + } + + /// Asserts every feed's rows equal 's; returns whether the reader streamed. + private static async Task RowsEqualDecodeIntoAsync(byte[] file, PixelFormat format, DecodeOptions? options = null, + StreamingAssert.Feed[]? feeds = null, string? label = null) + { + ImageCodecs.TryReadInfo(file, out var info).ShouldBeTrue(label); + var (w, h) = (options ?? DecodeOptions.Default).GetOutputSize(info); + var expected = new byte[w * h * format.BytesPerPixel]; + ImageCodecs.TryDecodeInto(file, expected, 0, format, options, Ct).ShouldBeTrue(label); + bool? streaming = null; + foreach (var feed in feeds ?? StreamingAssert.AllFeeds) + { + var (rows, s, rw, rh) = await ReadAllAsync(file, feed, format, options); + (rw, rh).ShouldBe((w, h), $"{label} {feed}: size"); + if (!rows.AsSpan().SequenceEqual(expected)) + throw new ShouldAssertException($"{label} {feed}: rows differ from TryDecodeInto at byte {rows.AsSpan().CommonPrefixLength(expected)}."); + streaming ??= s; + s.ShouldBe(streaming.Value, $"{label} {feed}: IsStreaming depends on the feed"); + } + return streaming!.Value; + } + + [Fact] + public async Task OpenRowReader_DispatchesToTheStreamingDecoder() + { + UseRegistry(RawStreamCodec.Registration); + var file = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(37, 23, 3), 37, 23); + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Bgr24, PixelFormat.Gray8, PixelFormat.Rgba64 }) + (await RowsEqualDecodeIntoAsync(file, format, label: format.ToString())).ShouldBeTrue(); + + // The codec's own fallback (a variant it cannot stream) and an option it does not stream: buffered, same rows. + var fallback = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(41, 17, 5), 41, 17, fallback: true); + (await RowsEqualDecodeIntoAsync(fallback, PixelFormat.Bgra32)).ShouldBeFalse(); + } + + [Fact] + public async Task OpenRowReader_ReadsTheStreamOnlyAsFarAsTheRowsNeed() + { + UseRegistry(RawStreamCodec.Registration); + const int w = 256, h = 256; + var file = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(w, h, 3), w, h); + var stream = new ChunkedStream(file, maxChunk: 1024, asyncOnly: true); + await using var reader = await ImageCodecs.OpenRowReaderAsync(stream, PixelFormat.Rgba32, cancellationToken: Ct); + (await reader.ReadRowsAsync(new byte[w * 4], 1, 0, Ct)).ShouldBe(1); + reader.IsStreaming.ShouldBeTrue(); + stream.BytesRead.ShouldBeLessThan(file.Length / 2); + } + + [Fact] + public async Task OpenRowReader_ACodecWithoutAStreamingDecoderIsBuffered() + { + UseRegistry(RawStreamCodec.NonStreamingRegistration); + var file = RawStreamCodec.Encode(RawStreamCodec.RandomRgba(29, 13, 9), 29, 13); + foreach (var format in new[] { PixelFormat.Rgb24, PixelFormat.Rgba32 }) + (await RowsEqualDecodeIntoAsync(file, format)).ShouldBeFalse(); + } + + [Fact] + public async Task OpenRowReader_EveryBuiltInFormatEqualsDecodeInto() + { + const int w = 37, h = 23; + var rgb = Pattern(w, h, 3, 1); + var files = EncoderFormats.Select(f => (f.ToString(), ImageCodecs.Encode(rgb, w, h, PixelFormat.Rgb24, f))).ToList(); + files.Add(("webp-lossy", Fixture("webp", "astronaut-192-q20-normal.webp"))); + files.Add(("webp-lossless", Fixture("webp", "lossless-palette-16.webp"))); + files.Add(("jbig2", Fixture("jbig2", "sym.jb2"))); + files.Add(("jp2", Fixture("jpeg2000", "jp2-rgb-struct64.jp2"))); + foreach (var (label, file) in files) + { + await RowsEqualDecodeIntoAsync(file, PixelFormat.Rgba32, label: label, + feeds: [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly, StreamingAssert.Feed.Whole]); + await RowsEqualDecodeIntoAsync(file, PixelFormat.Bgr24, label: label, feeds: [StreamingAssert.Feed.OneByte]); + // Options a codec may not stream: the rows are still TryDecodeInto's. + await RowsEqualDecodeIntoAsync(file, PixelFormat.Rgba32, new DecodeOptions { ScaleDenominator = 2 }, label: label + " 1/2", + feeds: [StreamingAssert.Feed.RandomChunks]); + await RowsEqualDecodeIntoAsync(file, PixelFormat.Gray8, new DecodeOptions { Region = new PixelRect(3, 2, 11, 9) }, + label: label + " region", feeds: [StreamingAssert.Feed.AsyncOnly]); + } + } + + [Fact] + public async Task OpenRowReader_UnknownOrUndecodableInputThrowsInvalidData() + { + foreach (var file in new[] { "not an image at all"u8.ToArray(), [], [0x89] }) + { + var e = Should.Throw(() => ImageCodecs.OpenRowReader(new ChunkedStream(file), PixelFormat.Rgba32)); + e.Message.ShouldBe(ImageCodecs.NoCodecMessage(file)); + await Should.ThrowAsync(async () => + await ImageCodecs.OpenRowReaderAsync(new ChunkedStream(file, asyncOnly: true), PixelFormat.Rgba32, cancellationToken: Ct)); + } + + // HEIF is recognised but not registered: the message says how to enable it. + byte[] heif = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8]; + Should.Throw(() => ImageCodecs.OpenRowReader(new MemoryStream(heif), PixelFormat.Rgba32)) + .Message.ShouldContain("Sdcb.SimdCodecs.Heif"); + + // An ftyp box longer than 64 bytes is sniffed whole: its 'avif' brand past byte 64 makes it AVIF, as for DetectFormat. + var avif = new byte[100]; + avif[3] = 100; + "ftypmif1"u8.CopyTo(avif.AsSpan(4)); + for (var at = 16; at < 96; at += 4) + "abcd"u8.CopyTo(avif.AsSpan(at)); + "mif1"u8.CopyTo(avif.AsSpan(16)); + "avif"u8.CopyTo(avif.AsSpan(96)); + ImageCodecs.DetectFormat(avif).ShouldBe(ImageFormat.Avif); + Should.Throw(() => ImageCodecs.OpenRowReader(new ChunkedStream(avif), PixelFormat.Rgba32)) + .Message.ShouldBe(ImageCodecs.NoCodecMessage(avif)); + (await Should.ThrowAsync(async () => + await ImageCodecs.OpenRowReaderAsync(new ChunkedStream(avif, asyncOnly: true), PixelFormat.Rgba32, cancellationToken: Ct))) + .Message.ShouldContain("AVIF"); + + // A truncated or corrupt file of a known format: the codec's reason, prefixed with the format. + var png = ImageCodecs.Encode(Pattern(40, 30, 3, 2), 40, 30, PixelFormat.Rgb24, ImageFormat.Png); + foreach (var cut in new[] { 8, 30, png.Length / 2, png.Length - 1 }) + { + foreach (var feed in StreamingAssert.AllFeeds) + { + await Should.ThrowAsync(async () => await ReadAllAsync(png[..cut], feed, PixelFormat.Rgba32), + $"cut at {cut}, {feed}"); + } + } + var corrupt = (byte[])png.Clone(); + corrupt[^20] ^= 0xFF; + Should.Throw(() => ImageCodecs.OpenRowReader(new MemoryStream(corrupt), PixelFormat.Rgba32)) + .Message.ShouldStartWith("The PNG file cannot be decoded"); + } + + [Fact] + public void OpenRowReader_FloatImagesHaveNoIntegerRows() + { + var pfm = Sdcb.SimdCodecs.Pnm.PnmEncoder.EncodePfm([.. Pattern(8, 4, 3, 3).Select(b => b / 255f)], 8, 4, 3); + Should.Throw(() => ImageCodecs.Decode(pfm, PixelFormat.Rgba32)); + Should.Throw(() => ImageCodecs.OpenRowReader(new MemoryStream(pfm), PixelFormat.Rgba32)); + } + + [Fact] + public async Task OpenRowReader_DisposesTheStreamUnlessLeftOpen() + { + var file = ImageCodecs.Encode(Pattern(9, 7, 3, 4), 9, 7, PixelFormat.Rgb24, ImageFormat.Bmp); + foreach (var leaveOpen in new[] { false, true }) + { + var stream = new ChunkedStream(file); + using (var reader = ImageCodecs.OpenRowReader(stream, PixelFormat.Rgba32, leaveOpen: leaveOpen)) + stream.WasDisposed.ShouldBeFalse(); + stream.WasDisposed.ShouldBe(!leaveOpen, $"leaveOpen {leaveOpen}"); + + var asyncStream = new ChunkedStream(file, asyncOnly: true); + await using (var reader = await ImageCodecs.OpenRowReaderAsync(asyncStream, PixelFormat.Rgba32, leaveOpen: leaveOpen, cancellationToken: Ct)) + asyncStream.WasDisposed.ShouldBeFalse(); + asyncStream.WasDisposed.ShouldBe(!leaveOpen); + + // When the open fails, the stream is disposed as the reader would have disposed it. + var garbage = new ChunkedStream("garbage, not an image"u8.ToArray()); + Should.Throw(() => ImageCodecs.OpenRowReader(garbage, PixelFormat.Rgba32, leaveOpen: leaveOpen)); + garbage.WasDisposed.ShouldBe(!leaveOpen); + } + + Should.Throw(() => ImageCodecs.OpenRowReader(null!, PixelFormat.Rgba32)); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Should.ThrowAsync(async () => + await ImageCodecs.OpenRowReaderAsync(new ChunkedStream(file, asyncOnly: true), PixelFormat.Rgba32, cancellationToken: cancelled.Token)); + } + + [Fact] + public async Task CreateEncoderStream_WritesTheBufferWriterSessionsBytes() + { + const int w = 256, h = 200; // ICO's largest width; large enough that most formats write more than one 64 KiB chunk + var rgb = Pattern(w, h, 3, 5); + foreach (var format in EncoderFormats) + { + var expected = new ArrayBufferWriter(); + bool streaming; + using (var session = ImageCodecs.CreateEncoder(format, expected)) + { + streaming = session.IsStreaming; + session.AddFrame(w, h, PixelFormat.Rgb24).WriteRows(rgb, h, 0, Ct); + session.Commit(Ct); + } + + // Synchronously, in bands. + var sink = new WriteLog(asyncOnly: false); + using (var session = ImageCodecs.CreateEncoder(format, sink, leaveOpen: true)) + { + session.IsStreaming.ShouldBe(streaming); + session.MaxFrames.ShouldBeGreaterThanOrEqualTo(1); + var frame = session.AddFrame(w, h, PixelFormat.Rgb24); + for (var y = 0; y < h; y += 17) + frame.WriteRows(rgb.AsSpan(y * w * 3), Math.Min(17, h - y), 0, Ct); + frame.RowsWritten.ShouldBe(h); + session.Commit(Ct); + } + sink.WasDisposed.ShouldBeFalse(); + sink.ToArray().ShouldBe(expected.WrittenSpan.ToArray(), $"{format} sync"); + sink.Flushes.ShouldBe(1); + + // Asynchronously only, into a stream whose synchronous members throw; disposing it disposes the stream. + var asyncSink = new WriteLog(asyncOnly: true); + await using (var session = ImageCodecs.CreateEncoder(format, asyncSink)) + { + var frame = session.AddFrame(w, h, PixelFormat.Rgb24); + for (var y = 0; y < h; y += 23) + await frame.WriteRowsAsync(rgb.AsMemory(y * w * 3), Math.Min(23, h - y), 0, Ct); + await session.CommitAsync(Ct); + } + asyncSink.WasDisposed.ShouldBeTrue(); + asyncSink.ToArray().ShouldBe(expected.WrittenSpan.ToArray(), $"{format} async"); + } + } + + [Fact] + public async Task CreateEncoderStream_AStreamingEncodersBytesReachTheStreamBeforeCommit() + { + ImageCodecs.ExchangeEncoders([RawEncoderSession.Registration, .. _encoders]); + const int w = 512, h = 256; // 512 KiB of RGBA: eight chunks + var rgba = RawStreamCodec.RandomRgba(w, h, 6); + var expected = RawStreamCodec.Encode(rgba, w, h); + foreach (var async in new[] { false, true }) + { + var sink = new WriteLog(asyncOnly: async); + await using (var session = ImageCodecs.CreateEncoder(ImageFormat.Qoi, sink)) + { + session.IsStreaming.ShouldBeTrue(); + var frame = session.AddFrame(w, h, PixelFormat.Rgba32); + for (var y = 0; y < h; y += 16) + { + if (async) + await frame.WriteRowsAsync(rgba.AsMemory(y * w * 4, 16 * w * 4), 16, 0, Ct); + else + frame.WriteRows(rgba.AsSpan(y * w * 4, 16 * w * 4), 16, 0, Ct); + // Never more than a chunk (and one band) held back. + (RawStreamCodec.HeaderLength + (y + 16) * w * 4 - sink.Length).ShouldBeLessThan(StreamBufferWriter.ChunkSize + 16 * w * 4); + } + sink.Length.ShouldBeGreaterThan(expected.Length / 2, "bytes reached the stream before Commit"); + if (async) await session.CommitAsync(Ct); + else session.Commit(Ct); + } + sink.ToArray().ShouldBe(expected, async ? "async" : "sync"); + sink.Writes.ShouldBeGreaterThan(4); + } + } + + [Fact] + public void CreateEncoderStream_ChecksItsArguments() + { + Should.Throw(() => ImageCodecs.CreateEncoder(ImageFormat.Png, (Stream)null!)); + Should.Throw(() => ImageCodecs.CreateEncoder(ImageFormat.Png, new MemoryStream([], writable: false))); + Should.Throw(() => ImageCodecs.CreateEncoder(ImageFormat.Avif, new MemoryStream())); + var stream = new WriteLog(asyncOnly: false); + Should.Throw(() => ImageCodecs.CreateEncoder(ImageFormat.Png, stream, new Sdcb.SimdCodecs.Jpeg.JpegEncodeOptions(), leaveOpen: true)); + stream.WasDisposed.ShouldBeFalse(); + var refused = new WriteLog(asyncOnly: false); + Should.Throw(() => ImageCodecs.CreateEncoder(ImageFormat.Png, refused, new Sdcb.SimdCodecs.Jpeg.JpegEncodeOptions())); + refused.WasDisposed.ShouldBeTrue("ownership passes with leaveOpen false, as for OpenRowReader"); + + var session = ImageCodecs.CreateEncoder(ImageFormat.Png, stream); + Should.Throw(() => session.Commit(Ct)); + var frame = session.AddFrame(2, 2, PixelFormat.Rgb24); + Should.Throw(() => frame.WriteRows(new byte[5], 2, 0, Ct)); + session.Dispose(); + session.Dispose(); + stream.WasDisposed.ShouldBeTrue(); + Should.Throw(() => frame.WriteRows(new byte[12], 2, 0, Ct)); + Should.Throw(() => session.Commit(Ct)); + } + + [Fact] + public void EncodeStream_WritesTheSameBytesInChunks() + { + const int w = 256, h = 256; // ICO's largest; files of several 64 KiB chunks + var rgb = Pattern(w, h, 3, 8); + foreach (var format in EncoderFormats) + { + var expected = ImageCodecs.Encode(rgb, w, h, PixelFormat.Rgb24, format); + var sink = new WriteLog(asyncOnly: false); + ImageCodecs.Encode(rgb, w, h, PixelFormat.Rgb24, format, sink); + sink.ToArray().ShouldBe(expected, $"{format} raw pixels"); + sink.Flushes.ShouldBe(0, "Encode(Stream) does not flush the stream"); + + using var image = ImageCodecs.Decode(expected); + var fromImage = new ArrayBufferWriter(); + ImageCodecs.Encode(image, format, fromImage); + var imageSink = new MemoryStream(); + ImageCodecs.Encode(image, format, imageSink); + imageSink.ToArray().ShouldBe(fromImage.WrittenSpan.ToArray(), $"{format} image"); + } + } + + [Fact] + public async Task StreamToStream_AsyncOnlyEndToEnd() + { + var sources = new[] + { + ImageCodecs.Encode(Pattern(333, 211, 3, 9), 333, 211, PixelFormat.Rgb24, ImageFormat.Jpeg), + ImageCodecs.Encode(Pattern(129, 64, 4, 10), 129, 64, PixelFormat.Rgba32, ImageFormat.Png), + Fixture("webp", "astronaut-192-q20-normal.webp"), + }; + foreach (var source in sources) + { + var output = new WriteLog(asyncOnly: true); + await using (var reader = await ImageCodecs.OpenRowReaderAsync(new ChunkedStream(source, maxChunk: 997, asyncOnly: true), + PixelFormat.Rgba32, cancellationToken: Ct)) + await using (var session = ImageCodecs.CreateEncoder(ImageFormat.Png, output, leaveOpen: true)) + { + var frame = session.AddFrame(reader.Width, reader.Height, PixelFormat.Rgba32); + var band = new byte[reader.Width * 4 * 8]; + int n; + while ((n = await reader.ReadRowsAsync(band, 8, 0, Ct)) > 0) + await frame.WriteRowsAsync(band.AsMemory(0, n * reader.Width * 4), n, 0, Ct); + await session.CommitAsync(Ct); + } + + ImageCodecs.TryReadInfo(source, out var info).ShouldBeTrue(); + var expected = new byte[info.Width * info.Height * 4]; + ImageCodecs.TryDecodeInto(source, expected, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + var actual = new byte[expected.Length]; + ImageCodecs.TryDecodeInto(output.ToArray(), actual, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + actual.ShouldBe(expected); + } + } + + /// A write-only stream that records what it is given; with asyncOnly its synchronous members throw, as + /// an ASP.NET Core response body's do by default. + private sealed class WriteLog(bool asyncOnly) : Stream + { + private readonly MemoryStream _data = new(); + + public int Writes { get; private set; } + public int Flushes { get; private set; } + public bool WasDisposed { get; private set; } + + public byte[] ToArray() => _data.ToArray(); + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => !WasDisposed; + public override long Length => _data.Length; + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Flush() + { + if (asyncOnly) throw new InvalidOperationException("Synchronous operations are disallowed."); + Flushes++; + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await Task.Yield(); + Flushes++; + } + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + if (asyncOnly) throw new InvalidOperationException("Synchronous operations are disallowed."); + Append(buffer); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await Task.Yield(); + Append(buffer.Span); + } + + private void Append(ReadOnlySpan buffer) + { + ObjectDisposedException.ThrowIf(WasDisposed, this); + Writes++; + _data.Write(buffer); + } + + protected override void Dispose(bool disposing) + { + WasDisposed = true; + base.Dispose(disposing); + } + + public override ValueTask DisposeAsync() + { + WasDisposed = true; + return ValueTask.CompletedTask; + } + } + + /// The format as a streaming encoder: header at the frame, rows as they come. + private sealed class RawEncoderSession(IBufferWriter output) : StreamingEncoderSession(output) + { + public static ImageEncoderRegistration Registration { get; } = new() + { + Format = ImageFormat.Qoi, + GetClosestInputFormat = _ => PixelFormat.Rgba32, + Create = (output, _) => new RawEncoderSession(output), + }; + + private int _width; + + public override int MaxFrames => 1; + + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) + { + _width = width; + WriteOutput(RawStreamCodec.Encode([], width, height).AsSpan(0, RawStreamCodec.HeaderLength)); + } + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + for (var y = 0; y < rowCount; y++) + WriteOutput(rows.Slice(y * stride, _width * 4)); + } + + protected override void Finish(CancellationToken cancellationToken) => WriteOutput("END!"u8); + } +}