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") 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..1cff0d5 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiCodec.cs @@ -82,10 +82,37 @@ 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. + 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); + return _position >= 0; + } + + // 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)] - public void Read(ReadOnlySpan data, Span pixels) + private void Read(ReadOnlySpan data, Span pixels) where TEnd : struct { var n = pixels.Length; var i = 0; @@ -122,7 +149,12 @@ 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."); + { + if (typeof(TEnd) == typeof(ThrowAtEnd)) + throw new InvalidDataException("QOI data ends before the last pixel."); + _position = -1; + return; + } tail.Clear(); data[p..].CopyTo(tail); tailBase = p; @@ -189,7 +221,12 @@ public void Read(ReadOnlySpan data, Span pixels) if (tailBase >= 0) { if (p > limit + 1) - throw new InvalidDataException("QOI data ends inside the last chunk."); + { + if (typeof(TEnd) == typeof(ThrowAtEnd)) + throw new InvalidDataException("QOI data ends inside the last chunk."); + _position = -1; + return; + } p += tailBase; } _position = p; @@ -219,6 +256,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) { 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..127f813 100644 --- a/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Qoi/QoiImageDecoder.cs @@ -1,4 +1,6 @@ +using System.Buffers; using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -10,8 +12,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 +33,7 @@ public sealed class QoiImageDecoder : IImageDecoder TryDecodeInto = TryDecodeInto, TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, + CreateRowReader = CreateRowReader, }; /// @@ -41,13 +48,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 +126,127 @@ 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. 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) + { + 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) + 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) + { + 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; + // 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) + { + var left = input.Length - consumed; + if (!isFinal && left < Math.Min(2L * _lastRowBytes + 16, _rowWorstBytes)) + return OperationStatus.NeedMoreData; + attempt.Position = consumed; + var k = batch ? (int)Math.Min(rowCount - rowsWritten, left / _rowWorstBytes) : 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; + } + // 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; + } + 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). + _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; + } + 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; + } +}