Repository navigation
PNG: streaming encoder session (IDATs per band, bounded memory) - #17
Merged
Merged
Conversation
PngImageEncoder.Create now returns a StreamingEncoderSession for a still image: signature, IHDR and the pre-IDAT chunks at AddFrame, each band of rows filtered and deflated as it arrives and emitted as complete 64 KiB IDAT chunks, the trailing chunks and IEND at Commit. Memory is a band of rows. With ParallelFragments the bands are PngWriter's fragments (capped at 2 MiB of rows) compressed on min(ParallelFragments, ProcessorCount) workers and emitted in order. The zlib stream equals PngWriter's (serial, and parallel up to the cap); only the IDAT packaging differs, +12 bytes per 64 KiB (+0.018%). A file whose zlib stream fits 64 KiB is byte-identical. Band boundaries depend only on the image size and options, never on WriteRows chunking. LosslessReduction, Quantize and the new PngWriteOptions.Animation keep the buffered session (IsStreaming false, bytes unchanged). API break: a session of several frames (APNG) now needs Animation = true; without it a PNG session holds one frame. 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.
What
PngImageEncoder.Createreturns a streaming session (StreamingEncoderSession) for a still image:AddFrame: signature, IHDR and every pre-IDAT chunk are written, after all option checks (bad text keyword,TransparentColoron an alpha layout, undefinedCompressionLevelthrow before any byte reaches the writer).WriteRows: rows are converted to the native layout (BGR→RGB, premultiplied→straight) into a fixed band, filtered with the existingPngWriter.CompressRows, deflated, and emitted as completeIDATchunks of 64 KiB as soon as each fills.Commit: last IDAT, eXIf / iTXt, IEND.ParallelFragments > 1: each band is one ofPngWriter's fragments (ceil(height / fragments)rows), capped at 2 MiB of filtered rows. Bands compress onmin(ParallelFragments, ProcessorCount)workers into sync-flushed deflate fragments and are emitted in order. The Adler-32 is combined, as the buffered fragmented path does.WriteRows(tested: one row at a time, random bands, whole, strided).New file
src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs.PngWriteronly had three private helpers made internal; its output is unchanged.Byte-level difference of the default path (please review)
The default options now stream, so default session output changes:
PngWriter's, in the serial path and in the parallel path up to the 2 MiB cap. The filter and deflate calls see the same rows in the same order.PngWriterwrites one IDAT, with its length back-patched. The session writes one IDAT per 64 KiB of zlib stream, which costs 12 bytes per chunk: +0.018% size (1.00018× on every 1920×1080 benchmark case).PngWriter's. This is whyASessionOfOneFrameIsTheStillPngByteForBytestill passes.PngWriterdoes, so those bytes differ. The size stays within 0.1%, and this is tested.API break: multi-frame sessions need
PngWriteOptions.AnimationAn APNG's
acTL(frame count) must come before the first IDAT, so a session that streams frame 0 cannot later become an animation. I addedPngWriteOptions.Animation(bool, default false):Animation = trueselects the buffered session: several frames, APNG, same bytes as before.MaxFrames == 1, also withLosslessReduction/Quantize, so the frame limit does not depend on unrelated options).Break: code from 2.0 that adds several frames to a default-options PNG session now gets
InvalidOperationExceptionon the secondAddFrame. This needs a line in the release notes. I updated the two in-repo callers (PngApngEncoderTests,AotSmoke/FacadeSmoke). The alternative was to keep the buffered session as the default, which would leave the facade (ImageCodecs.Encode) without streaming. I judged the streaming default the better trade, but this is your call.Fallbacks (
IsStreaming == false, bytes identical to before, tested):LosslessReduction,Quantize,Animation.Mid-call cancellation: a
WriteRowswhose token is already cancelled consumes nothing. A token cancelled while the call runs is checked at each band. In that case, or on any other failure part-way through, the session refuses further calls exceptDispose.Disposewaits for in-flight workers before it returns pooled memory, and writes nothing more.Tests (
tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs)PixelFormat.Allentry decodes, through our decoder and through libpng via Magick.NET, to exactly the converted input. Covered at small sizes (default, store, parallel) and at 1031×700 (many IDATs, two parallel bands).EncoderEmitsBeforeCommit, serial and parallel.WriteRowssplit. A small file is byte-identical toPngWriter's. A large file carriesPngWriter's zlib stream in 64 KiB IDATs. Parallel bands equal the buffered fragments up to the cap.MaxFramesis as described, and bad options are refused before any byte is written.AllocatesLessThan.FileStream-backed writer. The test checks the file grows while rows arrive, that noGetSpanasks for more than 1 MiB, and that the file decodes to exact pixels.Runs: full suite 7084 tests, 0 failed. Png classes with
REQUIRE_ORACLES=1,DOTNET_EnableAVX2=0andDOTNET_EnableHWIntrinsic=0: 1689 tests each, 0 failed, 0 skipped. NativeAOT smoke: output identical to JIT. The Wasm smoke was not run; the facade itself is unchanged.Benchmark (AMD Ryzen 7 5800X, 16 threads, Windows 11, .NET 10.0.15, 1920×1080, synthetic sources)
New contestants
streaming/streaming parallelpush rows 16 at a time through the session, with their own table inmatrix encode. BDN methods were added too. The run wasbaseline HEAD(main 533b03e) followed bymatrix encode --rounds 7; the full report is inbenchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md.PngWritercode is unchanged; individual cases scatter 0.85–1.20× because other agents' builds were running on the machine.MemoryStreamandToArraycopy is needed. Size is 1.00018×.matrixA/B against the freshly built baseline, because this benchmark has noabcommand. A BDN run is not included.For the coordinator / facade
No facade or Abstractions change is needed. The facade's
ImageCodecs.CreateEncoder(ImageFormat.Png, …)andEncodestream automatically. A facade caller who wants an APNG passesnew PngWriteOptions { Animation = true }.🤖 Generated with Claude Code