From c82c45e1a7b058f3ecc4c9983910241740a97d77 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 19:53:26 +0800 Subject: [PATCH] Png: streaming row reader (forward-only stream, bounded memory) PngImageDecoder implements IStreamingImageDecoder and registers CreateRowReader; OpenRowReader / OpenRowReaderAsync open a reader over any readable stream. A non-interlaced, non-animated PNG decodes as it arrives: the chunks before the first IDAT are read as ReadHeader reads them (now through a shared HeaderBuilder), then one ZLibStream inflates the IDAT payloads straight out of the StreamInput window. The walker checks each chunk's CRC as it ends and reads the chunks between and after the IDATs to IEND (or EOF at a chunk boundary) exactly as the span decode does; chunks it skips are passed over without being held. When the window runs dry inside a row the walker throws a private exception that unwinds the inflater without losing state (returning 0 would read as end of data, and fails under UseStrictValidation); retries back off by doubling. Rows are unfiltered and converted as DecodeInto (basic 8-bit formats) or DecodeWindow (the rest) does, so they equal TryDecodeInto byte for byte; the last row is held until the rest of the file is checked. Fallback (IsStreaming false, TryDecodeInto's result): Adam7, acTL, an indexed file with PLTE after IDAT, PQ/HLG cICP read to 8-bit samples, non-full options. A PLTE, tRNS (alpha formats) or PQ/HLG cICP (8-bit) after IDAT that would change rows already written fails with InvalidDataException (LateChunkMessage). DeflateInflate (iCCP, zTXt, iTXt) now turns zlib's IOException into InvalidDataException. The benchmark gains a Streaming decode contestant. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- README.zh-CN.md | 2 +- .../Contestants.cs | 48 ++ .../Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs | 29 +- .../PngBenchmarks.cs | 8 +- .../Sdcb.SimdCodecs.Png.Benchmarks/README.md | 1 + src/Sdcb.SimdCodecs.Png/PngImageDecoder.cs | 85 +- .../PngReader.Streaming.cs | 653 ++++++++++++++++ src/Sdcb.SimdCodecs.Png/PngReader.cs | 260 ++++--- .../PublicAPI.Unshipped.txt | 3 + .../PngStreamingDecodeTests.cs | 729 ++++++++++++++++++ 11 files changed, 1717 insertions(+), 103 deletions(-) create mode 100644 src/Sdcb.SimdCodecs.Png/PngReader.Streaming.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/PngStreamingDecodeTests.cs diff --git a/README.md b/README.md index ae4e09e..b324554 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ Upgrading from 1.x: [docs/migrating-to-2.0.md](docs/migrating-to-2.0.md). Feature details per package - **Jpeg**: T.81 decoder: baseline, progressive, restart intervals, any subsampling, grey / YCbCr / RGB / CMYK / YCCK, scaled 1/2–1/8 decode, lossless (SOF3, through `LosslessJpeg.FromMemory`). SIMD encoder: baseline, optimised Huffman or progressive; 4:4:4 / 4:2:0 / grey; restart intervals; embeds EXIF (APP1), XMP and an ICC profile (APP2). -- **Png**: every standard bit depth (including 1/2/4-bit grey and indexed), tEXt / zTXt / iTXt text chunks, PNG-3 cICP / mDCV / cLLI HDR signalling. `PngWriteOptions.Quantize` reduces an image to at most 256 colours, translucency included, the way pngquant does: smaller than pngquant's file at equal SSIM on the benchmark corpus (`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`). APNG: `PngAnimationDecoder` composites every dispose / blend operation and seeks; `PngAnimationEncoder` writes changed rectangles, merging unchanged frames. +- **Png**: every standard bit depth (including 1/2/4-bit grey and indexed), tEXt / zTXt / iTXt text chunks, PNG-3 cICP / mDCV / cLLI HDR signalling. `PngWriteOptions.Quantize` reduces an image to at most 256 colours, translucency included, the way pngquant does: smaller than pngquant's file at equal SSIM on the benchmark corpus (`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`). APNG: `PngAnimationDecoder` composites every dispose / blend operation and seeks; `PngAnimationEncoder` writes changed rectangles, merging unchanged frames. `PngImageDecoder.OpenRowReader(stream)` / `OpenRowReaderAsync` decode from a forward-only stream (an upload, a socket) a band of rows at a time, holding a few rows whatever the height, with exactly `TryDecodeInto`'s rows; interlaced and animated files are read whole first behind the same API (`IsStreaming` false). - **Tiff**: multi-page, classic and BigTIFF; 8/16/32-bit integer and float; Deflate / LZW (+ PackBits and JPEG read, with JPEGTables); strips or tiles; chunky or planar; on-demand single strip or tile reads, and a region decode that reads only the segments it touches; reads 1/2/4-bit pages (expanded to 8-bit), CCITT fax (Group 3 1D/2D, Group 4, Modified Huffman) and the floating-point predictor; the facade presents palette, CMYK and YCbCr pages as RGB and extra samples as alpha. Writes Deflate. - **Webp**: RFC 6386 / RFC 9649: VP8 lossy, VP8L lossless, ALPH, animation with seek, ICC / EXIF / XMP. `WebpAnimationDecoder` adds seeking by timestamp and the frame rectangles. `WebpEncoder.EncodeLossless` writes VP8L stills with alpha, effort 0–9; `WebpEncoder.EncodeLossy` writes VP8 stills, quality 0–100 and effort 0–6, with transparency in an ALPH plane; both can embed ICC / Exif / XMP. `WebpAnimationEncoder` and `WebpEncoder.EncodeAnimation` write animations, lossy, lossless or the smaller per frame, from whole canvases (reduced to the changed rectangle, unchanged frames merged) or from ANMF frames as given. - **Gif**: GIF89a: global / local colour tables, interlacing, transparency, all disposal methods, NETSCAPE2.0 loop count; composited frames with seek. Encoder: stills and animations, exact palettes or perceptual quantization (OKLab box split + k-means) with optional edge-aware Floyd–Steinberg dithering, changed-rectangle frames for opaque animations. The decisions the spec leaves open are listed in the package README. diff --git a/README.zh-CN.md b/README.zh-CN.md index f2a1bd7..eb24dd1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -105,7 +105,7 @@ ImageCodecs.Register(HeifImageDecoder.Registration); 各包的详细特性 - **Jpeg**:T.81 解码器,支持 baseline、progressive、restart interval、任意采样方式,灰度 / YCbCr / RGB / CMYK / YCCK,1/2–1/8 缩放解码,无损(SOF3,经由 `LosslessJpeg.FromMemory`)。SIMD 编码器支持 baseline、优化 Huffman 或 progressive;4:4:4 / 4:2:0 / 灰度;restart interval;可写入 EXIF(APP1)、XMP 和 ICC 配置文件(APP2)。 -- **Png**:所有标准位深(包括 1/2/4 位灰度和调色板),tEXt / zTXt / iTXt 文本块,PNG-3 的 cICP / mDCV / cLLI HDR 标记。`PngWriteOptions.Quantize` 像 pngquant 一样把图片降到最多 256 色(含半透明):在基准语料上,同等 SSIM 下文件比 pngquant 的小(`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`)。APNG:`PngAnimationDecoder` 支持所有 dispose / blend 操作并可跳帧;`PngAnimationEncoder` 只写变化矩形,并合并不变的帧。 +- **Png**:所有标准位深(包括 1/2/4 位灰度和调色板),tEXt / zTXt / iTXt 文本块,PNG-3 的 cICP / mDCV / cLLI HDR 标记。`PngWriteOptions.Quantize` 像 pngquant 一样把图片降到最多 256 色(含半透明):在基准语料上,同等 SSIM 下文件比 pngquant 的小(`benchmarks/Sdcb.SimdCodecs.Quantize.Benchmarks`)。APNG:`PngAnimationDecoder` 支持所有 dispose / blend 操作并可跳帧;`PngAnimationEncoder` 只写变化矩形,并合并不变的帧。`PngImageDecoder.OpenRowReader(stream)` / `OpenRowReaderAsync` 从只能前向读取的流(上传、套接字)按行带解码,无论图片多高只占几行的内存,行数据与 `TryDecodeInto` 逐字节相同;隔行扫描和动画文件在同一 API 后先整体读入再解码(`IsStreaming` 为 false)。 - **Tiff**:多页,经典 TIFF 和 BigTIFF;8/16/32 位整数和浮点;Deflate / LZW(另可读 PackBits 和带 JPEGTables 的 JPEG);条带或分块;chunky 或 planar;按需读取单个条带或分块,区域解码只读与区域相交的条带或分块;读取 1/2/4 位页面(扩展为 8 位)、CCITT 传真(Group 3 1D/2D、Group 4、Modified Huffman)和浮点预测器;门面把调色板、CMYK、YCbCr 页面呈现为 RGB,额外采样呈现为 alpha。写入用 Deflate。 - **Webp**:RFC 6386 / RFC 9649:VP8 有损、VP8L 无损、ALPH、带跳转的动画、ICC / EXIF / XMP。`WebpAnimationDecoder` 另外提供按时间戳定位和每帧的矩形。`WebpEncoder.EncodeLossless` 编码 VP8L 静态图(含 alpha),压缩力度 0–9;`WebpEncoder.EncodeLossy` 编码 VP8 静态图,质量 0–100、力度 0–6,透明度写进 ALPH 平面;两者都可写入 ICC / Exif / XMP。`WebpAnimationEncoder` 和 `WebpEncoder.EncodeAnimation` 编码动画:有损、无损,或每帧取两者中较小的;输入可以是整帧画布(只写变化的矩形,合并不变的帧),也可以是调用方给定的 ANMF 帧。 - **Gif**:GIF89a:全局 / 局部调色板、隔行、透明、全部 dispose 方式、NETSCAPE2.0 循环次数;合成好的帧,可跳转。编码器:静态图和动画,精确调色板或感知量化(OKLab 盒切分 + k-means,可选边缘自适应的 Floyd–Steinberg 抖动),不透明动画只写变化的矩形。规范没有定死的行为列在包的 README 里。 diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs index 98792e9..88e660e 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Contestants.cs @@ -18,6 +18,7 @@ internal static class Names public const string CurrentParallel = "CurrentParallel"; public const string CurrentReduced = "CurrentReduced"; public const string Baseline = "Baseline"; + public const string Streaming = "Streaming"; public const string ImageSharp = "ImageSharp"; public const string LibPng = "LibPng"; @@ -73,6 +74,39 @@ public static readonly (string Name, PngAblation Flags)[] Ablations = (Names.InflateOnly, PngAblation.InflateOnly), ]; + // Every row of png through PngImageDecoder.OpenRowReader (a non-seekable read of the bytes in memory) into rows. + private static void ReadStreaming(byte[] png, byte[] rows) + { + using var reader = PngImageDecoder.OpenRowReader(new ForwardOnlyStream(png), Abstractions.PixelFormat.Rgba32); + reader.ReadRows(rows, reader.Height); + } + + /// A byte array read forward only, as a network or request stream is. + private sealed class ForwardOnlyStream(byte[] data) : Stream + { + private int _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + int n = Math.Min(buffer.Length, data.Length - _position); + data.AsSpan(_position, n).CopyTo(buffer); + _position += n; + return n; + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + /// The case. /// /// Set up just this contestant, without the cross-checks (which would run every other one): what @@ -126,6 +160,20 @@ byte[] Destination() setup.Contestants.Add(new(Names.CurrentNative, () => Sink = PngReader.Decode(png))); } + if (Want(Names.Streaming)) + { + // The forward-only row reader over a stream of the file, every row into the same buffer layout. Its rows + // must be the span decode's before it is timed. + byte[] rows = Destination(); + ReadStreaming(png, rows); + if (verify && !rows.AsSpan().SequenceEqual(current)) + { + throw new InvalidOperationException($"{c.Name}: the streaming reader's rows differ from TryDecodeIntoRgba8; refusing to benchmark."); + } + + setup.Contestants.Add(new(Names.Streaming, () => ReadStreaming(png, rows))); + } + if (Settings.Ablate && only is null) { foreach ((string name, PngAblation flags) in Ablations) diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs index 181cbbd..ab1d20d 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/Matrix.cs @@ -132,6 +132,32 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary r.Ms.ContainsKey(Names.Streaming))) + { + sb.AppendLine(); + sb.AppendLine("Streaming = `PngImageDecoder.OpenRowReader` over a forward-only stream of the file, every row read into the " + + "same RGBA buffer (rows identical to current, checked before timing)."); + sb.AppendLine(); + sb.AppendLine("| Case | current | streaming | streaming ÷ current |"); + sb.AppendLine("|---|---:|---:|---:|"); + foreach ((DecodeSetup s, Dictionary ms) in rows) + { + if (ms.ContainsKey(Names.Streaming)) + { + sb.AppendLine($"| `{s.Case.Name}` | {Ms(ms, Names.Current)} | {Ms(ms, Names.Streaming)} | {Ratio(ms, Names.Streaming, Names.Current)} |"); + } + } + + foreach (string content in SourceImage.Contents) + { + var subset = rows.Where(r => r.Setup.Case.Content == content).Select(r => r.Ms).ToList(); + if (GeoMean(subset, Names.Streaming, Names.Current) is { } g) + { + sb.AppendLine($"- streaming ÷ current, {content}: {g.ToString("F3", CultureInfo.InvariantCulture)}× ({subset.Count(m => m.ContainsKey(Names.Streaming) && m.ContainsKey(Names.Current))} cases)"); + } + } + } + if (rows.Any(r => r.Ms.ContainsKey(Names.InflateOnly))) { sb.AppendLine(); @@ -154,7 +180,7 @@ public static string RenderDecode(IReadOnlyList<(DecodeSetup Setup, Dictionary (r.Setup.Case.Name, r.Setup.Allocated)).ToList(), - [Names.Current, Names.CurrentNative, Names.Baseline, Names.ImageSharp, Names.LibPng]); + [Names.Current, Names.CurrentNative, Names.Streaming, Names.Baseline, Names.ImageSharp, Names.LibPng]); AppendNotes(sb, notes); return sb.ToString(); } @@ -284,6 +310,7 @@ private static void AppendNotes(StringBuilder sb, List notes) Names.CurrentNative => "native", Names.CurrentParallel => "parallel", Names.CurrentReduced => "reduced", + Names.Streaming => "streaming", _ => name, }; diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs index 0efb3cc..ff7b27e 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/PngBenchmarks.cs @@ -33,6 +33,9 @@ public class PngDecodeBenchmarks [Benchmark] public void Baseline() => _run[Names.Baseline](); + [Benchmark] + public void Streaming() => _run[Names.Streaming](); + [Benchmark] public void ImageSharp() => _run[Names.ImageSharp](); @@ -51,7 +54,7 @@ public class PngDecodeBenchmarks [Benchmark] public void InflateOnly() => _run[Names.InflateOnly](); - public static readonly string[] Methods = [Names.Current, Names.CurrentNative, Names.Baseline, Names.ImageSharp, Names.LibPng]; + public static readonly string[] Methods = [Names.Current, Names.CurrentNative, Names.Streaming, Names.Baseline, Names.ImageSharp, Names.LibPng]; } /// BenchmarkDotNet over the encode cases; see . @@ -76,6 +79,9 @@ public class PngEncodeBenchmarks [Benchmark] public void Baseline() => _run[Names.Baseline](); + [Benchmark] + public void Streaming() => _run[Names.Streaming](); + [Benchmark] public void ImageSharp() => _run[Names.ImageSharp](); diff --git a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md index 644dbe7..91163cf 100644 --- a/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md +++ b/benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/README.md @@ -26,6 +26,7 @@ Decode inputs are encoded by ImageSharp (adaptive filters, zlib level 6) — a f |---|---|---| | `current` | `PngImageDecoder.TryDecodeIntoRgba8` into a reused buffer | `PngWriter.Encode*` with `PngWriteOptions.CompressionLevel` | | `native` (decode) | `PngReader.Decode`: samples as stored, no RGBA expansion | — | +| `streaming` (decode) | `PngImageDecoder.OpenRowReader` over a forward-only stream of the file, every row into the same RGBA buffer; its rows must equal `current`'s before it is timed, and the report gains a streaming ÷ current table | — | | `parallel` (encode) | — | the same with `ParallelFragments = Environment.ProcessorCount`; reported in its own table, never in the single-thread ratios | | `reduced` (encode) | — | the same with `LosslessReduction = true` (the smallest exact layout: indexed, sub-byte grey, tRNS, ...); its own table, with the layout chosen | | `baseline` | the previous commit's decoder, same process (see below) | the previous commit's encoder | diff --git a/src/Sdcb.SimdCodecs.Png/PngImageDecoder.cs b/src/Sdcb.SimdCodecs.Png/PngImageDecoder.cs index e8a4c58..0339c64 100644 --- a/src/Sdcb.SimdCodecs.Png/PngImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Png/PngImageDecoder.cs @@ -6,6 +6,7 @@ using System.Numerics; using System.Runtime.InteropServices; using System.Threading; +using System.Threading.Tasks; using Sdcb.SimdCodecs.Abstractions; using Sdcb.SimdCodecs.Abstractions.CodecSupport; @@ -26,7 +27,7 @@ namespace Sdcb.SimdCodecs.Png; /// at the facade boundary. /// /// -public sealed class PngImageDecoder : IMultiFrameImageDecoder +public sealed class PngImageDecoder : IMultiFrameImageDecoder, IStreamingImageDecoder { /// The registration for ImageCodecs.Register, built from this type's method groups. public static ImageDecoderRegistration Registration { get; } = new() @@ -41,6 +42,7 @@ public sealed class PngImageDecoder : IMultiFrameImageDecoder TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, TryOpenFrames = TryOpenFrames, + CreateRowReader = CreateRowReader, }; private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; @@ -313,6 +315,70 @@ private static bool TryDecodeWindowInto(ReadOnlySpan data, Span dest return ImageDecoderFallback.TryDecodeInto(TryDecode, data, destination, stride, format, options, cancellationToken); } + /// + /// + /// A non-interlaced, non-animated PNG streams: the IDAT data is inflated as it arrives and each row is written as soon + /// as it is complete, holding two rows and a window of compressed input whatever the height. The rows are + /// 's byte for byte; the last row is returned once the rest of the file (every CRC, up to + /// IEND) has been checked, so a file refuses throws + /// before its last row. is over the chunks before the + /// image data: an eXIf (orientation), cICP, gAMA, iCCP or pHYs placed after IDAT is + /// not in it. A chunk after IDAT that the PNG specification puts before it and that would change rows already + /// written fails the read with where honours it: a + /// PLTE (indexed), a tRNS (formats with alpha), or a PQ/HLG cICP (8-bit samples, which + /// refuses). + /// Read whole and decoded first ( false), with exactly + /// 's result: Adam7-interlaced and animated (acTL) files, an indexed file whose PLTE comes + /// after IDAT, a cICP PQ/HLG file read to 8-bit samples, and options other than the whole image at full size. + /// + public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + PngReader.CreateRowReader(input, format, options); + + /// + /// Opens a row reader over (positioned at the start of the + /// PNG; it need not seek) and reads its header. + /// + /// The PNG, read forward only. + /// The layout of the rows to write. + /// Null (or the whole image) to stream; any other options decode the whole file first. + /// Keep open when the reader is disposed, or when the open fails + /// (otherwise a failed open disposes it). + /// The stream is not a PNG, or its header is malformed or cut short. + public static StreamingRowReader OpenRowReader(Stream stream, PixelFormat format, DecodeOptions? options = null, bool leaveOpen = false) + { + var reader = CreateRowReader(new StreamInput(stream, leaveOpen), format, options); + try + { + reader.Initialize(); + return reader; + } + catch + { + reader.Dispose(); + throw; + } + } + + /// , reading the header asynchronously. + /// + /// Cancels the header read. + /// The stream is not a PNG, or its header is malformed or cut short. + public static async ValueTask OpenRowReaderAsync(Stream stream, PixelFormat format, DecodeOptions? options = null, + bool leaveOpen = false, CancellationToken cancellationToken = default) + { + var reader = CreateRowReader(new StreamInput(stream, leaveOpen), format, options); + try + { + await reader.InitializeAsync(cancellationToken).ConfigureAwait(false); + return reader; + } + catch + { + reader.Dispose(); + throw; + } + } + /// /// to tightly packed 8-bit RGBA: must be /// at least Width * Height * 4 bytes. @@ -448,6 +514,23 @@ private static ChunkFacts ScanChunks(ReadOnlySpan data, int colorType) return new ChunkFacts(transparent, orientation, frames, cicp, gamma, resolution, icc); } + // TryReadInfo's answer from a header ReadHeader has read: for a file TryReadInfo refuses but the span decoder reads + // (an IHDR that is not the first chunk), so that a row reader still has its info. + internal static ImageInfo InfoOf(PngImage header) + { + TryMapLayout(header.ColorType, header.SourceBitDepth, header.TransparentColor is not null, out var channels, out var format); + return new ImageInfo(header.Width, header.Height, channels, format) + { + Format = ImageFormat.Png, + BitDepth = header.ColorType == 3 ? 8 : header.SourceBitDepth, + Orientation = header.Exif is { } exif ? ExifOrientation.Read(exif) : ImageOrientation.Normal, + ColorEncoding = MapColorEncoding(header.Cicp, header.Gamma, header.IccProfile), + Resolution = header.PhysicalDimensions is { } p + ? new Resolution(p.PixelsPerUnitX, p.PixelsPerUnitY, p.UnitIsMetre ? ResolutionUnit.PerMeter : ResolutionUnit.AspectRatio) + : null, + }; + } + // The layout TryDecode produces. Indexed always expands to RGBA8; the rest keep // their native channel count and bit depth, plus alpha for a tRNS transparent colour. // Mirrors the ToDecoded mapping below. diff --git a/src/Sdcb.SimdCodecs.Png/PngReader.Streaming.cs b/src/Sdcb.SimdCodecs.Png/PngReader.Streaming.cs new file mode 100644 index 0000000..7b612d4 --- /dev/null +++ b/src/Sdcb.SimdCodecs.Png/PngReader.Streaming.cs @@ -0,0 +1,653 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Png; + +public static partial class PngReader +{ + /// + /// How a streaming decode's starts when a chunk after the image data changes the + /// rows it has already written (a PLTE, tRNS or cICP that the PNG specification places before IDAT): the one case + /// where it refuses a file accepts. + /// + internal const string LateChunkMessage = "A chunk after the image data changes rows a streaming decode has already written"; + + /// + /// : a reader that inflates the IDAT stream as it arrives and writes each + /// row as soon as it is inflated. See . + /// + internal static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + new RowReader(input, format, options); + + /// + /// The streaming decode of a non-interlaced, non-animated PNG. The header is every chunk before the first IDAT, + /// read as reads them. The rows come from one over an + /// , which hands it the IDAT payloads straight out of the input window, checking each chunk's + /// CRC as it ends and reading the chunks after the image data as does, up to IEND (or the + /// end of the stream at a chunk boundary). Each row is unfiltered against the one above and converted to the format + /// exactly as (the five basic 8-bit formats) or (any other) does it, + /// so the rows are 's byte for byte. The last row is held back until the + /// rest of the file is checked, so a file the span decode refuses never reads to the end. + /// + /// Interlaced and animated files, an indexed file whose PLTE comes after IDAT, a cICP PQ/HLG file read to 8-bit + /// samples, and any options but the whole image take the buffered fallback: the span decoder over the whole file. + /// + /// + /// Memory: two rows, the format's working rows, the inflater's window, and an input window of at most a few rows of + /// compressed data (), whatever the height; a chunk before the first IDAT, and a chunk after it that + /// reads, is held whole while it is read (as the span decoder holds the file). Chunks + /// after the first IDAT that it skips are passed over without being held. The row buffers are allocated only once the input + /// holds enough data that deflate's 1032:1 limit lets it make a row, so a forged IHDR costs no more than the span + /// decoder's own check allows. + /// + /// + private sealed class RowReader(StreamInput input, PixelFormat format, DecodeOptions? options) : StreamingRowReader(input, format) + { + private readonly HeaderBuilder _builder = new(); + private int _headerPos = 8; // the end of the last whole chunk DecodeHeader has read + private bool _animated; // an acTL before IDAT + private bool _bufferWhole; // the fallback is chosen: the header waits for the end of the stream + + // Set once the header is read and the image streams. + private PngImage _header = null!; + private IdatWalker _walker = null!; + private ZLibStream _z = null!; + private readonly byte[] _one = new byte[1]; + private int _rowBytes; // a packed row, without its filter byte + private int _filterBpp; + private int _spp; + private long _expected; // the bytes the image data inflates to + private long _gate; // the most input a retry waits for (see DecodeRows) + private long _retryAt; // after running dry: the input to wait for before trying again + private long _dataStart; // the file offset of the first IDAT + private long _scratchBytes; + private int _rgbaBytes, _unpackedBytes, _builtBytes; + private bool _basic, _copyRgba, _direct; + private PngRgba8Expander? _expander; // the basic formats' RGBA expansion + private PngRgba8Expander? _palette; // the other formats' index expansion + private ushort[]? _key; + private PixelFormat _fidelity; + + private byte[]? _scratch; + private bool _aIsCurrent = true; + private int _row; // rows written + private int _filled; // bytes of the current row (filter byte first) inflated + private bool _rowReady; // the current row is inflated and unfiltered + private bool _streamEnded, _fileEnded, _checked; + + 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 (_bufferWhole) + return WholeFileHeader(input, isFinal, out info, out width, out height); + + if (input.Length < Signature.Length) + { + if (!input.SequenceEqual(Signature.AsSpan(0, input.Length))) + throw new InvalidDataException("PNG signature missing — not a PNG file"); + return OperationStatus.NeedMoreData; + } + if (!input[..Signature.Length].SequenceEqual(Signature)) + throw new InvalidDataException("PNG signature missing — not a PNG file"); + + // The input starts at the image's first byte on every call; the chunks before _headerPos are read already. + while (true) + { + var pos = _headerPos; + var left = input.Length - pos; + if (left < 8) + { + if (!isFinal) + return OperationStatus.NeedMoreData; + if (left == 0) + throw NoImageData(); + throw new InvalidDataException($"Truncated chunk header at byte {pos}"); + } + var dataLen = BinaryPrimitives.ReadUInt32BigEndian(input.Slice(pos, 4)); + if (dataLen > int.MaxValue) + throw new InvalidDataException($"Chunk length {dataLen} exceeds int.MaxValue"); + var type = input.Slice(pos + 4, 4); + if (type.SequenceEqual("IDAT"u8)) + break; + if (left - 12L < dataLen) + { + if (isFinal) + throw new InvalidDataException($"Chunk at byte {pos} extends past end of file"); + return OperationStatus.NeedMoreData; + } + var len = (int)dataLen; + var chunk = input.Slice(pos + 8, len); + var declared = BinaryPrimitives.ReadUInt32BigEndian(input.Slice(pos + 8 + len, 4)); + var computed = Crc32(type, chunk); + if (declared != computed) + throw CrcMismatch(type, pos, declared, computed); + if (type.SequenceEqual("IEND"u8)) + throw NoImageData(); + if (type.SequenceEqual("acTL"u8)) + _animated = true; + _builder.Add(type, chunk); + _headerPos = pos + 12 + len; + } + + // The first IDAT: every chunk before it is read. (This point is reached once: the image streams from here, + // or the fallback takes over.) + _builder.AddIdat(); + var header = _builder.Snapshot(); + if (header.Interlaced || _animated || !IsFullImage(options) + || (header.ColorType == 3 && header.Palette is null) + || (Format.Sample == SampleFormat.UInt8 && header.Cicp is { TransferFunction: TransferFunction.Pq or TransferFunction.Hlg })) + { + // Adam7 scatters every pass over the whole image; an APNG's default image is decoded as the span decoder + // does; a palette still to come, an HDR refusal a later cICP may lift, options other than the whole + // image: all decided by the span decoder over the whole file. + _bufferWhole = true; + return WholeFileHeader(input, isFinal, out info, out width, out height); + } + if ((long)header.Width * Format.BytesPerPixel > Array.MaxLength) + throw new InvalidDataException($"A {header.Width}-pixel row of {Format} is longer than an array can hold."); + + // TryReadInfo over the chunks before the image data: the same info, but for what only later chunks say. + info = PngImageDecoder.TryReadInfo(input[.._headerPos], out var read) ? read : PngImageDecoder.InfoOf(header); + Prepare(header); + consumed = _headerPos; + _dataStart = Input.Position + _headerPos; + width = header.Width; + height = header.Height; + return OperationStatus.Done; + } + + // The span decoder's verdict on a file with no image data: no IHDR, or no IDAT. + private InvalidDataException NoImageData() + { + try + { + _builder.Build(0); + } + catch (InvalidDataException e) + { + return e; + } + return new InvalidDataException("No IDAT chunks found"); + } + + // The fallback's header: the whole file, checked as the span decoder checks it before it allocates anything. + private OperationStatus WholeFileHeader(ReadOnlySpan input, bool isFinal, out ImageInfo info, out int width, out int height) + { + info = default; + width = height = 0; + if (!isFinal) + return OperationStatus.NeedMoreData; + PngImage header; + try + { + header = ReadHeader(input, out _); + } + catch (Exception e) when (e is ArgumentException or NotSupportedException) + { + throw new InvalidDataException($"The PNG data is invalid: {e.Message}", e); + } + info = PngImageDecoder.TryReadInfo(input, out var read) ? read : PngImageDecoder.InfoOf(header); + (width, height) = (options ?? DecodeOptions.Default).GetOutputSize(info); + UseBufferedFallback(DecodeWhole, options); + return OperationStatus.Done; + } + + // The fallback's decode: TryDecodeInto, with the reason when it refuses the file. + private static bool DecodeWhole(ReadOnlySpan data, Span destination, int stride, PixelFormat format, + DecodeOptions? options, CancellationToken cancellationToken) + { + if (PngImageDecoder.TryDecodeInto(data, destination, stride, format, options, cancellationToken)) + return true; + if (format.Sample == SampleFormat.UInt8 && TryDecode(data, out var png, cancellationToken) + && png.Cicp is { TransferFunction: TransferFunction.Pq or TransferFunction.Hlg }) + throw new InvalidDataException("The PNG is tagged PQ or HLG (cICP), which has no 8-bit projection: read it to 16-bit samples."); + try + { + Decode(data, cancellationToken); + } + catch (InvalidDataException e) + { + throw new InvalidDataException($"The PNG could not be decoded: {e.Message}", e); + } + catch (Exception e) when (e is ArgumentException or NotSupportedException) + { + throw new InvalidDataException($"The PNG data is invalid: {e.Message}", e); + } + return false; + } + + // The per-image constants of the row loop, as DecodeInto (basic formats) and DecodeWindow (the rest) set them. + private void Prepare(PngImage header) + { + _header = header; + int width = header.Width, bitDepth = header.SourceBitDepth, colorType = header.ColorType; + _spp = SamplesPerPixel(colorType); + var rowBytes = ((long)width * _spp * bitDepth + 7) / 8; + if (rowBytes >= Array.MaxLength) + throw new InvalidDataException($"A {width}-pixel row is longer than an array can hold."); + _rowBytes = (int)rowBytes; + _filterBpp = bitDepth < 8 ? 1 : _spp * (bitDepth / 8); + _expected = InflatedSize(width, header.Height, bitDepth, colorType, interlaced: false); + _basic = Format.IsBasic8; + long rgba = 0, unpacked = 0, built = 0; + if (_basic) + { + _expander = new PngRgba8Expander(colorType, bitDepth, header.Palette, header.PaletteAlpha, header.TransparentColor); + _copyRgba = colorType == 6 && bitDepth == 8 && Format == PixelFormat.Rgba32; + _direct = Format != PixelFormat.Rgba32 && bitDepth == 8 && colorType != 3 && header.TransparentColor is null; + rgba = _copyRgba || _direct || Format == PixelFormat.Rgba32 ? 0 : 4L * width; + } + else + { + _fidelity = FidelityFormat(header); + _key = header.UnpackedTransparentColor(); + _palette = colorType == 3 ? new PngRgba8Expander(3, 8, header.Palette, header.PaletteAlpha) : null; + unpacked = bitDepth < 8 ? width : 0; + built = colorType == 3 || _key is not null || bitDepth == 16 ? (long)width * _fidelity.BytesPerPixel : 0; + } + _scratchBytes = 2 * (rowBytes + 1) + rgba + unpacked + built; + if (_scratchBytes > Array.MaxLength) + throw new InvalidDataException($"A {width}-pixel row is longer than an array can hold."); + (_rgbaBytes, _unpackedBytes, _builtBytes) = ((int)rgba, (int)unpacked, (int)built); + // A row's compressed form is at most a little longer than the row (stored blocks): with two rows' worth + // buffered, a row's inflate does not run out of input midway. Kept between 32 KiB and 16 MiB. + _gate = Math.Clamp(2 * (rowBytes + 1) + 1024, 32 * 1024, 16 * 1024 * 1024); + _walker = new IdatWalker(_builder); + _z = new ZLibStream(_walker, CompressionMode.Decompress, leaveOpen: true); + } + + protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed, + Span destination, int stride, int rowCount, out int rowsWritten) + { + rowsWritten = 0; + consumed = 0; + if (_scratch is null) + { + // Deflate makes at most 1032 bytes of each compressed byte: allocate a row's buffers only once the + // input could hold one (when the whole file cannot, the span decoder refuses it by the same limit). + if (_rowBytes + 1L > input.Length * 1032L + 1024) + { + if (isFinal) + throw new InvalidDataException( + $"{input.Length} bytes of image data cannot inflate to the {_expected} a {_header.Width}×{_header.Height} image needs"); + return OperationStatus.NeedMoreData; + } + _scratch = ArrayPool.Shared.Rent((int)_scratchBytes); + _scratch.AsSpan(0, 2 * (_rowBytes + 1)).Clear(); // the row above the first is zeros + } + + _walker.Begin(Input.BufferedMemory, Input.Position, isFinal); + var outRowBytes = _header.Width * Format.BytesPerPixel; + while (rowsWritten < rowCount) + { + // A row is tried as soon as input is there. Running dry inside one unwinds the inflater with an + // exception, so after that the next try waits for twice the input that was not enough (up to _gate): + // a row costs a few such tries at most, however its bytes arrive. + // Before that, a row waits for twice the input an average row so far has taken, so that a steady stream + // seldom runs dry at all. + var available = input.Length - _walker.Consumed; + var fed = Input.Position + _walker.Consumed - _dataStart; + var expected = _row == 0 || _rowReady ? 0 : Math.Min(_gate, 2 * fed / _row + 64); + if (!isFinal && !_walker.Ended && available < Math.Max(expected, _retryAt)) + break; + if (!_rowReady) + { + if (!InflateRow()) + { + _retryAt = Math.Min(_gate, 2L * available + 64); + break; + } + var raw = Current; + PngPredictor.UnfilterRow(raw[0], raw[1..], Above[1..], _filterBpp); + _rowReady = true; + } + if (_row == _header.Height - 1 && !FinishFile()) + { + _retryAt = Math.Min(_gate, 2L * available + 64); + break; + } + _retryAt = 0; + WriteRow(Current[1..], destination.Slice(rowsWritten * stride, outRowBytes)); + _aIsCurrent = !_aIsCurrent; + _row++; + rowsWritten++; + _filled = 0; + _rowReady = false; + } + consumed = _walker.Consumed; + return rowsWritten == rowCount ? OperationStatus.Done : OperationStatus.NeedMoreData; + } + + private Span Current => _scratch.AsSpan(_aIsCurrent ? 0 : _rowBytes + 1, _rowBytes + 1); + + private Span Above => _scratch.AsSpan(_aIsCurrent ? _rowBytes + 1 : 0, _rowBytes + 1); + + // Inflates the rest of the current row (filter byte, then samples). False when the input runs out first; the + // bytes inflated so far stay, and the inflater resumes from there. + private bool InflateRow() + { + var raw = Current; + while (_filled < raw.Length) + { + int n; + try + { + n = _z.Read(raw[_filled..]); + } + catch (InputStarvedException) + { + return false; + } + catch (IOException e) + { + // zlib's own error codes (a corrupt stream that is none of the cases DeflateStream names) arrive as an IOException. + throw new InvalidDataException("The image data is not a valid zlib stream", e); + } + if (n == 0) + throw LengthMismatch((long)_row * raw.Length + _filled, _expected, _header.Width, _header.Height, _filterBpp); + _filled += n; + } + return true; + } + + // Before the last row goes out: no byte past it in the zlib stream, the rest of the file read to IEND with + // every CRC and chunk checked, and the whole file's checks; then the chunks after the image data must not have + // changed what the rows decode to. False when the input runs out first. + private bool FinishFile() + { + if (!_streamEnded) + { + int extra; + try + { + extra = _z.Read(_one); + } + catch (InputStarvedException) + { + return false; + } + catch (IOException e) + { + throw new InvalidDataException("The image data is not a valid zlib stream", e); + } + if (extra != 0) + throw LengthMismatch(_expected + 1, _expected, _header.Width, _header.Height, _filterBpp); + _streamEnded = true; + } + if (!_fileEnded) + { + if (!_walker.DrainToEnd()) + return false; + _fileEnded = true; + } + if (!_checked) + { + var whole = _builder.Build(_walker.Compressed); + // A late tRNS changes only alpha, which a format without alpha drops (the expansion's colour is the same). + if (_header.ColorType == 3 && !SameBytes(whole.Palette, _header.Palette)) + throw new InvalidDataException($"{LateChunkMessage}: a PLTE after IDAT (the PNG specification puts it before it)."); + if (Format.HasAlpha && _header.ColorType == 3 && !SameBytes(whole.PaletteAlpha, _header.PaletteAlpha)) + throw new InvalidDataException($"{LateChunkMessage}: a tRNS after IDAT (the PNG specification puts it before it)."); + if (Format.HasAlpha && !Same(whole.TransparentColor, _header.TransparentColor)) + throw new InvalidDataException($"{LateChunkMessage}: a tRNS after IDAT (the PNG specification puts it before it)."); + if (Format.Sample == SampleFormat.UInt8 && whole.Cicp is { TransferFunction: TransferFunction.Pq or TransferFunction.Hlg }) + throw new InvalidDataException($"{LateChunkMessage}: a cICP after IDAT tags the image PQ or HLG, which has no 8-bit projection."); + _checked = true; + } + return true; + } + + private static bool SameBytes(byte[]? a, byte[]? b) => a is null ? b is null : b is not null && a.AsSpan().SequenceEqual(b); + + private static bool Same(ushort[]? a, ushort[]? b) => a is null ? b is null : b is not null && a.AsSpan().SequenceEqual(b); + + // One unfiltered row into the destination, as DecodeInto (basic formats) or DecodeWindow (the rest) writes it. + private void WriteRow(ReadOnlySpan row, Span target) + { + var width = _header.Width; + if (_basic) + { + if (_copyRgba) + { + row.CopyTo(target); + } + else if (_direct) + { + PixelConverter.ConvertRow(row, _spp, SampleFormat.UInt8, target, Format, width); + } + else if (Format == PixelFormat.Rgba32) + { + _expander!.Expand(row, target, width); + } + else + { + var rgbaRow = _scratch.AsSpan(2 * (_rowBytes + 1), _rgbaBytes); + _expander!.Expand(row, rgbaRow, width); + PixelConverter.ConvertRow(rgbaRow, 4, SampleFormat.UInt8, target, Format, width); + } + return; + } + var at = 2 * (_rowBytes + 1); + var unpacked = _scratch.AsSpan(at, _unpackedBytes); + var built = _scratch.AsSpan(at + _unpackedBytes, _builtBytes); + var fidelityRow = FidelityRow(row, 0, width, _header.SourceBitDepth, _header.ColorType, _spp, _key, _palette, unpacked, built); + PixelConverter.ConvertRow(fidelityRow, _fidelity, target, Format, width); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _z?.Dispose(); + if (_scratch is not null) + ArrayPool.Shared.Return(_scratch); + _scratch = null; + } + base.Dispose(disposing); + } + } + + /// The input window ran out inside the image data before the stream ended: unwinds the inflater to retry. + private sealed class InputStarvedException : Exception; + + /// + /// The chunks from the first IDAT on, walked over a window of the input that moves forward: as a + /// , the IDAT payloads in order (what inflates), each chunk's CRC checked + /// as it ends; the chunks between and after the IDATs read through the as + /// reads them, those it skips passed over without being held; up to IEND, or the end of the + /// stream at a chunk boundary (both of which accepts). When the window ends inside a chunk + /// before the stream does, throws (returning 0 there + /// would read as the end of the data, and is refused outright under System.IO.Compression.UseStrictValidation); + /// the inflater has taken nothing in that call, so it resumes where it was once the window holds more. + /// + private sealed class IdatWalker(HeaderBuilder builder) : Stream + { + private enum State { Header, Idat, Skip, Crc, End } + + private ReadOnlyMemory _window; + private int _pos; // bytes of _window consumed + private long _offset; // the file offset of _window[0] + private bool _final; + private State _state; + private long _chunkStart; // the file offset of the current chunk + private uint _type; // the current chunk's type, big-endian + private long _left; // payload bytes of the current IDAT or skipped chunk still to come + private uint _crc; // the raw CRC register over the current chunk's type and payload so far + + /// The IDAT payloads' total length so far. + public long Compressed { get; private set; } + + /// True once IEND, or the end of the stream at a chunk boundary, is reached. + public bool Ended => _state == State.End; + + /// Bytes of the window consumed since . + public int Consumed => _pos; + + /// The next window: the unconsumed input, from file offset . + public void Begin(ReadOnlyMemory window, long offset, bool isFinal) + { + _window = window; + _pos = 0; + _offset = offset; + _final = isFinal; + } + + public override int Read(Span buffer) + { + if (buffer.IsEmpty) + return 0; + while (true) + { + if (_state == State.Idat && _left > 0) + { + var available = _window.Length - _pos; + if (available == 0) + { + if (_final) + throw PastEnd(); + throw new InputStarvedException(); + } + var n = (int)Math.Min(Math.Min(_left, available), buffer.Length); + var bytes = _window.Span.Slice(_pos, n); + bytes.CopyTo(buffer); + _crc = PngCrc32.Update(_crc, bytes); + _pos += n; + _left -= n; + return n; + } + if (_state == State.End) + return 0; + if (!Step()) + throw new InputStarvedException(); + } + } + + /// + /// Walks to the end of the file, passing over what is left of the IDAT payloads (the zlib stream has ended). + /// False when the window runs out first. + /// + public bool DrainToEnd() + { + while (_state != State.End) + { + if (!Step()) + return false; + } + return true; + } + + // One step that hands the inflater nothing: the rest of a payload passed over, a CRC, or a chunk header (and a + // chunk the header builder reads, whole). False when the window ends inside it before the stream does. + private bool Step() + { + var span = _window.Span; + var available = span.Length - _pos; + switch (_state) + { + case State.Idat or State.Skip: + { + var n = (int)Math.Min(_left, available); + _crc = PngCrc32.Update(_crc, span.Slice(_pos, n)); + _pos += n; + _left -= n; + if (_left > 0) + return _final ? throw PastEnd() : false; + _state = State.Crc; + return true; + } + case State.Crc: + { + if (available < 4) + return _final ? throw PastEnd() : false; + var declared = BinaryPrimitives.ReadUInt32BigEndian(span.Slice(_pos, 4)); + var computed = _crc ^ 0xFFFFFFFFu; + if (declared != computed) + throw CrcMismatch(TypeBytes(_type), _chunkStart, declared, computed); + _pos += 4; + _state = State.Header; + return true; + } + case State.Header: + { + if (available < 8) + { + if (!_final) + return false; + // The file ends at a chunk boundary without IEND, as ReadHeader accepts; a few bytes more are a + // cut chunk header. + if (available == 0) + { + _state = State.End; + return true; + } + throw new InvalidDataException($"Truncated chunk header at byte {_offset + _pos}"); + } + var dataLen = BinaryPrimitives.ReadUInt32BigEndian(span.Slice(_pos, 4)); + if (dataLen > int.MaxValue) + throw new InvalidDataException($"Chunk length {dataLen} exceeds int.MaxValue"); + var type = span.Slice(_pos + 4, 4); + _chunkStart = _offset + _pos; + if (type.SequenceEqual("IDAT"u8) || !(HeaderBuilder.Reads(type) || type.SequenceEqual("IEND"u8))) + { + // A payload passed through (IDAT) or over (a chunk ReadHeader skips) without being held. + var idat = type.SequenceEqual("IDAT"u8); + if (idat) + { + builder.AddIdat(); + Compressed += dataLen; + } + _type = BinaryPrimitives.ReadUInt32BigEndian(type); + _crc = PngCrc32.Update(0xFFFFFFFFu, type); + _left = dataLen; + _pos += 8; + _state = idat ? State.Idat : State.Skip; + return true; + } + // A chunk the header builder reads, whole: as ReadHeader reads it. + if (available - 12L < dataLen) + return _final ? throw PastEnd() : false; + var len = (int)dataLen; + var chunk = span.Slice(_pos + 8, len); + var declared = BinaryPrimitives.ReadUInt32BigEndian(span.Slice(_pos + 8 + len, 4)); + var computed = Crc32(type, chunk); + if (declared != computed) + throw CrcMismatch(type, _chunkStart, declared, computed); + if (type.SequenceEqual("IEND"u8)) + _state = State.End; + else + builder.Add(type, chunk); + _pos += 12 + len; + return true; + } + default: + return true; + } + } + + private static byte[] TypeBytes(uint type) + { + var bytes = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(bytes, type); + return bytes; + } + + private InvalidDataException PastEnd() => new($"Chunk at byte {_chunkStart} extends past end of file"); + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/Sdcb.SimdCodecs.Png/PngReader.cs b/src/Sdcb.SimdCodecs.Png/PngReader.cs index e132b95..d44cf0a 100644 --- a/src/Sdcb.SimdCodecs.Png/PngReader.cs +++ b/src/Sdcb.SimdCodecs.Png/PngReader.cs @@ -101,24 +101,10 @@ internal static PngImage ReadHeader(ReadOnlySpan data, out List<(int Offse throw new InvalidDataException("PNG signature missing — not a PNG file"); int pos = Signature.Length; - int? width = null, height = null, bitDepth = null, colorType = null, - compressionMethod = null, filterMethod = null, interlaceMethod = null; // Where each IDAT's payload lies in the input: read in place, never copied out. var idatChunks = new List<(int Offset, int Length)>(); - byte[]? palette = null; // PLTE: 3 bytes (RGB) per entry - byte[]? trns = null; // tRNS as stored; read by colour type below - PngPhysicalDimensions? physical = null; - byte[]? iccProfileRaw = null; // zlib-deflated, as on disk - string? iccProfileName = null; - byte[]? rawExif = null; - List? text = null; - bool sawSrgb = false; - byte srgbRenderingIntent = 0; - uint? gamma100k = null; - ChromaticityChunk? chrm = null; - CicpChunk? cicp = null; - MdcvChunk? mdcv = null; - ClliChunk? clli = null; + var header = new HeaderBuilder(); + long compressed = 0; while (pos < data.Length) { @@ -140,10 +126,73 @@ internal static PngImage ReadHeader(ReadOnlySpan data, out List<(int Offse var declaredCrc = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(pos + 8 + len, 4)); var computedCrc = verifyCrc ? Crc32(typeBytes, chunkData) : declaredCrc; if (declaredCrc != computedCrc) - throw new InvalidDataException( - $"CRC mismatch on chunk '{TypeAscii(typeBytes)}' at byte {pos}: " + - $"declared 0x{declaredCrc:X8}, computed 0x{computedCrc:X8}"); + throw CrcMismatch(typeBytes, pos, declaredCrc, computedCrc); + + if (typeBytes.SequenceEqual("IDAT"u8)) + { + header.AddIdat(); + idatChunks.Add((pos + 8, len)); + compressed += len; + } + else if (typeBytes.SequenceEqual("IEND"u8)) + { + pos += 8 + len + 4; + break; + } + else + { + header.Add(typeBytes, chunkData); + } + pos += 8 + len + 4; + } + + // The IDAT chunks are one zlib stream — the spec lets a producer split IDATs anywhere, even + // mid-deflate-token — inflated by the caller, a row at a time. + idat = idatChunks; + return header.Build(compressed); + } + + private static InvalidDataException CrcMismatch(ReadOnlySpan typeBytes, long pos, uint declaredCrc, uint computedCrc) => + new($"CRC mismatch on chunk '{TypeAscii(typeBytes)}' at byte {pos}: " + + $"declared 0x{declaredCrc:X8}, computed 0x{computedCrc:X8}"); + + /// + /// The chunks other than IDAT and IEND, read one at a time as walks the file (and as the + /// streaming reader meets them, ): each chunk's own checks as it is added, the whole file's in + /// . Every chunk passed in has had its CRC checked. + /// + private sealed class HeaderBuilder + { + private int? width, height, bitDepth, colorType, interlaceMethod; + private bool sawIdat; + private byte[]? palette; // PLTE: 3 bytes (RGB) per entry + private byte[]? trns; // tRNS as stored; read by colour type below + private PngPhysicalDimensions? physical; + private byte[]? iccProfileRaw; // zlib-deflated, as on disk + private string? iccProfileName; + private byte[]? rawExif; + private List? text; + private bool sawSrgb; + private byte srgbRenderingIntent; + private uint? gamma100k; + private ChromaticityChunk? chrm; + private CicpChunk? cicp; + private MdcvChunk? mdcv; + private ClliChunk? clli; + + /// An IDAT chunk (its payload is the caller's): refused before IHDR. + public void AddIdat() + { + if (width is null) + throw new InvalidDataException("IDAT before IHDR"); + sawIdat = true; + } + + /// Any chunk but IDAT and IEND. + public void Add(ReadOnlySpan typeBytes, ReadOnlySpan chunkData) + { + var len = chunkData.Length; // --- chunk dispatch ----------------------------------------------------- // Critical chunks (uppercase first letter) must be understood; ancillary // chunks (lowercase first letter) can be skipped if unrecognised. @@ -157,8 +206,8 @@ internal static PngImage ReadHeader(ReadOnlySpan data, out List<(int Offse height = (int)BinaryPrimitives.ReadUInt32BigEndian(chunkData.Slice(4, 4)); bitDepth = chunkData[8]; colorType = chunkData[9]; - compressionMethod = chunkData[10]; - filterMethod = chunkData[11]; + int compressionMethod = chunkData[10]; + int filterMethod = chunkData[11]; interlaceMethod = chunkData[12]; if (width <= 0 || height <= 0) @@ -171,17 +220,6 @@ internal static PngImage ReadHeader(ReadOnlySpan data, out List<(int Offse throw new InvalidDataException($"Unknown interlace method {interlaceMethod} (PNG defines 0 and 1)"); ValidateColorTypeAndBitDepth(colorType.Value, bitDepth.Value); } - else if (typeBytes.SequenceEqual("IDAT"u8)) - { - if (width is null) - throw new InvalidDataException("IDAT before IHDR"); - idatChunks.Add((pos + 8, len)); - } - else if (typeBytes.SequenceEqual("IEND"u8)) - { - pos += 8 + len + 4; - break; - } else if (typeBytes.SequenceEqual("PLTE"u8)) { if (len == 0 || len % 3 != 0) @@ -267,75 +305,93 @@ internal static PngImage ReadHeader(ReadOnlySpan data, out List<(int Offse // Any other chunk — silently skip. PNG is forwards-compatible by design: // ancillary unknown chunks are explicitly permitted, and critical unknown // chunks have a leading uppercase letter we'd need to reject. We defer the - // critical-chunk rejection until we encounter a real one. - - pos += 8 + len + 4; + // critical-chunk rejection until we encounter a real one. (Reads lists the types read here.) } - if (width is null) throw new InvalidDataException("No IHDR chunk found"); - if (idatChunks.Count == 0) throw new InvalidDataException("No IDAT chunks found"); - if (colorType == 3 && palette is null) - throw new InvalidDataException("Indexed-color PNG missing required PLTE chunk"); + /// + /// True for a chunk type reads (and may refuse); false for one it skips, whose payload a + /// streaming reader therefore need not hold. + /// + public static bool Reads(ReadOnlySpan typeBytes) => + typeBytes.SequenceEqual("IHDR"u8) || typeBytes.SequenceEqual("PLTE"u8) || typeBytes.SequenceEqual("tRNS"u8) + || typeBytes.SequenceEqual("pHYs"u8) || typeBytes.SequenceEqual("iCCP"u8) || typeBytes.SequenceEqual("sRGB"u8) + || typeBytes.SequenceEqual("gAMA"u8) || typeBytes.SequenceEqual("cHRM"u8) || typeBytes.SequenceEqual("eXIf"u8) + || typeBytes.SequenceEqual("tEXt"u8) || typeBytes.SequenceEqual("zTXt"u8) || typeBytes.SequenceEqual("iTXt"u8) + || typeBytes.SequenceEqual("cICP"u8) || typeBytes.SequenceEqual("mDCV"u8) || typeBytes.SequenceEqual("mDCv"u8) + || typeBytes.SequenceEqual("cLLI"u8); + + /// + /// The whole file's checks, once every chunk is in ( the IDAT payloads' total + /// length), then . + /// + public PngImage Build(long compressed) + { + if (width is null) throw new InvalidDataException("No IHDR chunk found"); + if (!sawIdat) throw new InvalidDataException("No IDAT chunks found"); + if (colorType == 3 && palette is null) + throw new InvalidDataException("Indexed-color PNG missing required PLTE chunk"); + + // Deflate cannot expand more than 1032:1, so image data that would need more than that is cut + // short or the header lies. Refusing here keeps a forged header (2^30 × 2^30 over a few bytes) + // from reaching an allocation, or an int overflow, at all. + var inflatedSize = InflatedSize(width.Value, height!.Value, bitDepth!.Value, colorType!.Value, interlaceMethod == 1); + if (inflatedSize > compressed * 1032 + 1024) + throw new InvalidDataException( + $"{compressed} bytes of image data cannot inflate to the {inflatedSize} a {width}×{height} image needs"); + return Snapshot(); + } - // Deflate cannot expand more than 1032:1, so image data that would need more than that is cut - // short or the header lies. Refusing here keeps a forged header (2^30 × 2^30 over a few bytes) - // from reaching an allocation, or an int overflow, at all. - long compressed = 0; - foreach (var (_, length) in idatChunks) - compressed += length; - var inflatedSize = InflatedSize(width.Value, height!.Value, bitDepth!.Value, colorType!.Value, interlaceMethod == 1); - if (inflatedSize > compressed * 1032 + 1024) - throw new InvalidDataException( - $"{compressed} bytes of image data cannot inflate to the {inflatedSize} a {width}×{height} image needs"); - - // tRNS (PNG §11.3.1.1): for indexed colour one alpha byte per palette entry, entries past its - // end opaque; for greyscale and truecolour one colour, every sample in two bytes of which only - // the low bit depth's worth count (decoders mask the rest), marking the pixels of exactly that - // colour fully transparent. Colour types 4 and 6 have alpha already and may not carry one; one - // there, or one of the wrong length, is ignored, as an ancillary chunk can be. - byte[]? paletteAlpha = null; - ushort[]? transparentColor = null; - if (trns is not null) + /// The header and metadata of the chunks added so far, without the whole file's checks; needs IHDR. + public PngImage Snapshot() { - var sampleMask = (ushort)((1 << bitDepth!.Value) - 1); - if (colorType == 3) - paletteAlpha = trns; - else if ((colorType == 0 && trns.Length == 2) || (colorType == 2 && trns.Length == 6)) + if (width is null) throw new InvalidDataException("No IHDR chunk found"); + + // tRNS (PNG §11.3.1.1): for indexed colour one alpha byte per palette entry, entries past its + // end opaque; for greyscale and truecolour one colour, every sample in two bytes of which only + // the low bit depth's worth count (decoders mask the rest), marking the pixels of exactly that + // colour fully transparent. Colour types 4 and 6 have alpha already and may not carry one; one + // there, or one of the wrong length, is ignored, as an ancillary chunk can be. + byte[]? paletteAlpha = null; + ushort[]? transparentColor = null; + if (trns is not null) { - transparentColor = new ushort[trns.Length / 2]; - for (var i = 0; i < transparentColor.Length; i++) - transparentColor[i] = (ushort)(BinaryPrimitives.ReadUInt16BigEndian(trns.AsSpan(2 * i)) & sampleMask); + var sampleMask = (ushort)((1 << bitDepth!.Value) - 1); + if (colorType == 3) + paletteAlpha = trns; + else if ((colorType == 0 && trns.Length == 2) || (colorType == 2 && trns.Length == 6)) + { + transparentColor = new ushort[trns.Length / 2]; + for (var i = 0; i < transparentColor.Length; i++) + transparentColor[i] = (ushort)(BinaryPrimitives.ReadUInt16BigEndian(trns.AsSpan(2 * i)) & sampleMask); + } } - } - // The IDAT chunks are one zlib stream — the spec lets a producer split IDATs anywhere, even - // mid-deflate-token — inflated by the caller, a row at a time. - idat = idatChunks; - return new PngImage - { - Width = width.Value, - Height = height!.Value, - // A sub-byte image's samples come back unpacked, one byte each: they are 8-bit samples now. - BitDepth = bitDepth!.Value < 8 ? 8 : bitDepth.Value, - SourceBitDepth = bitDepth.Value, - ColorType = colorType!.Value, - Interlaced = interlaceMethod == 1, - Pixels = [], - Palette = palette, - PaletteAlpha = paletteAlpha, - TransparentColor = transparentColor, - PhysicalDimensions = physical, - IccProfile = iccProfileRaw, - IccProfileName = iccProfileName, - SrgbRenderingIntent = sawSrgb ? srgbRenderingIntent : null, - Gamma = gamma100k.HasValue ? gamma100k.Value / 100_000.0 : null, - Chromaticity = chrm, - Exif = rawExif, - Text = text is null ? [] : [.. text], - Cicp = cicp, - Mdcv = mdcv, - Clli = clli, - }; + return new PngImage + { + Width = width.Value, + Height = height!.Value, + // A sub-byte image's samples come back unpacked, one byte each: they are 8-bit samples now. + BitDepth = bitDepth!.Value < 8 ? 8 : bitDepth.Value, + SourceBitDepth = bitDepth.Value, + ColorType = colorType!.Value, + Interlaced = interlaceMethod == 1, + Pixels = [], + Palette = palette, + PaletteAlpha = paletteAlpha, + TransparentColor = transparentColor, + PhysicalDimensions = physical, + IccProfile = iccProfileRaw, + IccProfileName = iccProfileName, + SrgbRenderingIntent = sawSrgb ? srgbRenderingIntent : null, + Gamma = gamma100k.HasValue ? gamma100k.Value / 100_000.0 : null, + Chromaticity = chrm, + Exif = rawExif, + Text = text is null ? [] : [.. text], + Cicp = cicp, + Mdcv = mdcv, + Clli = clli, + }; + } } /// @@ -989,11 +1045,19 @@ public override void Flush() { } using var output = new MemoryStream(); var buffer = new byte[81920]; int read; - while ((read = z.Read(buffer)) > 0) + try { - if (output.Length + read > maxBytes) - return null; - output.Write(buffer, 0, read); + while ((read = z.Read(buffer)) > 0) + { + if (output.Length + read > maxBytes) + return null; + output.Write(buffer, 0, read); + } + } + catch (IOException e) + { + // zlib's own error codes (a corrupt stream that is none of the cases DeflateStream names) arrive as an IOException. + throw new InvalidDataException("A compressed chunk is not a valid zlib stream", e); } return output.ToArray(); } diff --git a/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt index 7dc5c58..947c571 100644 --- a/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Png/PublicAPI.Unshipped.txt @@ -1 +1,4 @@ #nullable enable +static Sdcb.SimdCodecs.Png.PngImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! +static Sdcb.SimdCodecs.Png.PngImageDecoder.OpenRowReader(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! +static Sdcb.SimdCodecs.Png.PngImageDecoder.OpenRowReaderAsync(System.IO.Stream! stream, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options = null, bool leaveOpen = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask diff --git a/tests/Sdcb.SimdCodecs.Tests/PngStreamingDecodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/PngStreamingDecodeTests.cs new file mode 100644 index 0000000..cfc6586 --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/PngStreamingDecodeTests.cs @@ -0,0 +1,729 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.IO.Compression; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Png; +using Sdcb.SimdCodecs.Tests.Streaming; +using Shouldly; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// : a non-interlaced PNG decodes from a forward-only stream as it arrives, +/// its rows exactly 's for every colour type, depth and pixel format, under +/// every feed; interlaced and animated files and non-full options fall back with the same rows; truncated and corrupt +/// streams fail with exactly where the span decode refuses them; memory stays a few +/// rows whatever the height. +/// +public sealed class PngStreamingDecodeTests +{ + private static readonly PixelFormat[] Formats = + [ + PixelFormat.Rgba32, PixelFormat.Bgra32, PixelFormat.Rgb24, PixelFormat.Bgr24, PixelFormat.Gray8, PixelFormat.GrayAlpha16, + PixelFormat.Rgba64, PixelFormat.Rgb48, PixelFormat.Gray16, PixelFormat.GrayAlpha32, PixelFormat.Rgba32Premultiplied, + PixelFormat.Bgra64Premultiplied, + ]; + + private static readonly (int ColorType, int Depth)[] Layouts = + [ + (0, 1), (0, 2), (0, 4), (0, 8), (0, 16), (2, 8), (2, 16), (3, 1), (3, 2), (3, 4), (3, 8), (4, 8), (4, 16), (6, 8), (6, 16), + ]; + + private static ImageDecoderRegistration Codec => PngImageDecoder.Registration; + + public static TheoryData LayoutCases() + { + var data = new TheoryData(); + foreach (var (colorType, depth) in Layouts) + { + data.Add(colorType, depth, 0); // plain + if (colorType is 0 or 2 or 3) + data.Add(colorType, depth, 1); // tRNS + } + return data; + } + + [Theory] + [MemberData(nameof(LayoutCases))] + public void HandBuilt_RowsEqualDecodeInto_EveryFormatAndFeed(int colorType, int depth, int trns) + { + // Odd sizes, every filter type, the zlib stream split into small IDATs. + var png = HandBuilt(colorType, depth, 13, 11, seed: colorType * 100 + depth + trns, idatBytes: 37, trns: trns == 1); + foreach (var format in Formats) + StreamingAssert.RowsEqualDecodeInto(Codec, png, format, expectStreaming: true); + } + + [Fact] + public void ImageMagickFiles_RowsEqualDecodeInto() + { + foreach (var (colorType, depth) in Layouts) + { + var png = MagickPng(colorType, depth, interlace: false, 37, 23); + (png[24], png[25]).ShouldBe(((byte)depth, (byte)colorType)); + foreach (var format in Formats) + StreamingAssert.RowsEqualDecodeInto(Codec, png, format, expectStreaming: true, + feeds: [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly, StreamingAssert.Feed.Whole]); + StreamingAssert.RowsEqualDecodeInto(Codec, png, PixelFormat.Rgba32, expectStreaming: true, feeds: [StreamingAssert.Feed.OneByte]); + } + } + + [Fact] + public void OurEncoder_RowsEqualDecodeInto() + { + const int w = 301, h = 97; + var rgba = Gradient(w, h, alpha: true); + foreach (var png in new[] + { + PngWriter.Encode(rgba, w, h), + PngWriter.Encode(rgba, w, h, new PngWriteOptions { LosslessReduction = true }), + PngWriter.EncodeRgb8(Gradient(w, h, alpha: false), w, h), + }) + { + foreach (var format in Formats) + StreamingAssert.RowsEqualDecodeInto(Codec, png, format, expectStreaming: true, + feeds: [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly, StreamingAssert.Feed.Whole]); + } + } + + [Fact] + public void IdatsOfOneByte_AndChunksBetweenAndAfterThem_Stream() + { + var png = HandBuilt(6, 8, 29, 17, seed: 5, idatBytes: 1); + StreamingAssert.RowsEqualDecodeInto(Codec, png, PixelFormat.Rgba32, expectStreaming: true); + StreamingAssert.RowsEqualDecodeInto(Codec, png, PixelFormat.Rgb48, expectStreaming: true); + + // IDATs interleaved with an unknown chunk and a text chunk; metadata, an unknown chunk and no IEND after the data. + var mixed = HandBuilt(2, 8, 29, 17, seed: 6, idatBytes: 50, between: s => + { + PngRgba8ExpansionTests.Chunk(s, "prVt"u8, new byte[300]); + PngRgba8ExpansionTests.Chunk(s, "tEXt"u8, "Comment\0between"u8); + }, after: s => + { + PngRgba8ExpansionTests.Chunk(s, "tEXt"u8, "Comment\0after"u8); + PngRgba8ExpansionTests.Chunk(s, "eXIf"u8, new byte[20]); + PngRgba8ExpansionTests.Chunk(s, "zzZz"u8, new byte[5000]); + }, iend: false); + StreamingAssert.RowsEqualDecodeInto(Codec, mixed, PixelFormat.Rgba32, expectStreaming: true); + StreamingAssert.RowsEqualDecodeInto(Codec, mixed, PixelFormat.Gray8, expectStreaming: true); + } + + [Fact] + public void InterlacedAnimatedAndOptions_FallBack_WithTheSameRows() + { + foreach (var (colorType, depth) in Layouts) + { + var png = MagickPng(colorType, depth, interlace: true, 19, 13); + png[28].ShouldBe((byte)1); + foreach (var format in new[] { PixelFormat.Rgba32, PixelFormat.Gray8, PixelFormat.Rgba64 }) + StreamingAssert.RowsEqualDecodeInto(Codec, png, format, expectStreaming: false, + feeds: [StreamingAssert.Feed.RandomChunks, StreamingAssert.Feed.AsyncOnly]); + } + + foreach (var (name, apng) in ApngRobustnessTests.Seeds().Take(3)) + StreamingAssert.RowsEqualDecodeInto(Codec, apng, PixelFormat.Rgba32, expectStreaming: false); + + var plain = HandBuilt(6, 8, 40, 30, seed: 9); + DecodeOptions[] options = + [ + new() { Region = new PixelRect(3, 4, 20, 10) }, + new() { ScaleDenominator = 2 }, + new() { ApplyOrientation = true }, + ]; + foreach (var o in options) + StreamingAssert.RowsEqualDecodeInto(Codec, plain, PixelFormat.Rgba32, o, expectStreaming: false); + } + + [Fact] + public void HdrTagged_FallsBackForEightBitSamples_StreamsSixteen() + { + var cicp = new byte[] { 9, 16, 0, 1 }; // BT.2020, PQ, full range + var png = PngTransparentColorTests.WithChunk(HandBuilt(2, 16, 9, 7, seed: 3), "cICP"u8, cicp); + PngImageDecoder.TryDecodeInto(png, new byte[9 * 7 * 4], 0, PixelFormat.Rgba32, cancellationToken: TestContext.Current.CancellationToken).ShouldBeFalse(); + Should.Throw(() => ReadAll(png, PixelFormat.Rgba32, out _)); + StreamingAssert.RowsEqualDecodeInto(Codec, png, PixelFormat.Rgba64, expectStreaming: true); + } + + [Fact] + public void PaletteAfterIdat_FallsBack() + { + // PLTE after the data: the span decoder takes it, so the reader reads the file whole. + var palette = new byte[12]; + for (var i = 0; i < palette.Length; i++) + palette[i] = (byte)(i * 21); + var png = HandBuilt(3, 2, 11, 6, seed: 4, palette: false, after: s => PngRgba8ExpansionTests.Chunk(s, "PLTE"u8, palette)); + StreamingAssert.RowsEqualDecodeInto(Codec, png, PixelFormat.Rgba32, expectStreaming: false); + } + + [Fact] + public void ChunksAfterIdatThatChangeWrittenRows_AreRefused() + { + // The specification puts tRNS before IDAT; the span decoder honours one after it, the stream has written its + // rows by then and refuses the file rather than return other pixels. + var png = HandBuilt(2, 8, 9, 5, seed: 8, after: s => PngRgba8ExpansionTests.Chunk(s, "tRNS"u8, [0, 1, 0, 2, 0, 3])); + PngImageDecoder.TryDecodeInto(png, new byte[9 * 5 * 4], 0, PixelFormat.Rgba32, cancellationToken: TestContext.Current.CancellationToken).ShouldBeTrue(); + Should.Throw(() => ReadAll(png, PixelFormat.Rgba32, out _)).Message.ShouldStartWith(PngReader.LateChunkMessage); + + // A late tRNS changes only alpha: a format without alpha streams it, with TryDecodeInto's rows. + foreach (var format in new[] { PixelFormat.Rgb24, PixelFormat.Gray8, PixelFormat.Bgr48, PixelFormat.Gray16 }) + StreamingAssert.RowsEqualDecodeInto(Codec, png, format, expectStreaming: true); + var indexed = HandBuilt(3, 4, 9, 5, seed: 8, after: s => PngRgba8ExpansionTests.Chunk(s, "tRNS"u8, [0, 10, 20, 30])); + Should.Throw(() => ReadAll(indexed, PixelFormat.Rgba32, out _)).Message.ShouldStartWith(PngReader.LateChunkMessage); + foreach (var format in new[] { PixelFormat.Rgb24, PixelFormat.Gray8, PixelFormat.Rgb48 }) + StreamingAssert.RowsEqualDecodeInto(Codec, indexed, format, expectStreaming: true); + + var hdr = HandBuilt(2, 8, 9, 5, seed: 8, after: s => PngRgba8ExpansionTests.Chunk(s, "cICP"u8, [9, 16, 0, 1])); + PngImageDecoder.TryDecodeInto(hdr, new byte[9 * 5 * 4], 0, PixelFormat.Rgba32, cancellationToken: TestContext.Current.CancellationToken).ShouldBeFalse(); + Should.Throw(() => ReadAll(hdr, PixelFormat.Rgba32, out _)).Message.ShouldStartWith(PngReader.LateChunkMessage); + StreamingAssert.RowsEqualDecodeInto(Codec, hdr, PixelFormat.Rgba64, expectStreaming: true); + } + + [Fact] + public void InfoIsTheChunksBeforeTheImageData() + { + var png = HandBuilt(0, 8, 8, 4, seed: 2, trns: true); + using var reader = PngImageDecoder.OpenRowReader(new ChunkedStream(png, maxChunk: 3), PixelFormat.Rgba32); + PngImageDecoder.TryReadInfo(png, out var info).ShouldBeTrue(); + reader.Info.ShouldBe(info); + reader.IsStreaming.ShouldBeTrue(); + } + + [Fact] + public void EveryTruncation_FailsExactlyWhereTheSpanDecodeDoes() + { + var files = new[] + { + HandBuilt(6, 8, 7, 5, seed: 1, idatBytes: 20), + HandBuilt(3, 4, 9, 4, seed: 2, idatBytes: 9, trns: true, after: s => PngRgba8ExpansionTests.Chunk(s, "tEXt"u8, "a\0b"u8)), + HandBuilt(0, 16, 5, 6, seed: 3, iend: false), + }; + foreach (var png in files) + { + for (var cut = 0; cut <= png.Length; cut++) + SameVerdict(png[..cut], PixelFormat.Rgba32, $"cut to {cut} of {png.Length}"); + } + } + + [Fact] + public void BadCrcs_AndCorruptData_Fail() + { + var png = HandBuilt(6, 8, 7, 5, seed: 1, idatBytes: 20, after: s => PngRgba8ExpansionTests.Chunk(s, "zzZz"u8, [1, 2, 3])); + foreach (var chunk in ChunkStarts(png)) + { + // The last CRC byte of each chunk, then a payload byte. + var crc = (byte[])png.Clone(); + crc[chunk.End - 1] ^= 0x40; + SameVerdict(crc, PixelFormat.Rgba32, $"CRC of {chunk.Type}").ShouldBeFalse(); + if (chunk.Length > 0) + { + var payload = (byte[])png.Clone(); + payload[chunk.Offset + 8] ^= 0x01; + SameVerdict(payload, PixelFormat.Rgba32, $"payload of {chunk.Type}"); + } + } + } + + [Fact] + public void ReadingTheFirstRows_ReadsOnlyAPrefix() + { + const int w = 1024, h = 1024; + var png = PngWriter.EncodeRgb8(Noise(w, h, 3, seed: 11), w, h); + var stream = new ChunkedStream(png, maxChunk: 4096); + using var reader = PngImageDecoder.OpenRowReader(stream, PixelFormat.Rgb24); + var rows = new byte[w * 3 * 16]; + reader.ReadRows(rows, 16, cancellationToken: TestContext.Current.CancellationToken).ShouldBe(16); + reader.IsStreaming.ShouldBeTrue(); + stream.BytesRead.ShouldBeLessThan(png.Length / 8, $"{stream.BytesRead} of {png.Length} bytes read for 16 of {h} rows"); + } + + [Fact] + public void ARowComesOutOnceItsBytesArrive() + { + // 100-byte rows trickling in a byte at a time: the first row needs a few hundred bytes, not a buffer's worth. + var png = HandBuilt(2, 8, 33, 400, seed: 13); + var stream = new ChunkedStream(png, maxChunk: 1); + using var reader = PngImageDecoder.OpenRowReader(stream, PixelFormat.Rgb24); + var row = new byte[33 * 3]; + reader.ReadRows(row, 1, cancellationToken: TestContext.Current.CancellationToken).ShouldBe(1); + stream.BytesRead.ShouldBeLessThan(1000); + png.Length.ShouldBeGreaterThan(20_000); + } + + [Fact] + public void TheFallbackSaysWhy() + { + var png = PngTransparentColorTests.WithChunk(MagickPng(2, 8, interlace: true, 9, 7), "cICP"u8, [9, 16, 0, 1]); + Should.Throw(() => ReadAll(png, PixelFormat.Rgba32, out _)).Message.ShouldContain("PQ or HLG"); + } + + [Fact] + public void MemoryIsAFewRows_NotTheImage() + { + // 8192 × 4096 RGB: 96 MiB of pixels, a file of several megabytes; the reader holds a few rows. + const int w = 8192, h = 4096; + var pixels = Noise(w, h, 3, seed: 12, bits: 2); + var png = PngWriter.EncodeRgb8(pixels, w, h); + png.Length.ShouldBeGreaterThan(4 << 20); + var row = new byte[w * 3]; + var rowsRead = 0; + StreamingAssert.AllocatesLessThan(64 * 1024, () => + { + using var reader = PngImageDecoder.OpenRowReader(new ChunkedStream(png, maxChunk: 65536), PixelFormat.Rgb24); + for (var y = 0; y < h; y++) + rowsRead += reader.ReadRows(row, 1); // no assertion per row: Shouldly allocates + }, "a streamed 8192x4096 decode"); + rowsRead.ShouldBe(2 * h); + // And the rows are right: the last one equals the source. + using var check = PngImageDecoder.OpenRowReader(new MemoryStream(png), PixelFormat.Rgb24); + for (var y = 0; y < h; y++) + check.ReadRows(row, 1, cancellationToken: TestContext.Current.CancellationToken); + row.AsSpan().SequenceEqual(pixels.AsSpan((h - 1) * w * 3, w * 3)).ShouldBeTrue(); + } + + [Fact] + public async Task EndToEnd_AsyncFileStream_ReencodedRowsDecodeTheSame() + { + const int w = 211, h = 157; + var source = PngWriter.Encode(Gradient(w, h, alpha: true), w, h); + var path = Path.Combine(Path.GetTempPath(), $"png-stream-{Guid.NewGuid():N}.png"); + await File.WriteAllBytesAsync(path, source, TestContext.Current.CancellationToken); + try + { + byte[] rows; + await using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true)) + await using (var reader = await PngImageDecoder.OpenRowReaderAsync(new AsyncOnlyStream(file), PixelFormat.Rgba32, + cancellationToken: TestContext.Current.CancellationToken)) + { + reader.IsStreaming.ShouldBeTrue(); + rows = new byte[w * h * 4]; + var done = 0; + while (done < h) + done += await reader.ReadRowsAsync(rows.AsMemory(done * w * 4), 7, cancellationToken: TestContext.Current.CancellationToken); + } + var expected = new byte[w * h * 4]; + PngImageDecoder.TryDecodeInto(source, expected, 0, PixelFormat.Rgba32, cancellationToken: TestContext.Current.CancellationToken).ShouldBeTrue(); + rows.ShouldBe(expected); + var reencoded = PngWriter.Encode(rows, w, h); + var again = new byte[w * h * 4]; + PngImageDecoder.TryDecodeInto(reencoded, again, 0, PixelFormat.Rgba32, cancellationToken: TestContext.Current.CancellationToken).ShouldBeTrue(); + again.ShouldBe(expected); + } + finally + { + File.Delete(path); + } + } + + // ---------------------------------------------------------------- helpers + + /// + /// Asserts the streaming reader and agree on : the + /// same rows, or the reader throws where the span decode returns false (and only + /// there, but for the documented late-chunk refusal). Returns the span decode's verdict. + /// + internal static bool SameVerdict(byte[] data, PixelFormat format, string what, int seed = 1) + { + var ok = PngImageDecoder.TryReadInfo(data, out var info); + byte[]? expected = null; + if (ok) + { + expected = new byte[(long)info.Width * info.Height * format.BytesPerPixel]; + ok = PngImageDecoder.TryDecodeInto(data, expected, 0, format); + } + byte[] actual; + try + { + actual = StreamingAssert.ReadAll(data, StreamingAssert.Feed.RandomChunks, + input => PngImageDecoder.CreateRowReader(input, format, null), out _, out _, out _, seed); + } + catch (InvalidDataException e) + { + if (ok && !e.Message.StartsWith(PngReader.LateChunkMessage, StringComparison.Ordinal)) + throw new ShouldAssertException($"{what}: the span decode accepts it, the stream threw: {e.Message}"); + return ok; + } + catch (Exception e) + { + throw new ShouldAssertException($"{what}: the stream threw {e.GetType().Name}: {e.Message}\n{e.StackTrace}"); + } + if (!ok) + throw new ShouldAssertException($"{what}: the span decode refuses it, the stream decoded it."); + if (!actual.AsSpan().SequenceEqual(expected)) + throw new ShouldAssertException($"{what}: the rows differ from TryDecodeInto."); + return true; + } + + private static byte[] ReadAll(byte[] png, PixelFormat format, out bool streaming) => + StreamingAssert.ReadAll(png, StreamingAssert.Feed.RandomChunks, input => PngImageDecoder.CreateRowReader(input, format, null), + out streaming, out _, out _); + + internal readonly record struct ChunkRef(int Offset, string Type, int Length) + { + public int End => Offset + 12 + Length; + } + + internal static List ChunkStarts(byte[] png) + { + var list = new List(); + for (var pos = 8; pos + 12 <= png.Length;) + { + var length = (long)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos)); + if (pos + 12 + length > png.Length) + break; + list.Add(new ChunkRef(pos, System.Text.Encoding.Latin1.GetString(png, pos + 4, 4), (int)length)); + pos += 12 + (int)length; + } + return list; + } + + /// + /// A PNG built here byte by byte: seeded random samples (indices inside the palette), each row with a filter type of + /// its own (cycling through all five), the zlib stream cut into IDATs of . + /// + internal static byte[] HandBuilt(int colorType, int depth, int width, int height, int seed, int idatBytes = 8192, + bool trns = false, bool palette = true, Action? between = null, Action? after = null, bool iend = true) + { + var random = new Random(seed); + var spp = colorType switch { 0 => 1, 2 => 3, 3 => 1, 4 => 2, _ => 4 }; + var entries = colorType == 3 ? Math.Min(1 << depth, 200) : 0; + var rowBytes = (width * spp * depth + 7) / 8; + var bpp = Math.Max(1, spp * depth / 8); + var rows = new byte[height][]; + for (var y = 0; y < height; y++) + { + var row = new byte[rowBytes]; + for (var i = 0; i < width * spp; i++) + { + var max = colorType == 3 ? entries : 1 << Math.Min(depth, 8); + var v = random.Next(max); + if (depth == 16) + { + row[2 * i] = (byte)random.Next(256); + row[2 * i + 1] = (byte)random.Next(256); + } + else if (depth == 8) + row[i] = (byte)v; + else + row[i * depth / 8] |= (byte)(v << (8 - depth - i * depth % 8)); + } + rows[y] = row; + } + var raw = new MemoryStream(); + for (var y = 0; y < height; y++) + { + var filter = (byte)((y + seed) % 5); + raw.WriteByte(filter); + var above = y > 0 ? rows[y - 1] : new byte[rowBytes]; + for (var i = 0; i < rowBytes; i++) + { + int a = i >= bpp ? rows[y][i - bpp] : 0, b = above[i], c = i >= bpp ? above[i - bpp] : 0; + var p = filter switch { 1 => a, 2 => b, 3 => (a + b) / 2, 4 => Paeth(a, b, c), _ => 0 }; + raw.WriteByte((byte)(rows[y][i] - p)); + } + } + byte[] zlib; + using (var z = new MemoryStream()) + { + using (var zs = new ZLibStream(z, CompressionLevel.Optimal, leaveOpen: true)) + zs.Write(raw.ToArray()); + zlib = z.ToArray(); + } + + var ms = new MemoryStream(); + ms.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + var ihdr = new byte[13]; + BinaryPrimitives.WriteUInt32BigEndian(ihdr, (uint)width); + BinaryPrimitives.WriteUInt32BigEndian(ihdr.AsSpan(4), (uint)height); + ihdr[8] = (byte)depth; + ihdr[9] = (byte)colorType; + PngRgba8ExpansionTests.Chunk(ms, "IHDR"u8, ihdr); + PngRgba8ExpansionTests.Chunk(ms, "gAMA"u8, [0, 0, 0xB1, 0x8F]); + if (colorType == 3 && palette) + { + var plte = new byte[entries * 3]; + random.NextBytes(plte); + PngRgba8ExpansionTests.Chunk(ms, "PLTE"u8, plte); + } + if (trns) + { + byte[] t = colorType switch + { + 3 => [.. Enumerable.Range(0, entries / 2).Select(i => (byte)(i * 37))], + 0 => [0, (byte)(depth == 16 ? rows[0][1] : 1)], + _ => [0, rows[0][0], 0, rows[0][1], 0, rows[0][2]], + }; + if (colorType == 0 && depth == 16) + t = [rows[0][0], rows[0][1]]; + PngRgba8ExpansionTests.Chunk(ms, "tRNS"u8, t); + } + for (var o = 0; o < zlib.Length; o += idatBytes) + { + PngRgba8ExpansionTests.Chunk(ms, "IDAT"u8, zlib.AsSpan(o, Math.Min(idatBytes, zlib.Length - o))); + if (o == 0 && between is not null && zlib.Length > idatBytes) + between(ms); + } + after?.Invoke(ms); + if (iend) + PngRgba8ExpansionTests.Chunk(ms, "IEND"u8, []); + return ms.ToArray(); + } + + private static int Paeth(int a, int b, int c) + { + var p = a + b - c; + int pa = Math.Abs(p - a), pb = Math.Abs(p - b), pc = Math.Abs(p - c); + if (pa <= pb && pa <= pc) return a; + return pb <= pc ? b : c; + } + + /// An ImageMagick (libpng) PNG of the colour type and depth: foreign bytes. + internal static byte[] MagickPng(int colorType, int depth, bool interlace, int w, int h) + { + var levels = 1 << Math.Min(depth, 8); + using var image = new MagickImage(MagickColors.Black, (uint)w, (uint)h); + if (colorType is 4 or 6) + image.Alpha(AlphaOption.Set); + using (var pixels = image.GetPixels()) + { + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var k = (x * 7 + y * 3) % (colorType == 3 ? Math.Max(1, Math.Min(levels - 1, 200)) : levels); + var v = (float)(k * (double)Quantum.Max / (levels - 1)); + float[] px = colorType switch + { + 0 => [v, v, v], + 4 => [v, v, v, (float)((x * 13 % 256) * (double)Quantum.Max / 255)], + 3 => [(float)(k * 37 % 256 * (double)Quantum.Max / 255), (float)((255 - k * 53 % 256) * (double)Quantum.Max / 255), (float)(k * 91 % 256 * (double)Quantum.Max / 255)], + 2 => [v, (float)((x * 9 % 256) * (double)Quantum.Max / 255), (float)((y * 5 % 256) * (double)Quantum.Max / 255)], + _ => [v, (float)((x * 9 % 256) * (double)Quantum.Max / 255), (float)((y * 5 % 256) * (double)Quantum.Max / 255), (float)((x * y % 256) * (double)Quantum.Max / 255)], + }; + pixels.SetPixel(x, y, px); + } + } + } + if (colorType == 3) + image.ColorType = ColorType.Palette; + if (interlace) + image.Settings.Interlace = Interlace.Png; + image.Settings.SetDefine(MagickFormat.Png, "bit-depth", depth.ToString(System.Globalization.CultureInfo.InvariantCulture)); + image.Settings.SetDefine(MagickFormat.Png, "color-type", colorType.ToString(System.Globalization.CultureInfo.InvariantCulture)); + return image.ToByteArray(MagickFormat.Png); + } + + internal static byte[] Gradient(int w, int h, bool alpha) + { + var c = alpha ? 4 : 3; + var p = new byte[w * h * c]; + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) + { + var i = (y * w + x) * c; + p[i] = (byte)(x * 255 / w); + p[i + 1] = (byte)(y * 255 / h); + p[i + 2] = (byte)((x ^ y) & 0xFF); + if (alpha) + p[i + 3] = (byte)((x + y) % 256); + } + return p; + } + + // A smooth gradient with `bits` low bits of seeded noise per sample: compresses, but not to nothing. + internal static byte[] Noise(int w, int h, int channels, int seed, int bits = 8) + { + var p = new byte[(long)w * h * channels]; + new Random(seed).NextBytes(p); + var mask = (1 << bits) - 1; + for (long i = 0; i < p.Length; i++) + { + var x = (int)(i / channels % w); + p[i] = (byte)(((x >> 5) & ~mask) | (p[i] & mask)); + } + return p; + } + + /// A stream whose synchronous reads throw, as an ASP.NET Core request body's do. + private sealed class AsyncOnlyStream(Stream inner) : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Synchronous operations are disallowed."); + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + inner.ReadAsync(buffer[..Math.Min(buffer.Length, 1500)], cancellationToken); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + if (disposing) + inner.Dispose(); + base.Dispose(disposing); + } + } +} + +/// +/// The streaming PNG reader on untrusted input: seeded mutations of a corpus (hand-built files of every layout, +/// ImageMagick's, ours) — random bytes, bytes with CRCs put right, IHDR fields set to values that break arithmetic, +/// chunks deleted, repeated, swapped, moved past IDAT — read through the stream either give exactly +/// 's rows or fail with where it returns +/// false; never another exception or a hang. Iterations: PNG_STREAM_FUZZ_ITERATIONS (default 2000), seed: +/// PNG_STREAM_FUZZ_SEED. +/// +public sealed class PngStreamingRobustnessTests +{ + private const long MaxPixels = 1L << 20; + + private static int Iterations => int.TryParse(Environment.GetEnvironmentVariable("PNG_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 2000; + + private static int Seed => int.TryParse(Environment.GetEnvironmentVariable("PNG_STREAM_FUZZ_SEED"), out var n) ? n : 20261123; + + private static readonly uint[] Interesting = [0, 1, 2, 3, 7, 8, 255, 256, 65535, 65536, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF]; + + private static List Seeds() + { + var seeds = new List(); + var k = 0; + foreach (var (colorType, depth) in new[] { (0, 1), (0, 4), (0, 16), (2, 8), (2, 16), (3, 2), (3, 8), (4, 8), (6, 8), (6, 16) }) + { + seeds.Add(PngStreamingDecodeTests.HandBuilt(colorType, depth, 11, 7, seed: ++k, idatBytes: 23, trns: colorType is 0 or 2 or 3, + after: s => PngRgba8ExpansionTests.Chunk(s, "tEXt"u8, "k\0v"u8))); + } + seeds.Add(PngStreamingDecodeTests.MagickPng(2, 8, interlace: false, 17, 9)); + seeds.Add(PngStreamingDecodeTests.MagickPng(3, 4, interlace: true, 9, 9)); + seeds.Add(PngWriter.Encode(PngStreamingDecodeTests.Gradient(23, 13, alpha: true), 23, 13)); + return seeds; + } + + [Fact] + public void Seeds_stream_and_survive_mutation() + { + var seeds = Seeds(); + foreach (var seed in seeds) + PngStreamingDecodeTests.SameVerdict(seed, PixelFormat.Rgba32, "seed").ShouldBeTrue(); + + var rng = new Random(Seed); + var clock = Stopwatch.StartNew(); + PixelFormat[] formats = [PixelFormat.Rgba32, PixelFormat.Rgb24, PixelFormat.Rgba64, PixelFormat.GrayAlpha16]; + for (var i = 0; i < Iterations; i++) + { + var data = Mutate(seeds[rng.Next(seeds.Count)], rng, out var how); + if (data.Length >= 24) + { + var w = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(16)); + var h = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(20)); + if ((long)w * h > MaxPixels) + { + // Too large for the span decode's buffer here; the stream must still fail cleanly or decode rows. + StreamOnly(data, $"{how}, iteration {i}, seed {Seed}"); + continue; + } + } + PngStreamingDecodeTests.SameVerdict(data, formats[rng.Next(formats.Length)], $"{how}, iteration {i}, seed {Seed}", seed: i); + } + clock.Elapsed.ShouldBeLessThan(TimeSpan.FromMinutes(30)); + } + + // A header too large to decode whole: the reader may only throw InvalidDataException, reading a few rows. + private static void StreamOnly(byte[] data, string what) + { + try + { + using var reader = PngImageDecoder.CreateRowReader(new StreamInput(new ChunkedStream(data, maxChunk: 64)), PixelFormat.Rgba32, null); + reader.Initialize(TestContext.Current.CancellationToken); + if ((long)reader.Width * 4 > 1 << 24) + return; + var row = new byte[reader.Width * 4]; + for (var y = 0; y < Math.Min(reader.Height, 4); y++) + reader.ReadRows(row, 1, cancellationToken: TestContext.Current.CancellationToken); + } + catch (InvalidDataException) + { + } + catch (Exception e) + { + throw new ShouldAssertException($"{what}: the stream threw {e.GetType().Name}: {e.Message}\n{e.StackTrace}"); + } + } + + private static byte[] Mutate(byte[] seed, Random rng, out string how) + { + var data = (byte[])seed.Clone(); + var chunks = PngStreamingDecodeTests.ChunkStarts(data); + switch (rng.Next(8)) + { + case 0: + how = "random bytes"; + for (var k = rng.Next(1, 5); k > 0; k--) + data[rng.Next(data.Length)] = (byte)rng.Next(256); + return data; + case 1: + how = "random bytes, CRCs fixed"; + for (var k = rng.Next(1, 5); k > 0; k--) + data[rng.Next(8, data.Length)] = (byte)rng.Next(256); + FixCrcs(data); + return data; + case 2: + { + how = "IHDR field"; + var at = 16 + 4 * rng.Next(3); + if (at == 24) + data[24 + rng.Next(5)] = (byte)rng.Next(rng.Next(2) == 0 ? 20 : 256); + else + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(at), rng.Next(3) == 0 ? (uint)rng.Next(70) : Interesting[rng.Next(Interesting.Length)]); + FixCrcs(data); + return data; + } + case 3: + { + how = "chunk deleted"; + var c = chunks[rng.Next(chunks.Count)]; + return [.. data[..c.Offset], .. data[c.End..]]; + } + case 4: + { + how = "chunk repeated"; + var c = chunks[rng.Next(chunks.Count)]; + return [.. data[..c.End], .. data[c.Offset..c.End], .. data[c.End..]]; + } + case 5: + { + how = "chunks swapped"; + if (chunks.Count < 3) + goto case 0; + var i = rng.Next(chunks.Count - 1); + var (a, b) = (chunks[i], chunks[i + 1]); + return [.. data[..a.Offset], .. data[b.Offset..b.End], .. data[a.Offset..b.Offset], .. data[b.End..]]; + } + case 6: + { + how = "chunk moved to the end"; + var c = chunks[rng.Next(chunks.Count)]; + var rest = (byte[])[.. data[..c.Offset], .. data[c.End..]]; + var last = PngStreamingDecodeTests.ChunkStarts(rest).LastOrDefault(); + var at = last.Type == "IEND" ? last.Offset : rest.Length; + return [.. rest[..at], .. data[c.Offset..c.End], .. rest[at..]]; + } + default: + how = "cut"; + return data[..rng.Next(data.Length)]; + } + } + + private static void FixCrcs(byte[] data) + { + foreach (var c in PngStreamingDecodeTests.ChunkStarts(data)) + { + var crc = PngCrc32.Compute(data.AsSpan(c.Offset + 4, 4), data.AsSpan(c.Offset + 8, c.Length)); + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(c.Offset + 8 + c.Length), crc); + } + } +}