Skip to content

Pnm: streaming row reader (P1–P7) and streaming encoder session - #13

Merged
sdcb merged 1 commit into
mainfrom
streaming/pnm
Nov 23, 2026
Merged

sdcb merged 1 commit into
mainfrom
streaming/pnm

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

What

  • PnmImageDecoder implements IStreamingImageDecoder (Registration.CreateRowReader set by method group). It covers P1–P7: plain and raw, 8 and 16 bits, every PixelFormat.
    • The header is scanned as it arrives. The scan resumes where the previous call stopped, so a long comment fed a byte at a time is scanned once. Once the last field and its terminator are buffered, PnmHeader.Read parses the header exactly as it does from the whole file. Streaming caps the header at 1 MiB, comments included; a longer header throws InvalidDataException.
    • Raw rows decode once all their bytes are buffered, through the same Source8 / chunk kernels as TryDecodeInto (new PnmPixels.DecodeRawRow). 16-bit samples into a 16-bit layout go through native samples and ConvertRow, as the span path's fallback does.
    • Plain rasters are read token by token. The number, comment and sample-index state carries across reads, so a token never splits and a comment is never buffered. The sample scratch grows with the samples that arrive, never to the width the header declares.
    • Acceptance matches the span decoder. Bytes after the last row are never read, a short raster throws InvalidDataException, and a trailing number at end of stream is accepted.
    • Options other than the full image use UseBufferedFallback. PFM has no streaming reader: it is a separate registration, so the facade buffers it.
  • PnmImageEncoder.Create always returns a StreamingEncoderSession. The header is written at AddFrame and each band's raster as it is written. The bytes equal the whole-image encode for any split, because every Netpbm row is encoded on its own. A consequence: an option the input cannot be written with now throws at AddFrame instead of at Commit.
  • New public API: PnmImageDecoder.CreateRowReader (in PublicAPI.Unshipped.txt). The README has a new Streaming section.

Tests

  • PnmStreamingTests:
    • Rows equal TryDecodeInto for every P1–P7 variant at maxima 255 / 7 / 300 / 1000 / 4095 / 65535, for 8- and 16-bit input, across PixelFormat.All and every StreamingAssert feed.
    • Hand-written files cover comments everywhere, CR line ends, leading zeros, samples above the maximum, trailing data, a second image, and raw rasters that start with 0x20 / 0x23.
    • Magick.NET files (foreign bytes) decode the same streamed as from a span.
    • Every truncation is accepted or refused exactly as the span decoder does. Malformed headers and rasters throw InvalidDataException.
    • A row too wide for a buffer throws InvalidDataException, not OverflowException.
    • Memory stays bounded: 8192×4096 raw grey and RGB, and 2048×512 plain, each read in under 256 KB of allocation. 8192×4096 encodes in under 256 KB.
    • Encoder bytes equal the buffered encode for every option × PixelFormat with random strided bands. EncoderEmitsBeforeCommit passes.
    • End to end: an async-only ChunkedStream is decoded with ReadRowsAsync and piped into the streaming encoder, which reproduces the source file byte for byte (P6, 16-bit P5, P3).
  • PnmStreamingRobustnessTests adds a streaming fuzz with its own soak variable. For each mutation, the streamed rows must equal the span decoder's, or the stream must throw InvalidDataException where the span decoder refuses.
  • I broke the code deliberately to confirm the tests catch it: a plain-sample scaling bug fails 6 tests, and a full-row scratch fails the allocation test.

Runs on an AMD Ryzen 7 5800X, Windows 11, .NET 10.0.15:

  • Full suite: 7073 tests, 0 failures (559 oracle skips, the same as on main).
  • DOTNET_EnableAVX2=0 and DOTNET_EnableHWIntrinsic=0: all 164 PNM tests pass.
  • Soaks: PNM_STREAM_FUZZ_ITERATIONS=300000 QOI_FUZZ_ITERATIONS=300000 PNM_FUZZ_ITERATIONS=300000 … --filter "FullyQualifiedName~PnmStreamingRobustness|FullyQualifiedName~QoiPnmRobustness" passes.
  • The build adds no new warnings.

Please add to AGENTS.md (I did not edit it): after touching the PNM streaming reader, soak PNM_STREAM_FUZZ_ITERATIONS=300000 … --filter "FullyQualifiedName~PnmStreamingRobustness".

Benchmark

QoiPnm matrix against a freshly built baseline 533b03e, run from a detached worktree outside the repo. Same machine, 1920×1080, medians of 15 interleaved rounds, ms. New contestants: "PNM row reader" (CreateRowReader over a MemoryStream, 16 rows per call, into RGBA) and "PNM streaming session" (16-row bands into a reused ArrayBufferWriter).

Decode span TryDecodeInto row reader ratio
photo-ppm 0.717 0.820 1.14×
photo-pgm 0.775 0.814 1.05×
photo-pbm 0.966 0.948 0.98×
photo-ppm16 1.200 1.364 1.14×
photo-ppm-plain 45.3 49.0 1.08×
photo-pam-rgba 0.297 0.480 1.62×
screen-ppm 1.138 1.414 1.24×

The streaming decode does not meet the 1.05× target on the raw formats that are pure copies. The added cost is one copy of the file from the Stream into the StreamInput buffer, which a span decode of bytes already in memory skips. About 0.18 ms of the PAM case is that copy (8 MB at memory bandwidth). PBM, PGM and plain rasters are within 1.05–1.08×.

Encode Encode → stream streaming session
photo-ppm 0.117 0.125
photo-pam-rgba 0.168 0.183
photo-ppm16 0.736 0.401
photo-ppm-plain 22.9 21.6

The session matches the Stream overload, and is faster for 16-bit because it skips the whole-image conversion buffer.

Regression check:

  • The span decode is unchanged in its hot path. The baseline's decode entry point is not found by the existing harness (its signature predates this branch), so the baseline decode column is empty both on main and here.
  • Encode current against baseline (a new array per call) is within run-to-run noise. Over 31 rounds: photo-ppm 0.755 vs 0.719, screen-pgm 0.277 vs 0.270, screen-pam 0.807 vs 0.819.

🤖 Generated with Claude Code

PnmImageDecoder implements IStreamingImageDecoder. The header is scanned
as it arrives (resumable, at most 1 MiB) and then parsed by PnmHeader.Read
as from the whole file; raw rows decode once their bytes are buffered,
through the same chunk kernels as TryDecodeInto; plain rasters are read
token by token with the number / comment state carried across reads.
Non-full options take the buffered fallback. Rows equal TryDecodeInto's,
with the same acceptance (trailing data ignored, short rasters refused).

PnmImageEncoder.Create now returns a StreamingEncoderSession for every
option: the header at AddFrame, each band's raster as it is written; the
bytes equal the whole-image encode for any split.

Tests: PnmStreamingTests (every variant x PixelFormat x feed, Magick.NET
files, truncations, malformed input, memory bounds, encoder bytes,
emits-before-commit, async end to end) and PnmStreamingRobustnessTests
(PNM_STREAM_FUZZ_ITERATIONS). QoiPnm benchmark: row reader and streaming
session contestants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sdcb
sdcb merged commit d7446c4 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