Skip to content

Png: streaming row reader (forward-only stream, bounded memory) - #18

Merged
sdcb merged 1 commit into
mainfrom
streaming/png-decode
Nov 23, 2026
Merged

sdcb merged 1 commit into
mainfrom
streaming/png-decode

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Unit 2 of the streaming batch: true forward-only streaming decode for PNG.

What

  • PngImageDecoder implements IStreamingImageDecoder; Registration.CreateRowReader is set (bound by method group). New public API: CreateRowReader, OpenRowReader(Stream, PixelFormat, DecodeOptions?, bool leaveOpen) and OpenRowReaderAsync (both read the header; a failed open disposes the stream unless leaveOpen).
  • Header: the chunks before the first IDAT, read exactly as ReadHeader reads them (its dispatch moved into a shared HeaderBuilder, no behaviour change). Info is TryReadInfo over that prefix, so an eXIf / cICP / gAMA / iCCP / pHYs after IDAT is not in it (documented).
  • Rows: one ZLibStream over an IdatWalker that serves the IDAT payloads straight out of the StreamInput window, checks each chunk's CRC as it ends, and reads the chunks between and after the IDATs up to IEND (or EOF at a chunk boundary) with the span decode's strictness. Chunks the header builder skips are passed over without being held. When the window runs dry inside a row, the walker throws a private exception, which unwinds the inflater without losing state. Returning 0 there would read as end of data, and under System.IO.Compression.UseStrictValidation it throws "truncated"; I checked both modes. Retries back off: twice the average compressed row, doubling after a dry run. Rows are unfiltered and converted exactly as DecodeInto (basic 8-bit formats) or DecodeWindow (the rest) does. The last row is held back until the rest of the file is checked.
  • Fallback (IsStreaming == false, TryDecodeInto's result plus its reason): Adam7, acTL, indexed with PLTE after IDAT, PQ/HLG cICP read to 8-bit samples, non-full options.
  • One documented divergence: a PLTE (indexed), a tRNS (formats with alpha) or a PQ/HLG cICP (8-bit) after IDAT changes rows that are already written. The spec puts these chunks before IDAT. The stream throws InvalidDataException (PngReader.LateChunkMessage) where TryDecodeInto honours the chunk. A late tRNS read to a format without alpha streams with equal rows.
  • DeflateInflate (iCCP / zTXt / iTXt) now turns zlib's IOException into InvalidDataException. This was a pre-existing gap in the span path, found in review.
  • Memory: two rows, the working rows, the inflater, and a small input window. A warm 8192×4096 RGB decode (36 MB file) allocates under 64 KiB of managed memory. Row buffers are allocated only once the input could inflate to a row (the 1032:1 limit), so a forged IHDR costs nothing.

Tests

PngStreamingDecodeTests:

  • Hand-built files of every colour type and depth, with and without tRNS, every filter type, × 12 pixel formats × every StreamingAssert feed.
  • ImageMagick (libpng) files, our encoder's files, 1-byte IDATs, IDATs interleaved with other chunks, missing IEND.
  • Fallbacks (Adam7, APNG, options) with equal rows.
  • Every truncation, and bad CRCs or payload bytes in every chunk, giving the same verdict as TryDecodeInto.
  • Prefix-only reads, a row coming out once its bytes arrive, the memory bound, and an async-only FileStream end-to-end (rows re-encoded and re-decoded).
  • PngStreamingRobustnessTests: a mutation fuzzer that checks the stream against the span decode (same rows, or InvalidDataException exactly where it returns false).

I broke the walker's CRC check on purpose and the tests caught it.

Soak (passed at 300000 with two seeds):

PNG_STREAM_FUZZ_ITERATIONS=300000 dotnet test tests/Sdcb.SimdCodecs.Tests -c Release --filter "FullyQualifiedName~PngStreamingRobustness"
PNG_STREAM_FUZZ_ITERATIONS=300000 PNG_STREAM_FUZZ_SEED=7 ...
  • Full suite: 7082 tests, 0 failures.
  • DOTNET_EnableAVX2=0 and DOTNET_EnableHWIntrinsic=0: every Png*/Apng* test (1687) passes.
  • REQUIRE_ORACLES=1: no PNG/APNG failures. The failures are oracles whose tools are missing on this machine (dwebp, OpenJPEG, jbig2dec).
  • Build: no warnings. Goldens untouched.

Benchmark (AMD Ryzen 7 5800X, Windows 10.0.26200, .NET 10.0.15, AVX2; 1920×1080 ImageSharp-encoded inputs; synthetic photo source; baseline 533b03e + matrix decode, 9 interleaved rounds)

  • Span decode vs baseline (main): geomean 1.00× photo, 1.01× screen. Two first-run outliers (photo-rgb16 1.08×, screen-rgba8 1.12×) re-ran at 0.99–1.01× over 15 rounds, twice. That is noise: the span path changed only in header parsing.
  • Streaming (OpenRowReader over a forward-only stream, all rows) vs span TryDecodeIntoRgba8: geomean 1.022× photo, 0.987× screen. Every non-interlaced case is ≤ 1.05×, except screen-rgba8 (85 KB file, 2.1 ms), which re-ran at 1.05× and 1.08×. On a 2 ms decode, the fixed cost (64 KiB input buffer, reader and inflater setup) and the per-row copy matter. The span path inflates RGBA8 straight into the caller's buffer, which a resumable reader cannot do safely. photo-rgba8 is 1.03×.
  • photo-rgba8-adam7 (fallback, not streaming) is 1.17×: the file is read whole into the input buffer, then the frame is copied out.

Not changed / for the coordinator

  • src/Sdcb.SimdCodecs/ImageCodecs.cs needs nothing for this unit; the facade only needs Registration.CreateRowReader.
  • Foundation note (Abstractions, not touched): StreamingRowReader.DecodeFallback rents Width × Height × bpp before calling the codec's decoder. The PNG fallback header therefore runs the span ReadHeader (including its 1032:1 check) first, so a forged IHDR cannot reach that allocation. Other codecs' fallbacks should do the same.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
@sdcb
sdcb merged commit 0e341fa into main Nov 23, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant