From 1f4368b9de8b4be25cb311573957fb8193d6e225 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:19:08 +0800 Subject: [PATCH 1/6] QOI: streaming row reader and streaming encoder session QoiImageDecoder implements IStreamingImageDecoder: CreateRowReader decodes a forward-only stream a row at a time (sync and async). A row decodes on a copy of the reader state and is kept only when all its chunks are buffered; a failed attempt waits for twice the bytes (capped at 5 bytes a pixel), so a byte-at-a-time stream costs a few decodes per row. Non-full-image options take the buffered fallback. Rows come from the same per-row step as TryDecodeInto (QoiDecoder.TryDecodeRow), so they are the same bytes for every PixelFormat. QoiImageEncoder.Create returns a StreamingEncoderSession: header at AddFrame, each band encoded and written as it arrives with the encoder state (index, previous pixel, open run) carried across bands, end marker at Commit. Bytes equal QoiEncoder.Encode for any banding (shared WriteHeader/WriteRow/WriteEnd). Tests: QoiStreamingTests (rows vs TryDecodeInto over every feed and format, ImageMagick-written and hand-assembled streams, every cut, banded encode bytes, emits before commit, 8192x4096 decode/encode under 1 MiB, async-only pipe into the encoder) and QoiStreamingRobustnessTests (QOI_STREAM_FUZZ_ITERATIONS). The QoiPnm benchmark gains a QOI `streaming` contestant. Co-Authored-By: Claude Opus 5.5 --- .../Bench.cs | 51 ++- .../Infrastructure.cs | 2 + .../PublicAPI.Unshipped.txt | 1 + src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs | 30 +- src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs | 67 ++-- src/Sdcb.SimdCodecs.Qoi/QoiEncoder.cs | 76 ++-- src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs | 106 +++++- src/Sdcb.SimdCodecs.Qoi/QoiImageEncoder.cs | 44 ++- src/Sdcb.SimdCodecs.Qoi/README.md | 14 + .../QoiStreamingRobustnessTests.cs | 168 +++++++++ .../QoiStreamingTests.cs | 330 ++++++++++++++++++ 11 files changed, 812 insertions(+), 77 deletions(-) create mode 100644 tests/Sdcb.SimdCodecs.Tests/QoiStreamingRobustnessTests.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/QoiStreamingTests.cs diff --git a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs index 7e96c9a..47b55a0 100644 --- a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs +++ b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Bench.cs @@ -1,7 +1,9 @@ +using System.Buffers; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; using Sdcb.SimdCodecs.Png.Benchmarks; using Sdcb.SimdCodecs.Pnm; using Sdcb.SimdCodecs.Qoi; @@ -167,6 +169,22 @@ public static Setup Decode(Case c) } setup.Contestants.Add(new(Names.Current, () => Ours(rgba))); + if (c.Qoi) + { + // The streaming reader over a stream of the file, 16 rows a call, into the same kind of buffer. + var streamed = new byte[rgba.Length]; + void Stream() + { + using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(data, writable: false)), PixelFormat.Rgba32, null); + reader.Initialize(); + while (reader.RowsRead < reader.Height) + reader.ReadRows(streamed.AsSpan(reader.RowsRead * w * 4), 16); + } + Stream(); + if (!streamed.AsSpan().SequenceEqual(rgba)) throw new InvalidOperationException($"{c.Name}: the streaming reader differs from current"); + setup.Contestants.Add(new(Names.Streaming, Stream)); + } + if (Baseline.CanDecode(c.Qoi)) { var other = new byte[rgba.Length]; @@ -233,6 +251,29 @@ void Check(string name, byte[] output) toStream(); })); + if (c.Qoi) + { + // The streaming session, 16 rows a band, into a reused writer. + var writer = new ArrayBufferWriter(ours.Length + 64); + var rowBytes = w * format.BytesPerPixel; + void Session() + { + writer.ResetWrittenCount(); + using var session = QoiImageEncoder.Create(writer); + var frame = session.AddFrame(w, h, format); + for (var y = 0; y < h; y += 16) + { + var n = Math.Min(16, h - y); + frame.WriteRows(pixels.AsSpan(y * rowBytes, n * rowBytes), n); + } + session.Commit(); + } + Session(); + if (!writer.WrittenSpan.SequenceEqual(ours)) throw new InvalidOperationException($"{c.Name}: the streaming session's bytes differ from current"); + setup.Sizes[Names.Streaming] = writer.WrittenCount; + setup.Contestants.Add(new(Names.Streaming, Session)); + } + if (c.Format is not ("pfm" or "ppm16") && Baseline.CanEncode(c.Qoi)) { Func baseline; @@ -295,17 +336,17 @@ public static string Run(bool decode, int rounds) } var names = decode - ? new[] { Names.Current, Names.Baseline, Names.ImageSharp } - : [Names.Current, Names.CurrentStream, Names.Baseline, Names.ImageSharp]; + ? new[] { Names.Current, Names.Streaming, Names.Baseline, Names.ImageSharp } + : [Names.Current, Names.CurrentStream, Names.Streaming, Names.Baseline, Names.ImageSharp]; var compare = decode ? Names.Current : Names.CurrentStream; var sb = new StringBuilder(); sb.AppendLine($"### {(decode ? "Decode" : "Encode")} (in-process medians of {rounds} interleaved rounds, ms)"); sb.AppendLine(); sb.AppendLine(decode ? "`current` = `QoiImageDecoder` / `PnmImageDecoder.TryDecodeInto` to RGBA in a caller buffer (PFM: `PnmDecoder.Decode` to " + - "floats); ImageSharp = `Image.Load` + `CopyPixelDataTo`, one thread. Every timed output was checked against ours first." + "floats); `streaming` = QOI's `CreateRowReader` over a `MemoryStream`, 16 rows a call; ImageSharp = `Image.Load` + `CopyPixelDataTo`, one thread. Every timed output was checked against ours first." : "`current` = `QoiEncoder` / `PnmEncoder.Encode` to a new array; `current → stream` = the `Stream` overload into a reused " + - "stream, as ImageSharp writes; ImageSharp = its encoder from an image built beforehand into a reused stream, one thread. " + + "stream, as ImageSharp writes; `streaming` = QOI's streaming session in 16-row bands into a reused writer; ImageSharp = its encoder from an image built beforehand into a reused stream, one thread. " + "Every output decodes to the input."); sb.AppendLine(); sb.AppendLine("| Case | KB | " + string.Join(" | ", names.Select(Names.Label)) + $" | {Names.Label(compare)} ÷ ImageSharp | ÷ baseline |"); @@ -319,7 +360,7 @@ public static string Run(bool decode, int rounds) notes.AddRange(s.Notes.Select(n => $"`{s.Case.Name}`: {n}")); } sb.AppendLine(); - foreach (var (a, b) in new[] { (compare, Names.ImageSharp), (compare, Names.Baseline) }) + foreach (var (a, b) in new[] { (compare, Names.ImageSharp), (compare, Names.Baseline), (Names.Streaming, Names.Current) }) { foreach (var codec in new[] { "qoi", "pnm" }) { diff --git a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs index a655db4..1af974d 100644 --- a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs +++ b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Infrastructure.cs @@ -63,6 +63,7 @@ internal static class Names { public const string Current = "Current"; public const string CurrentStream = "CurrentStream"; + public const string Streaming = "Streaming"; public const string Baseline = "Baseline"; public const string ImageSharp = "ImageSharp"; @@ -70,6 +71,7 @@ internal static class Names { Current => "current", CurrentStream => "current → stream", + Streaming => "streaming", Baseline => "baseline", _ => name, }; diff --git a/src/Sdcb.SimdCodecs.Qoi/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Qoi/PublicAPI.Unshipped.txt index 7dc5c58..a58e094 100644 --- a/src/Sdcb.SimdCodecs.Qoi/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Qoi/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static Sdcb.SimdCodecs.Qoi.QoiImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs index 53282db..98f9382 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs @@ -82,10 +82,31 @@ public Reader(bool opaque) _px = 0xFF000000u; } + /// + /// The offset in the data of the next chunk: for a whole file; a streaming decoder + /// that hands the reader a window of the file sets it to the window's first unread byte. + /// + public int Position + { + readonly get => _position; + set => _position = value; + } + /// Decodes the next pixels.Length pixels. /// The chunks end first. - [MethodImpl(MethodImplOptions.AggressiveOptimization)] public void Read(ReadOnlySpan data, Span pixels) + { + if (!TryRead(data, pixels)) + throw new InvalidDataException("QOI data ends before the last pixel."); + } + + /// + /// Decodes the next pixels.Length pixels; false when the chunks end first (a chunk would run past the + /// data). Every byte is a valid chunk opcode, so running out is the only way to fail. After false the state is + /// partly advanced: a caller that retries with more data restores a copy taken before the call. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + public bool TryRead(ReadOnlySpan data, Span pixels) { var n = pixels.Length; var i = 0; @@ -100,7 +121,7 @@ public void Read(ReadOnlySpan data, Span pixels) if (i == n) { _run = run; - return; + return true; } // Every chunk is at most 5 bytes. While p <= limit = length − 5 a chunk read from p stays inside data. @@ -122,7 +143,7 @@ public void Read(ReadOnlySpan data, Span pixels) { var remaining = tailBase < 0 ? data.Length - p : 0; if (remaining <= 0) - throw new InvalidDataException("QOI data ends before the last pixel."); + return false; tail.Clear(); data[p..].CopyTo(tail); tailBase = p; @@ -189,12 +210,13 @@ public void Read(ReadOnlySpan data, Span pixels) if (tailBase >= 0) { if (p > limit + 1) - throw new InvalidDataException("QOI data ends inside the last chunk."); + return false; p += tailBase; } _position = p; _run = run; _px = px; + return true; } /// diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs index 95d809a..34956d1 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiDecoder.cs @@ -64,41 +64,54 @@ internal static void Decode(ReadOnlySpan data, QoiInfo info, Span de { var reader = new QoiCodec.Reader(info.Channels == 3); int width = info.Width, height = info.Height; - if (format == PixelFormat.Rgba32 || format == PixelFormat.Bgra32) + if (format == PixelFormat.Rgba32 && rowStride == width * 4 && !cancellationToken.CanBeCanceled) { - // RGBA pixels land in place; BGRA swaps them where they are. - var rowBytes = width * 4; - if (rowStride == rowBytes && format == PixelFormat.Rgba32 && !cancellationToken.CanBeCanceled) - { - reader.Read(data, MemoryMarshal.Cast(destination[..(rowBytes * height)])); - return; - } - for (var y = 0; y < height; y++) - { - if ((y & 63) == 0) - cancellationToken.ThrowIfCancellationRequested(); - var row = destination.Slice(y * rowStride, rowBytes); - reader.Read(data, MemoryMarshal.Cast(row)); - if (format == PixelFormat.Bgra32) - PixelConverter.ConvertRow(row, PixelFormat.Rgba32, row, PixelFormat.Bgra32, width); - } + // RGBA pixels land in place, the whole image in one call. + reader.Read(data, MemoryMarshal.Cast(destination[..(width * 4 * height)])); return; } - const int Chunk = 512; - Span chunk = stackalloc uint[Chunk]; - var bpp = format.BytesPerPixel; + Span chunk = stackalloc uint[RowChunk]; + var rowBytes = width * format.BytesPerPixel; for (var y = 0; y < height; y++) { if ((y & 63) == 0) cancellationToken.ThrowIfCancellationRequested(); - var row = destination.Slice(y * rowStride, width * bpp); - for (var x = 0; x < width; x += Chunk) - { - var n = Math.Min(Chunk, width - x); - reader.Read(data, chunk[..n]); - PixelConverter.ConvertRow(MemoryMarshal.AsBytes(chunk[..n]), PixelFormat.Rgba32, row[(x * bpp)..], format, n); - } + if (!TryDecodeRow(ref reader, data, destination.Slice(y * rowStride, rowBytes), width, format, chunk)) + throw new InvalidDataException("QOI data ends before the last pixel."); + } + } + + /// The pixels converts at a time when the format is not RGBA or BGRA. + internal const int RowChunk = 512; + + /// + /// Decodes the next row into (width × format.BytesPerPixel bytes) as + /// : the one row step of both the span decoder and the streaming reader, so their rows + /// are the same bytes. False when ends first; the reader is then partly advanced. + /// + /// Scratch of pixels. + internal static bool TryDecodeRow(ref QoiCodec.Reader reader, ReadOnlySpan data, Span row, int width, + PixelFormat format, Span chunk) + { + if (format == PixelFormat.Rgba32 || format == PixelFormat.Bgra32) + { + // RGBA pixels land in place; BGRA swaps them where they are. + if (!reader.TryRead(data, MemoryMarshal.Cast(row))) + return false; + if (format == PixelFormat.Bgra32) + PixelConverter.ConvertRow(row, PixelFormat.Rgba32, row, PixelFormat.Bgra32, width); + return true; + } + + var bpp = format.BytesPerPixel; + for (var x = 0; x < width; x += RowChunk) + { + var n = Math.Min(RowChunk, width - x); + if (!reader.TryRead(data, chunk[..n])) + return false; + PixelConverter.ConvertRow(MemoryMarshal.AsBytes(chunk[..n]), PixelFormat.Rgba32, row[(x * bpp)..], format, n); } + return true; } } diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiEncoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiEncoder.cs index 8ded604..07677ab 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiEncoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiEncoder.cs @@ -13,7 +13,7 @@ namespace Sdcb.SimdCodecs.Qoi; /// public static class QoiEncoder { - private const int Chunk = 512; + internal const int Chunk = 512; // A chunk of pixels writes at most 5 bytes each, plus a run left over from before it. private const int ChunkOutput = Chunk * 5 + 1; @@ -88,18 +88,39 @@ internal static void Encode(ReadOnlySpan pixels, int width, int height, Pi } private static int Validate(ReadOnlySpan pixels, int width, int height, PixelFormat format, QoiColorSpace colorSpace, int stride) + { + ValidateSize(width, height, colorSpace); + if (!PixelConverter.TryGetLayout(width, height, format, stride, pixels.Length, out var rowStride)) + throw new ArgumentException($"The pixels do not hold a {width}x{height} {format} image with stride {stride}.", nameof(pixels)); + return rowStride; + } + + internal static void ValidateSize(int width, int height, QoiColorSpace colorSpace) { if (width <= 0 || height <= 0 || (long)width * height > QoiCodec.MaximumPixels) throw new ArgumentException($"QOI size {width}x{height} must be positive and at most {QoiCodec.MaximumPixels:N0} pixels."); if (colorSpace is not (QoiColorSpace.Srgb or QoiColorSpace.Linear)) throw new ArgumentOutOfRangeException(nameof(colorSpace)); - if (!PixelConverter.TryGetLayout(width, height, format, stride, pixels.Length, out var rowStride)) - throw new ArgumentException($"The pixels do not hold a {width}x{height} {format} image with stride {stride}.", nameof(pixels)); - return rowStride; } private static void Write(ReadOnlySpan pixels, int width, int height, PixelFormat format, QoiColorSpace colorSpace, int rowStride, IBufferWriter output, CancellationToken cancellationToken = default) + { + WriteHeader(width, height, format, colorSpace, output); + Span rgba = stackalloc uint[Chunk]; + var state = new Writer(); + var rowBytes = width * format.BytesPerPixel; + for (var y = 0; y < height; y++) + { + if ((y & 63) == 0) + cancellationToken.ThrowIfCancellationRequested(); + WriteRow(ref state, pixels.Slice(y * rowStride, rowBytes), width, format, rgba, output); + } + WriteEnd(ref state, output); + } + + /// The 14-byte header: 4 channels when has alpha, else 3. + internal static void WriteHeader(int width, int height, PixelFormat format, QoiColorSpace colorSpace, IBufferWriter output) { var header = output.GetSpan(QoiCodec.HeaderSize); "qoif"u8.CopyTo(header); @@ -108,34 +129,39 @@ private static void Write(ReadOnlySpan pixels, int width, int height, Pixe header[12] = format.HasAlpha ? (byte)4 : (byte)3; header[13] = (byte)colorSpace; output.Advance(QoiCodec.HeaderSize); + } + /// + /// Encodes one row (width × format.BytesPerPixel bytes) with carried over from the + /// rows before it: the one row step of the whole-image encoder and the streaming session, so their bytes are the same. + /// + /// Scratch of pixels. + internal static void WriteRow(ref Writer state, ReadOnlySpan row, int width, PixelFormat format, Span rgba, + IBufferWriter output) + { // Every pixel goes to the encoder as straight 8-bit RGBA; RGBA32 input already is. var bpp = format.BytesPerPixel; - Span rgba = stackalloc uint[Chunk]; - var state = new Writer(); - for (var y = 0; y < height; y++) + for (var x = 0; x < width; x += Chunk) { - if ((y & 63) == 0) - cancellationToken.ThrowIfCancellationRequested(); - var row = pixels.Slice(y * rowStride, width * bpp); - for (var x = 0; x < width; x += Chunk) + var n = Math.Min(Chunk, width - x); + scoped ReadOnlySpan chunk; + if (format == PixelFormat.Rgba32) { - var n = Math.Min(Chunk, width - x); - scoped ReadOnlySpan chunk; - if (format == PixelFormat.Rgba32) - { - chunk = MemoryMarshal.Cast(row.Slice(x * 4, n * 4)); - } - else - { - PixelConverter.ConvertRow(row.Slice(x * bpp, n * bpp), format, MemoryMarshal.AsBytes(rgba), PixelFormat.Rgba32, n); - chunk = rgba[..n]; - } - var span = output.GetSpan(ChunkOutput); - output.Advance(state.Write(chunk, span)); + chunk = MemoryMarshal.Cast(row.Slice(x * 4, n * 4)); } + else + { + PixelConverter.ConvertRow(row.Slice(x * bpp, n * bpp), format, MemoryMarshal.AsBytes(rgba), PixelFormat.Rgba32, n); + chunk = rgba[..n]; + } + var span = output.GetSpan(ChunkOutput); + output.Advance(state.Write(chunk, span)); } + } + /// The open run, if any, then the 8-byte end marker. + internal static void WriteEnd(ref Writer state, IBufferWriter output) + { var end = output.GetSpan(1 + QoiCodec.PaddingSize); var written = state.Flush(end); end.Slice(written, QoiCodec.PaddingSize).Clear(); @@ -144,7 +170,7 @@ private static void Write(ReadOnlySpan pixels, int width, int height, Pixe } /// The encoder state between chunks of pixels: the previous pixel, the open run, the index. - private struct Writer + internal struct Writer { private uint _prev; private int _run; diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs index 3129c7e..07aacd5 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Diagnostics.CodeAnalysis; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -10,8 +11,12 @@ namespace Sdcb.SimdCodecs.Qoi; /// a linear transfer in . writes the /// caller's buffer directly. Malformed data makes the Try methods return false rather than throw. QOI carries /// no metadata and no thumbnail, and does not scale natively. +/// +/// decodes from a forward-only stream a row at a time, holding the decoder state and +/// the input of about one row; scaling, cropping or orientation options read the stream whole first. +/// /// -public sealed class QoiImageDecoder : IImageDecoder +public sealed class QoiImageDecoder : IStreamingImageDecoder { private static readonly ColorEncoding LinearSrgb = new() { Transfer = TransferFunction.Linear }; @@ -27,6 +32,7 @@ public sealed class QoiImageDecoder : IImageDecoder TryDecodeInto = TryDecodeInto, TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, + CreateRowReader = CreateRowReader, }; /// @@ -41,13 +47,7 @@ public static bool TryReadInfo(ReadOnlySpan data, out ImageInfo info) { try { - var qoi = QoiCodec.ReadHeader(data); - info = new ImageInfo(qoi.Width, qoi.Height, qoi.Channels, SampleFormat.UInt8) - { - Format = ImageFormat.Qoi, - BitDepth = 8, - ColorEncoding = ColorOf(qoi.ColorSpace), - }; + info = InfoOf(QoiCodec.ReadHeader(data)); return true; } catch (InvalidDataException) @@ -125,6 +125,96 @@ public static bool TryDecodeThumbnail(ReadOnlySpan data, [NotNullWhen(true public static bool TryDecodeIntoRgba8(ReadOnlySpan data, Span rgbaDestination) => TryDecodeInto(data, rgbaDestination, 0, PixelFormat.Rgba32); + /// + /// + /// The whole image at full size streams: a row is decoded once the input holds all of its chunks, so the reader + /// buffers about one row of the file. Any other read the stream to its end and decode + /// it with ( false). As for the span + /// decoder, the 8-byte end marker is not checked. + /// + public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + new RowReader(input, format, options); + + private static ImageInfo InfoOf(QoiInfo qoi) => new(qoi.Width, qoi.Height, qoi.Channels, SampleFormat.UInt8) + { + Format = ImageFormat.Qoi, + BitDepth = 8, + ColorEncoding = ColorOf(qoi.ColorSpace), + }; + private static ColorEncoding ColorOf(QoiColorSpace space) => space == QoiColorSpace.Linear ? LinearSrgb : ColorEncoding.AssumedSrgb; + + /// + /// The streaming reader. A row is the unit: runs on a copy of the decoder + /// state over the buffered input and the copy is kept only when the whole row decoded, so a row never splits + /// across calls and the destination of a failed attempt is simply written again. After a failed attempt the next + /// one waits for twice the bytes (capped at the 5 bytes a pixel a row can take at most), so a stream that arrives a + /// byte at a time costs a few decodes of each row, not one per byte. + /// + private sealed class RowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : StreamingRowReader(input, format) + { + private QoiCodec.Reader _reader; + private int _width; + private long _rowWorstBytes; // the most input one row's chunks take: 5 bytes a pixel + private int _retryAt; // after a failed row: the input length worth another attempt (0: any) + + protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed, + out ImageInfo info, out int width, out int height) + { + consumed = 0; + info = default; + width = height = 0; + if (input.Length < QoiCodec.HeaderSize) + { + if (!"qoif"u8.StartsWith(input[..Math.Min(input.Length, 4)])) + throw new InvalidDataException("Not a QOI image."); + return OperationStatus.NeedMoreData; + } + var qoi = QoiCodec.ReadHeader(input); + if ((long)qoi.Width * Format.BytesPerPixel > Array.MaxLength) + throw new InvalidDataException($"A {qoi.Width}-pixel {Format} row does not fit in one buffer."); + info = InfoOf(qoi); + if (!IsFullImage(options)) + { + UseBufferedFallback(TryDecodeInto, options); + (width, height) = options!.GetOutputSize(info); + return OperationStatus.Done; + } + _reader = new QoiCodec.Reader(qoi.Channels == 3); + _width = qoi.Width; + _rowWorstBytes = 5L * qoi.Width; + (width, height) = (qoi.Width, qoi.Height); + consumed = QoiCodec.HeaderSize; + return OperationStatus.Done; + } + + protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed, + Span destination, int stride, int rowCount, out int rowsWritten) + { + consumed = rowsWritten = 0; + if (!isFinal && input.Length < _retryAt) + return OperationStatus.NeedMoreData; + var rowBytes = _width * Format.BytesPerPixel; + Span chunk = stackalloc uint[QoiDecoder.RowChunk]; + var attempt = _reader; + while (rowsWritten < rowCount) + { + attempt.Position = consumed; + if (!QoiDecoder.TryDecodeRow(ref attempt, input, destination.Slice(rowsWritten * stride, rowBytes), _width, Format, chunk)) + { + // The bytes left end inside this row; they start the next call's input. Wait for twice as many, + // never for more than the row can need (with that many it cannot fail). + var left = input.Length - consumed; + _retryAt = (int)Math.Min(Math.Min(Math.Max(2L * left, 64), _rowWorstBytes), Array.MaxLength); + return OperationStatus.NeedMoreData; + } + _reader = attempt; + consumed = attempt.Position; + rowsWritten++; + _retryAt = 0; + } + return OperationStatus.Done; + } + } } diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiImageEncoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiImageEncoder.cs index 36ccf95..f209ff3 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageEncoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageEncoder.cs @@ -1,5 +1,4 @@ using System.Buffers; -using System.Collections.Generic; using System.Threading; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -12,8 +11,14 @@ namespace Sdcb.SimdCodecs.Qoi; /// and any without to . /// QOI has no options record: accepts null only. /// The colour space byte is written as when -/// has set to +/// the frame's colour encoding has set to /// , else . +/// +/// The session streams ( true): the header is written by +/// , each band of rows is encoded and written as it arrives, and the end +/// marker at . The bytes are those writes for the +/// whole image, however the rows are split into bands. +/// /// public sealed class QoiImageEncoder : IImageEncoder { @@ -40,16 +45,39 @@ options is null ? new Session(output) : throw new ArgumentException($"QOI encoding takes no options (pass null), not {options.GetType().Name}.", nameof(options)); - private sealed class Session(IBufferWriter output) : BufferedEncoderSession(output) + private sealed class Session(IBufferWriter output) : StreamingEncoderSession(output) { + // The encoder state between bands: previous pixel, open run, index. A run open at the end of one band goes on + // into the next, as it does between rows of a whole image. + private QoiEncoder.Writer _state; + private int _width; + private PixelFormat _format; + public override int MaxFrames => 1; - protected override void Encode(IReadOnlyList frames, CancellationToken cancellationToken) + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) { - cancellationToken.ThrowIfCancellationRequested(); - var frame = frames[0]; - var colorSpace = frame.Color?.Transfer == TransferFunction.Linear ? QoiColorSpace.Linear : QoiColorSpace.Srgb; - QoiEncoder.Encode(frame.Pixels, frame.Width, frame.Height, frame.Format, Output, colorSpace, 0, cancellationToken); + var colorSpace = color?.Transfer == TransferFunction.Linear ? QoiColorSpace.Linear : QoiColorSpace.Srgb; + QoiEncoder.ValidateSize(width, height, colorSpace); + _state = new QoiEncoder.Writer(); + _width = width; + _format = format; + QoiEncoder.WriteHeader(width, height, format, colorSpace, Output); } + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + Span rgba = stackalloc uint[QoiEncoder.Chunk]; + var rowBytes = _width * _format.BytesPerPixel; + for (var y = 0; y < rowCount; y++) + { + if ((y & 63) == 63) + cancellationToken.ThrowIfCancellationRequested(); + QoiEncoder.WriteRow(ref _state, rows.Slice(y * stride, rowBytes), _width, _format, rgba, Output); + } + } + + protected override void Finish(CancellationToken cancellationToken) => QoiEncoder.WriteEnd(ref _state, Output); } } diff --git a/src/Sdcb.SimdCodecs.Qoi/README.md b/src/Sdcb.SimdCodecs.Qoi/README.md index 747f489..c7f4c58 100644 --- a/src/Sdcb.SimdCodecs.Qoi/README.md +++ b/src/Sdcb.SimdCodecs.Qoi/README.md @@ -27,6 +27,20 @@ QoiEncoder.Encode(bgr, width, height, PixelFormat.Bgr24, file, QoiColorSpace.Lin The encoder takes RGBA, BGRA, RGB, BGR or grey input at any row stride. RGBA and BGRA input is written with 4 channels; the others are written with 3. For each pixel the encoder uses the first chunk that fits, trying them in this order: run, index, diff, luma, RGB, RGBA. +## Streaming + +`QoiImageDecoder.CreateRowReader` decodes from a forward-only stream (a network or request body that cannot seek), a band of rows at a time, top to bottom, synchronously (`ReadRows`) or asynchronously (`ReadRowsAsync`). It holds the decoder state and about one row of the file, and its rows are exactly those `TryDecodeInto` writes. A row is decoded once all of its chunks have arrived; a truncated stream throws `InvalidDataException`. Scaling, cropping or orientation options read the stream to its end and decode it whole (`IsStreaming` is false). + +```csharp +using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(requestBody), PixelFormat.Rgba32, null); +await reader.InitializeAsync(); +var band = new byte[reader.Width * 4 * 16]; +int rows; +while ((rows = await reader.ReadRowsAsync(band, 16)) > 0) + Consume(band, rows); +``` + +`QoiImageEncoder.Create` returns a streaming session: `AddFrame` writes the header, each `WriteRows` band is encoded and written to the output as it arrives (a run goes on across bands), and `Commit` writes the end marker. The bytes are those `QoiEncoder.Encode` writes for the whole image, however the rows are banded. ## Decisions The specification leaves these cases open. The table shows what this package does: diff --git a/tests/Sdcb.SimdCodecs.Tests/QoiStreamingRobustnessTests.cs b/tests/Sdcb.SimdCodecs.Tests/QoiStreamingRobustnessTests.cs new file mode 100644 index 0000000..7137166 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/QoiStreamingRobustnessTests.cs @@ -0,0 +1,168 @@ +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Qoi; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// Hostile input for the streaming QOI reader: random mutations of a set of seed files, fed in random pieces (sync and +/// async-only), either give exactly 's rows or fail with +/// exactly when it returns false, within seconds. QOI_STREAM_FUZZ_ITERATIONS +/// (default 500) and QOI_STREAM_FUZZ_SEED set the soak. +/// +public sealed class QoiStreamingRobustnessTests +{ + // Images up to this many pixels are decoded whole for the comparison; bigger headers are only read row by row. + private const long MaxComparedPixels = 1L << 20; + + private static int Iterations => + int.TryParse(Environment.GetEnvironmentVariable("QOI_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 500; + + private static int Seed => + int.TryParse(Environment.GetEnvironmentVariable("QOI_STREAM_FUZZ_SEED"), out var n) ? n : 20261123; + + private static List<(string Name, byte[] Data)> Seeds() + { + var rgba = QoiTests.Pattern(23, 9, alpha: true, seed: 4); + var flat = new byte[70 * 3 * 4]; + return + [ + ("rgba", QoiEncoder.Encode(rgba, 23, 9, PixelFormat.Rgba32)), + ("rgb", QoiEncoder.Encode([.. rgba.Where((_, i) => i % 4 != 3)], 23, 9, PixelFormat.Rgb24)), + ("flat", QoiEncoder.Encode(flat, 70, 3, PixelFormat.Rgba32)), + ("hand", QoiTests.HandStream().Stream), + ]; + } + + [Fact] + public async Task Mutations_stream_like_the_span_decoder_or_throw_invalid_data() + { + var seeds = Seeds(); + var iterations = Iterations; + var budget = TimeSpan.FromSeconds(Math.Max(60, iterations / 20)); + var current = ""; + var run = Task.Run(() => + { + var random = new Random(Seed); + for (var i = 0; i < iterations; i++) + { + var (name, seed) = seeds[random.Next(seeds.Count)]; + var data = Mutate(seed, random, out var description); + var format = QoiStreamingTests.Formats[random.Next(QoiStreamingTests.Formats.Length)]; + var feed = random.Next(3); + current = $"#{i} {name}: {description}, {format}, feed {feed}"; + StreamOne(data, format, feed, random.Next(), current); + } + }, TestContext.Current.CancellationToken); + if (await Task.WhenAny(run, Task.Delay(budget, TestContext.Current.CancellationToken)) != run) + throw new ShouldAssertException($"The streaming fuzz loop is stuck at {current}"); + await run; + } + + private static void StreamOne(byte[] data, PixelFormat format, int feed, int seed, string what) + { + byte[]? expected = null; + var spanOk = false; + var compared = QoiImageDecoder.TryReadInfo(data, out var info) && (long)info.Width * info.Height <= MaxComparedPixels; + if (compared) + { + expected = new byte[info.Width * info.Height * format.BytesPerPixel]; + spanOk = QoiImageDecoder.TryDecodeInto(data, expected, 0, format, null, TestContext.Current.CancellationToken); + } + + Stream stream = feed switch + { + 0 => new ChunkedStream(data, maxChunk: 1, seed), + 1 => new ChunkedStream(data, maxChunk: 64, seed), + _ => new ChunkedStream(data, maxChunk: 37, seed, asyncOnly: true), + }; + var async = feed == 2; + var random = new Random(seed); + byte[]? actual = null; + try + { + using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 16), format, null); + if (async) reader.InitializeAsync(TestContext.Current.CancellationToken).AsTask().GetAwaiter().GetResult(); + else reader.Initialize(TestContext.Current.CancellationToken); + var rowBytes = (long)reader.Width * format.BytesPerPixel; + if (!compared) + { + // A header too big to compare: read one row where a row fits a test buffer; it must fail, the data is short. + if (rowBytes <= 1 << 24) + { + var row = new byte[rowBytes]; + while (reader.RowsRead < reader.Height) + _ = async ? reader.ReadRowsAsync(row, 1, 0, TestContext.Current.CancellationToken).AsTask().GetAwaiter().GetResult() + : reader.ReadRows(row, 1, 0, TestContext.Current.CancellationToken); + } + return; + } + actual = new byte[rowBytes * reader.Height]; + while (reader.RowsRead < reader.Height) + { + var at = (int)(reader.RowsRead * rowBytes); + var band = random.Next(1, 6); + var n = async ? reader.ReadRowsAsync(actual.AsMemory(at), band, 0, TestContext.Current.CancellationToken).AsTask().GetAwaiter().GetResult() + : reader.ReadRows(actual.AsSpan(at), band, 0, TestContext.Current.CancellationToken); + n.ShouldBeGreaterThan(0, what); + } + } + catch (InvalidDataException) + { + spanOk.ShouldBeFalse($"{what}: the stream threw where the span decoder decoded"); + return; + } + if (compared) + { + spanOk.ShouldBeTrue($"{what}: the stream decoded where the span decoder failed"); + actual.ShouldBe(expected, what); + } + } + + // Half the mutations land in the header and first chunks. + private static byte[] Mutate(byte[] seed, Random random, out string description) + { + var data = seed.ToArray(); + var span = random.Next(2) == 0 ? Math.Min(24, data.Length) : data.Length; + var at = random.Next(Math.Max(1, span)); + switch (random.Next(6)) + { + case 0: + data[at] ^= (byte)(1 << random.Next(8)); + description = $"bit flip at {at}"; + return data; + case 1: + data[at] = (byte)random.Next(256); + description = $"byte {at} = {data[at]}"; + return data; + case 2: + { + var n = random.Next(2, 9); + for (var k = 0; k < n; k++) data[random.Next(data.Length)] ^= (byte)(1 << random.Next(8)); + description = $"{n} flips"; + return data; + } + case 3: + description = $"cut to {at}"; + return data[..at]; + case 4: + { + // A size byte: width or height. + var i = 4 + random.Next(8); + data[i] = (byte)random.Next(256); + description = $"size byte {i} = {data[i]}"; + return data; + } + default: + { + var n = random.Next(1, 16); + description = $"{n} random bytes inserted at {at}"; + var extra = new byte[n]; + random.NextBytes(extra); + return [.. data[..at], .. extra, .. data[at..]]; + } + } + } +} diff --git a/tests/Sdcb.SimdCodecs.Tests/QoiStreamingTests.cs b/tests/Sdcb.SimdCodecs.Tests/QoiStreamingTests.cs new file mode 100644 index 0000000..3afc03f --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/QoiStreamingTests.cs @@ -0,0 +1,330 @@ +using System.Buffers; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Qoi; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// QOI streaming: 's rows equal 's +/// under every feed and pixel format, a cut stream fails exactly where the span decoder fails, and +/// 's streaming session writes the whole-image encoder's bytes however the rows are banded, +/// handing them over before Commit, in bounded memory. +/// +public sealed class QoiStreamingTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ImageDecoderRegistration Codec => QoiImageDecoder.Registration; + + internal static readonly PixelFormat[] Formats = + [ + PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Bgr24, PixelFormat.Gray8, + PixelFormat.GrayAlpha16, PixelFormat.Rgba64, PixelFormat.Rgb48, PixelFormat.Gray16, PixelFormat.Rgba32Premultiplied, + ]; + + private static byte[] Rgb(byte[] rgba) => [.. rgba.Where((_, i) => i % 4 != 3)]; + + private static byte[] File(int width, int height, bool alpha, int seed) + { + var rgba = QoiTests.Pattern(width, height, alpha, seed); + return alpha ? QoiEncoder.Encode(rgba, width, height, PixelFormat.Rgba32) : QoiEncoder.Encode(Rgb(rgba), width, height, PixelFormat.Rgb24); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Rows_equal_decode_into_for_every_feed_and_format(bool alpha) + { + foreach (var width in new[] { 1, 2, 3, 7, 16, 33, 67, 600, 1100 }) + { + var height = width >= 600 ? 9 : 13; + var file = File(width, height, alpha, width * 7 + 1); + foreach (var format in Formats) + { + // One byte a read costs a few row decodes a byte; keep it to the narrow images. + StreamingAssert.RowsEqualDecodeInto(Codec, file, format, expectStreaming: true, + feeds: width <= 67 ? StreamingAssert.AllFeeds : [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly, StreamingAssert.Feed.Whole]); + } + } + } + + [Fact] + public void Foreign_and_hand_assembled_streams_stream() + { + StreamingAssert.RowsEqualDecodeInto(Codec, QoiTests.HandStream().Stream, PixelFormat.Rgba32, expectStreaming: true); + foreach (var alpha in new[] { true, false }) + { + const int w = 45, h = 11; + using var image = new MagickImage(); + image.ReadPixels(QoiTests.Pattern(w, h, alpha, 3), new PixelReadSettings(w, h, StorageType.Char, "RGBA")); + if (!alpha) image.Alpha(AlphaOption.Off); + var qoi = image.ToByteArray(MagickFormat.Qoi); + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Bgr24, PixelFormat.Rgba64 }) + StreamingAssert.RowsEqualDecodeInto(Codec, qoi, format, expectStreaming: true); + } + } + + [Fact] + public void Runs_across_rows_and_a_run_past_the_last_pixel_stream() + { + // A flat image is one run after another, each crossing row boundaries. + var flat = QoiEncoder.Encode(new byte[5 * 40 * 4], 5, 40, PixelFormat.Rgba32); + StreamingAssert.RowsEqualDecodeInto(Codec, flat, PixelFormat.Rgb24, expectStreaming: true); + + // 2x2 pixels, one run of 62 (the rest is ignored), no end marker: the span decoder reads it, so must the reader. + byte[] overrun = [.. QoiTests.Header(2, 2, 4), QoiCodec.OpRgba, 1, 2, 3, 4, QoiCodec.OpRun | 61]; + StreamingAssert.RowsEqualDecodeInto(Codec, overrun, PixelFormat.Rgba32, expectStreaming: true); + } + + [Fact] + public void Options_other_than_the_full_image_fall_back_with_the_same_rows() + { + var file = File(37, 21, true, 5); + foreach (var options in new[] + { + new DecodeOptions { ScaleDenominator = 2 }, + new DecodeOptions { Region = new PixelRect(3, 4, 20, 9) }, + new DecodeOptions { ApplyOrientation = true }, + }) + StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Bgra32, options, expectStreaming: false); + StreamingAssert.RowsEqualDecodeInto(Codec, file, PixelFormat.Bgra32, DecodeOptions.Default, expectStreaming: true); + } + + [Fact] + public void Every_cut_fails_where_the_span_decoder_fails() + { + foreach (var alpha in new[] { true, false }) + { + var file = File(9, 5, alpha, 11); + var expected = new byte[9 * 5 * 4]; + for (var cut = 0; cut <= file.Length; cut++) + { + var data = file[..cut]; + var spanOk = QoiImageDecoder.TryDecodeInto(data, expected, 0, PixelFormat.Rgba32, null, Ct); + foreach (var feed in new[] { StreamingAssert.Feed.OneByte, StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly }) + { + if (spanOk) + { + // A cut inside the end marker: the span decoder does not check it, nor does the reader. + StreamingAssert.ReadAll(data, feed, Create(PixelFormat.Rgba32), out _, out _, out _).ShouldBe(expected, $"{feed} cut at {cut}"); + } + else + { + Should.Throw(() => StreamingAssert.ReadAll(data, feed, Create(PixelFormat.Rgba32), out _, out _, out _), + $"{feed} cut at {cut}"); + } + } + } + } + } + + [Fact] + public void Malformed_headers_throw_invalid_data_before_any_row() + { + foreach (var bad in new[] + { + "qoix"u8.ToArray(), "QOIF0000000000"u8.ToArray(), QoiTests.Header(0, 4, 4), QoiTests.Header(4, 4, 5), + QoiTests.Header(4, 4, 4, colorSpace: 2), QoiTests.Header(1 << 15, 1 << 15, 4), + }) + { + using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(bad, maxChunk: 2)), PixelFormat.Rgba32, null); + Should.Throw(() => reader.Initialize(Ct)); + } + } + + [Fact] + public void Reads_the_stream_only_as_far_as_the_rows_need() + { + const int w = 512, h = 512; + var file = File(w, h, true, 9); + var stream = new ChunkedStream(file, maxChunk: 1024); + using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 4096), PixelFormat.Rgba32, null); + var rows = new byte[w * 4 * 4]; + reader.ReadRows(rows, 4, 0, Ct).ShouldBe(4); + reader.IsStreaming.ShouldBeTrue(); + stream.BytesRead.ShouldBeLessThan(file.Length / 8, "a streaming reader reads ahead about a row"); + var expected = new byte[w * h * 4]; + QoiImageDecoder.TryDecodeInto(file, expected, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + rows.ShouldBe(expected.AsSpan(0, rows.Length).ToArray()); + } + + [Fact] + public void Streaming_encode_bytes_equal_the_whole_image_encoder_for_any_banding() + { + var random = new Random(17); + foreach (var (width, height) in new[] { (1, 200), (3, 70), (61, 9), (600, 7), (1100, 3) }) + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Gray8, PixelFormat.Rgba64 }) + foreach (var linear in new[] { false, true }) + { + var rgba = QoiTests.Pattern(width, height, format.HasAlpha, width + height); + var pixels = PixelConverter.ToPacked(rgba, 0, PixelFormat.Rgba32, format, width, height).ToArray(); + var colorSpace = linear ? QoiColorSpace.Linear : QoiColorSpace.Srgb; + var expected = QoiEncoder.Encode(pixels, width, height, format, colorSpace); + var rowBytes = width * format.BytesPerPixel; + for (var trial = 0; trial < 6; trial++) + { + // Bands of random height at a random stride (trial 0: one row at a time; trial 1: all at once). + var output = new ArrayBufferWriter(trial == 2 ? 1 : 256); + using var session = QoiImageEncoder.Create(output); + session.IsStreaming.ShouldBeTrue(); + var frame = session.AddFrame(width, height, format, linear ? new ColorEncoding { Transfer = TransferFunction.Linear } : null); + var y = 0; + while (y < height) + { + var band = trial switch { 0 => 1, 1 => height, _ => Math.Min(height - y, random.Next(1, 9)) }; + var stride = rowBytes + (trial >= 3 ? random.Next(0, 9) : 0); + var buffer = new byte[stride * band]; + for (var k = 0; k < band; k++) + pixels.AsSpan((y + k) * rowBytes, rowBytes).CopyTo(buffer.AsSpan(k * stride)); + frame.WriteRows(buffer, band, stride, Ct); + y += band; + } + session.Commit(Ct); + output.WrittenSpan.ToArray().ShouldBe(expected, $"{width}x{height} {format} linear {linear} trial {trial}"); + } + } + } + + [Fact] + public void Encoder_emits_before_commit_and_decodes_back() + { + const int w = 300, h = 40; + var rgba = QoiTests.Pattern(w, h, true, 2); + var file = StreamingAssert.EncoderEmitsBeforeCommit(output => QoiImageEncoder.Create(output), rgba, w, h, PixelFormat.Rgba32); + file.ShouldBe(QoiEncoder.Encode(rgba, w, h, PixelFormat.Rgba32)); + QoiDecoder.Decode(file).Pixels.ShouldBe(rgba); + } + + [Fact] + public void Encoder_session_refuses_what_qoi_cannot_store() + { + using var session = QoiImageEncoder.Create(new ArrayBufferWriter()); + Should.Throw(() => session.AddFrame(1 << 15, 1 << 14, PixelFormat.Rgb24)); + var frame = session.AddFrame(2, 1, PixelFormat.Rgb24); + frame.WriteRows(new byte[6], 1, 0, Ct); + Should.Throw(() => session.AddFrame(2, 1, PixelFormat.Rgb24)); + session.Commit(Ct); + } + + [Fact] + public void Decode_and_encode_of_a_large_image_stay_in_bounded_memory() + { + const int w = 8192, h = 4096; + // Rows that change from one to the next (diffs, lumas, index hits, runs), made a band at a time. + const int band = 16; + var rows = new byte[w * 4 * band]; + void Fill(int y0) + { + for (var k = 0; k < band; k++) + for (var x = 0; x < w; x++) + { + var i = (k * w + x) * 4; + var y = y0 + k; + rows[i] = (byte)(x >> 3); rows[i + 1] = (byte)y; rows[i + 2] = (byte)((x ^ y) >> 5); rows[i + 3] = (byte)(x < 64 ? x * 4 : 255); + } + } + + var sink = new CountingWriter(); + void Encode() + { + sink.Reset(); + using var session = QoiImageEncoder.Create(sink); + var frame = session.AddFrame(w, h, PixelFormat.Rgba32); + for (var y = 0; y < h; y += band) + { + Fill(y); + frame.WriteRows(rows, band, 0, Ct); + } + session.Commit(Ct); + } + StreamingAssert.AllocatesLessThan(1 << 20, Encode, "a streaming encode of a 128 MiB image"); + + var file = new ArrayBufferWriter(1 << 20); + using (var session = QoiImageEncoder.Create(file)) + { + var frame = session.AddFrame(w, h, PixelFormat.Rgba32); + for (var y = 0; y < h; y += band) + { + Fill(y); + frame.WriteRows(rows, band, 0, Ct); + } + session.Commit(Ct); + } + sink.Count.ShouldBe(file.WrittenCount); + var bytes = file.WrittenSpan.ToArray(); + + var row = new byte[w * 3]; + StreamingAssert.AllocatesLessThan(1 << 20, () => + { + using var reader = QoiImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(bytes, maxChunk: 1 << 16)), PixelFormat.Rgb24, null); + var y = 0; + while (reader.ReadRows(row, 1, 0, Ct) > 0) + { + if ((y & 1023) == 7) + { + // Spot-check a row against the source. + Fill(y & ~(band - 1)); + var k = y & (band - 1); + for (var x = 0; x < w; x += 997) + (row[x * 3], row[x * 3 + 1], row[x * 3 + 2]).ShouldBe((rows[(k * w + x) * 4], rows[(k * w + x) * 4 + 1], rows[(k * w + x) * 4 + 2])); + } + y++; + } + y.ShouldBe(h); + }, "a streaming decode of a 128 MiB image"); + } + + [Fact] + public async Task Async_only_stream_pipes_into_the_streaming_encoder() + { + foreach (var alpha in new[] { true, false }) + { + const int w = 333, h = 77; + var file = File(w, h, alpha, 23); + var format = alpha ? PixelFormat.Rgba32 : PixelFormat.Rgb24; + var output = new ArrayBufferWriter(); + await using (var reader = QoiImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(file, maxChunk: 997, seed: 5, asyncOnly: true), initialCapacity: 16), format, null)) + { + await reader.InitializeAsync(Ct); + reader.IsStreaming.ShouldBeTrue(); + using var session = QoiImageEncoder.Create(output); + var frame = session.AddFrame(reader.Width, reader.Height, format, reader.Info.ColorEncoding); + var band = new byte[w * format.BytesPerPixel * 10]; + var random = new Random(3); + int n; + while ((n = await reader.ReadRowsAsync(band, random.Next(1, 11), 0, Ct)) > 0) + frame.WriteRows(band, n, 0, Ct); + session.Commit(Ct); + } + output.WrittenSpan.ToArray().ShouldBe(file, "our encoder's file comes back byte for byte"); + var expected = new byte[w * h * 4]; + var actual = new byte[w * h * 4]; + QoiImageDecoder.TryDecodeInto(file, expected, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + QoiImageDecoder.TryDecodeInto(output.WrittenSpan, actual, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + actual.ShouldBe(expected); + } + } + + private static Func Create(PixelFormat format) => + input => QoiImageDecoder.CreateRowReader(input, format, null); + + /// A writer that keeps nothing: one reused buffer, the bytes counted. + private sealed class CountingWriter : IBufferWriter + { + private readonly byte[] _buffer = new byte[1 << 16]; + + public long Count { get; private set; } + + public void Reset() => Count = 0; + + public void Advance(int count) => Count += count; + + public Memory GetMemory(int sizeHint = 0) => _buffer; + + public Span GetSpan(int sizeHint = 0) => _buffer; + } +} From aa84f3ccd838f38e3e2432d6058ec0c9c2227e8a Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:21:26 +0800 Subject: [PATCH 2/6] QoiPnm benchmark: bind the baseline's six-parameter TryDecodeInto The 2.0 TryDecodeInto takes options and a token; the four-parameter lookup found nothing, so decode had no baseline column. Co-Authored-By: Claude Opus 5.5 --- .../Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs index bcfe699..e44f211 100644 --- a/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs +++ b/benchmarks/Sdcb.SimdCodecs.QoiPnm.Benchmarks/Baseline.cs @@ -36,10 +36,10 @@ private sealed class Bound public static bool CanEncode(bool qoi) => IsBuilt && (qoi ? Loaded.Value.QoiEncode : Loaded.Value.PnmEncode) != IntPtr.Zero; - /// The baseline's QoiImageDecoder / PnmImageDecoder.TryDecodeInto, to RGBA. + /// The baseline's QoiImageDecoder / PnmImageDecoder.TryDecodeInto (the 2.0 six-parameter form), to RGBA. public static bool TryDecodeInto(bool qoi, ReadOnlySpan data, Span rgba) => - ((delegate*, Span, int, PixelFormat, bool>)(qoi ? Loaded.Value.QoiDecodeInto : Loaded.Value.PnmDecodeInto))( - data, rgba, 0, PixelFormat.Rgba32); + ((delegate*, Span, int, PixelFormat, DecodeOptions?, CancellationToken, bool>)(qoi ? Loaded.Value.QoiDecodeInto : Loaded.Value.PnmDecodeInto))( + data, rgba, 0, PixelFormat.Rgba32, null, default); /// The baseline's QoiEncoder.Encode(pixels, width, height, format, Srgb, 0). public static byte[] EncodeQoi(byte[] pixels, int width, int height, PixelFormat format) => @@ -72,7 +72,7 @@ private static Bound Load() if (File.Exists(Path.Combine(dir, "Sdcb.SimdCodecs.Qoi.dll"))) { var qoi = alc.LoadFromAssemblyName(new AssemblyName("Sdcb.SimdCodecs.Qoi")); - bound.QoiDecodeInto = Pointer(qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiImageDecoder"), "TryDecodeInto", 4); + bound.QoiDecodeInto = Pointer(qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiImageDecoder"), "TryDecodeInto", 6); bound.QoiEncode = qoi.GetType("Sdcb.SimdCodecs.Qoi.QoiEncoder")?.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(m => m.Name == "Encode" && m.GetParameters() is { Length: 6 } p && p[4].ParameterType.Name == "QoiColorSpace") ?.MethodHandle.GetFunctionPointer() ?? IntPtr.Zero; @@ -80,7 +80,7 @@ private static Bound Load() if (File.Exists(Path.Combine(dir, "Sdcb.SimdCodecs.Pnm.dll"))) { var pnm = alc.LoadFromAssemblyName(new AssemblyName("Sdcb.SimdCodecs.Pnm")); - bound.PnmDecodeInto = Pointer(pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmImageDecoder"), "TryDecodeInto", 4); + bound.PnmDecodeInto = Pointer(pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmImageDecoder"), "TryDecodeInto", 6); bound.PnmOptionsType = pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmEncodeOptions"); bound.PnmEncode = pnm.GetType("Sdcb.SimdCodecs.Pnm.PnmEncoder")?.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(m => m.Name == "Encode" && m.GetParameters() is { Length: 6 } p && p[3].ParameterType.Name == nameof(PixelFormat) && p[4].ParameterType.Name == "PnmEncodeOptions") From eed6111bc6c28f37897a4e50915f709cee76f179 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:24:58 +0800 Subject: [PATCH 3/6] QOI: keep the whole-image reader's end checks as throw blocks TryRead and Read share one loop instantiated over a struct marker; returning false from the end checks in the shared loop cost the span decode about 8%. Co-Authored-By: Claude Opus 5.5 --- src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs index 98f9382..fb719d3 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs @@ -94,19 +94,19 @@ public int Position /// Decodes the next pixels.Length pixels. /// The chunks end first. - public void Read(ReadOnlySpan data, Span pixels) - { - if (!TryRead(data, pixels)) - throw new InvalidDataException("QOI data ends before the last pixel."); - } + public void Read(ReadOnlySpan data, Span pixels) => Read(data, pixels); /// /// Decodes the next pixels.Length pixels; false when the chunks end first (a chunk would run past the /// data). Every byte is a valid chunk opcode, so running out is the only way to fail. After false the state is /// partly advanced: a caller that retries with more data restores a copy taken before the call. /// + public bool TryRead(ReadOnlySpan data, Span pixels) => Read(data, pixels); + + // One loop, two instantiations over a struct marker: the typeof test is a constant in each (also under Mono AOT), so the throwing one keeps its end checks as + // cold throw blocks (returning false from them instead costs the whole-image decode about 8%). [MethodImpl(MethodImplOptions.AggressiveOptimization)] - public bool TryRead(ReadOnlySpan data, Span pixels) + private bool Read(ReadOnlySpan data, Span pixels) where TEnd : struct { var n = pixels.Length; var i = 0; @@ -143,7 +143,11 @@ public bool TryRead(ReadOnlySpan data, Span pixels) { var remaining = tailBase < 0 ? data.Length - p : 0; if (remaining <= 0) + { + if (typeof(TEnd) == typeof(ThrowAtEnd)) + throw new InvalidDataException("QOI data ends before the last pixel."); return false; + } tail.Clear(); data[p..].CopyTo(tail); tailBase = p; @@ -210,7 +214,11 @@ public bool TryRead(ReadOnlySpan data, Span pixels) if (tailBase >= 0) { if (p > limit + 1) + { + if (typeof(TEnd) == typeof(ThrowAtEnd)) + throw new InvalidDataException("QOI data ends inside the last chunk."); return false; + } p += tailBase; } _position = p; @@ -241,6 +249,11 @@ private static uint SubBytes(uint a, uint b) } } + /// Markers for what does when the chunks end before the pixels asked for. + internal struct ThrowAtEnd; + + internal struct ReturnAtEnd; + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ReadUInt32(ref byte source) { From b7aba2e81f9e8040e643376226d3f95cf246db07 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:30:01 +0800 Subject: [PATCH 4/6] QOI: whole-image reader loop returns void again; streaming reads ahead two rows The throwing instantiation is the pre-streaming loop; TryRead marks running out with position -1. The row reader asks for more input while fewer than twice the previous row's bytes are buffered, so it seldom decodes a partial row twice. Co-Authored-By: Claude Opus 5.5 --- src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs | 23 ++++++++++++++-------- src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs | 10 ++++++++-- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs index fb719d3..1cff0d5 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs @@ -101,12 +101,18 @@ public int Position /// data). Every byte is a valid chunk opcode, so running out is the only way to fail. After false the state is /// partly advanced: a caller that retries with more data restores a copy taken before the call. /// - public bool TryRead(ReadOnlySpan data, Span pixels) => Read(data, pixels); + public bool TryRead(ReadOnlySpan data, Span pixels) + { + Read(data, pixels); + return _position >= 0; + } - // One loop, two instantiations over a struct marker: the typeof test is a constant in each (also under Mono AOT), so the throwing one keeps its end checks as - // cold throw blocks (returning false from them instead costs the whole-image decode about 8%). + // One loop, two instantiations over a struct marker; the typeof test is a constant in each (also under Mono AOT). + // The throwing one is the loop as it was before streaming: its end checks are cold throw blocks and it returns + // nothing. (A shared loop returning bool cost the whole-image decode 4-8%, measured.) The other marks running + // out with a position of -1: the state is discarded after a failed read anyway. [MethodImpl(MethodImplOptions.AggressiveOptimization)] - private bool Read(ReadOnlySpan data, Span pixels) where TEnd : struct + private void Read(ReadOnlySpan data, Span pixels) where TEnd : struct { var n = pixels.Length; var i = 0; @@ -121,7 +127,7 @@ private bool Read(ReadOnlySpan data, Span pixels) where TEnd : if (i == n) { _run = run; - return true; + return; } // Every chunk is at most 5 bytes. While p <= limit = length − 5 a chunk read from p stays inside data. @@ -146,7 +152,8 @@ private bool Read(ReadOnlySpan data, Span pixels) where TEnd : { if (typeof(TEnd) == typeof(ThrowAtEnd)) throw new InvalidDataException("QOI data ends before the last pixel."); - return false; + _position = -1; + return; } tail.Clear(); data[p..].CopyTo(tail); @@ -217,14 +224,14 @@ private bool Read(ReadOnlySpan data, Span pixels) where TEnd : { if (typeof(TEnd) == typeof(ThrowAtEnd)) throw new InvalidDataException("QOI data ends inside the last chunk."); - return false; + _position = -1; + return; } p += tailBase; } _position = p; _run = run; _px = px; - return true; } /// diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs index 07aacd5..c31911b 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs @@ -150,7 +150,9 @@ private static ColorEncoding ColorOf(QoiColorSpace space) => /// state over the buffered input and the copy is kept only when the whole row decoded, so a row never splits /// across calls and the destination of a failed attempt is simply written again. After a failed attempt the next /// one waits for twice the bytes (capped at the 5 bytes a pixel a row can take at most), so a stream that arrives a - /// byte at a time costs a few decodes of each row, not one per byte. + /// byte at a time costs a few decodes of each row, not one per byte. Before a row it asks for more input while the + /// bytes buffered are fewer than twice what the previous row took, so a partial row is seldom decoded only to be + /// decoded again. /// private sealed class RowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : StreamingRowReader(input, format) { @@ -158,6 +160,7 @@ private sealed class RowReader(StreamInput input, PixelFormat format, DecodeOpti private int _width; private long _rowWorstBytes; // the most input one row's chunks take: 5 bytes a pixel private int _retryAt; // after a failed row: the input length worth another attempt (0: any) + private int _lastRowBytes; // the input the previous row took protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed, out ImageInfo info, out int width, out int height) @@ -200,16 +203,19 @@ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isF var attempt = _reader; while (rowsWritten < rowCount) { + var left = input.Length - consumed; + if (!isFinal && left < Math.Min(2L * _lastRowBytes + 16, _rowWorstBytes)) + return OperationStatus.NeedMoreData; attempt.Position = consumed; if (!QoiDecoder.TryDecodeRow(ref attempt, input, destination.Slice(rowsWritten * stride, rowBytes), _width, Format, chunk)) { // The bytes left end inside this row; they start the next call's input. Wait for twice as many, // never for more than the row can need (with that many it cannot fail). - var left = input.Length - consumed; _retryAt = (int)Math.Min(Math.Min(Math.Max(2L * left, 64), _rowWorstBytes), Array.MaxLength); return OperationStatus.NeedMoreData; } _reader = attempt; + _lastRowBytes = attempt.Position - consumed; consumed = attempt.Position; rowsWritten++; _retryAt = 0; From 2a96174a06687b541552005c174e7bba89b7def7 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:32:56 +0800 Subject: [PATCH 5/6] QOI streaming: decode tightly packed RGBA / BGRA rows in batches Co-Authored-By: Claude Opus 5.5 --- src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs index c31911b..e9d1d99 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -201,12 +202,35 @@ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isF var rowBytes = _width * Format.BytesPerPixel; Span chunk = stackalloc uint[QoiDecoder.RowChunk]; var attempt = _reader; + // Tightly packed RGBA or BGRA rows decode as one run of pixels, as many rows a call as half the buffered + // bytes hold at the previous rows' rate: a call per row costs the decode several percent. + var batch = stride == rowBytes && (Format == PixelFormat.Rgba32 || Format == PixelFormat.Bgra32); while (rowsWritten < rowCount) { var left = input.Length - consumed; if (!isFinal && left < Math.Min(2L * _lastRowBytes + 16, _rowWorstBytes)) return OperationStatus.NeedMoreData; attempt.Position = consumed; + var k = batch && _lastRowBytes > 0 ? (int)Math.Min(rowCount - rowsWritten, left / (2L * _lastRowBytes)) : 1; + if (k > 1) + { + var band = destination.Slice(rowsWritten * stride, k * rowBytes); + if (attempt.TryRead(input, MemoryMarshal.Cast(band))) + { + if (Format == PixelFormat.Bgra32) + PixelConverter.ConvertRow(band, PixelFormat.Rgba32, band, PixelFormat.Bgra32, k * _width); + _reader = attempt; + _lastRowBytes = Math.Max(1, (attempt.Position - consumed) / k); + consumed = attempt.Position; + rowsWritten += k; + _retryAt = 0; + continue; + } + // The rows were denser than the ones before: go on a row at a time. + attempt = _reader; + attempt.Position = consumed; + batch = false; + } if (!QoiDecoder.TryDecodeRow(ref attempt, input, destination.Slice(rowsWritten * stride, rowBytes), _width, Format, chunk)) { // The bytes left end inside this row; they start the next call's input. Wait for twice as many, From daca39ceb2a9e89559d8486ad0785608174551b1 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:35:46 +0800 Subject: [PATCH 6/6] QOI streaming: batch only the rows the buffered bytes are sure to hold Co-Authored-By: Claude Opus 5.5 --- src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs index e9d1d99..127f813 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs @@ -202,8 +202,10 @@ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isF var rowBytes = _width * Format.BytesPerPixel; Span chunk = stackalloc uint[QoiDecoder.RowChunk]; var attempt = _reader; - // Tightly packed RGBA or BGRA rows decode as one run of pixels, as many rows a call as half the buffered - // bytes hold at the previous rows' rate: a call per row costs the decode several percent. + // Tightly packed RGBA or BGRA rows decode as one run of pixels, as many rows a call as the buffered bytes + // hold at 5 bytes a pixel, the most a row can take: such a batch cannot run out, so no work is thrown + // away. (A call per row costs the decode several percent; a batch guessed from the previous rows' rate + // that ran out threw away up to a buffer's worth of decoding.) var batch = stride == rowBytes && (Format == PixelFormat.Rgba32 || Format == PixelFormat.Bgra32); while (rowsWritten < rowCount) { @@ -211,7 +213,7 @@ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isF if (!isFinal && left < Math.Min(2L * _lastRowBytes + 16, _rowWorstBytes)) return OperationStatus.NeedMoreData; attempt.Position = consumed; - var k = batch && _lastRowBytes > 0 ? (int)Math.Min(rowCount - rowsWritten, left / (2L * _lastRowBytes)) : 1; + var k = batch ? (int)Math.Min(rowCount - rowsWritten, left / _rowWorstBytes) : 1; if (k > 1) { var band = destination.Slice(rowsWritten * stride, k * rowBytes); @@ -226,7 +228,7 @@ protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isF _retryAt = 0; continue; } - // The rows were denser than the ones before: go on a row at a time. + // Not reached (k rows fit in the bytes left); should it be, go on a row at a time. attempt = _reader; attempt.Position = consumed; batch = false;