Repository navigation
Png: streaming row reader (forward-only stream, bounded memory) - #18
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Unit 2 of the streaming batch: true forward-only streaming decode for PNG.
What
PngImageDecoderimplementsIStreamingImageDecoder;Registration.CreateRowReaderis set (bound by method group). New public API:CreateRowReader,OpenRowReader(Stream, PixelFormat, DecodeOptions?, bool leaveOpen)andOpenRowReaderAsync(both read the header; a failed open disposes the stream unlessleaveOpen).ReadHeaderreads them (its dispatch moved into a sharedHeaderBuilder, no behaviour change).InfoisTryReadInfoover that prefix, so aneXIf/cICP/gAMA/iCCP/pHYsafter IDAT is not in it (documented).ZLibStreamover anIdatWalkerthat serves the IDAT payloads straight out of theStreamInputwindow, 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 underSystem.IO.Compression.UseStrictValidationit 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 asDecodeInto(basic 8-bit formats) orDecodeWindow(the rest) does. The last row is held back until the rest of the file is checked.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.InvalidDataException(PngReader.LateChunkMessage) whereTryDecodeIntohonours the chunk. A late tRNS read to a format without alpha streams with equal rows.DeflateInflate(iCCP / zTXt / iTXt) now turns zlib'sIOExceptionintoInvalidDataException. This was a pre-existing gap in the span path, found in review.Tests
PngStreamingDecodeTests:StreamingAssertfeed.TryDecodeInto.FileStreamend-to-end (rows re-encoded and re-decoded).PngStreamingRobustnessTests: a mutation fuzzer that checks the stream against the span decode (same rows, orInvalidDataExceptionexactly 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):
DOTNET_EnableAVX2=0andDOTNET_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).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)OpenRowReaderover a forward-only stream, all rows) vs spanTryDecodeIntoRgba8: 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×.Not changed / for the coordinator
src/Sdcb.SimdCodecs/ImageCodecs.csneeds nothing for this unit; the facade only needsRegistration.CreateRowReader.StreamingRowReader.DecodeFallbackrentsWidth × Height × bppbefore calling the codec's decoder. The PNG fallback header therefore runs the spanReadHeader(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