Skip to content

Jpeg: true streaming decode from forward-only streams - #16

Merged
sdcb merged 2 commits into
mainfrom
streaming/jpeg-decode
Nov 23, 2026
Merged

sdcb merged 2 commits into
mainfrom
streaming/jpeg-decode

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Summary

  • JpegImageDecoder implements IStreamingImageDecoder; Registration.CreateRowReader is set by method group. New public OpenRowReader(Stream, PixelFormat, DecodeOptions?, bool leaveOpen) and OpenRowReaderAsync(...) (PublicAPI.Unshipped.txt updated).
  • JpegRowReader (new, internal) drives JpegCore over StreamInput.Buffered. A sequential frame whose first scan interleaves every component streams MCU row by MCU row through the existing two-MCU-row strips. DCT-domain scales 2/4/8 stream too. Progressive, multi-scan, no-scan frames, Region, ApplyOrientation and scales above 8 use UseBufferedFallback (IsStreaming == false).
  • How resumption works: the engine state lives in JpegCore.Suspended between calls. Each MCU row, and each marker step after the scan, is one unit. Before a unit the code checkpoints the bit buffer and count, position, DC predictors, restart counter, EOB run, marker and nomore state. If the unit read past the buffered window and the stream has not ended, it rolls back and returns NeedMoreData. Reads past the window are detected by a new _overrun flag set in Get8 / Skip / AtEnd. The 8-byte fast refill already stops at _data.Length - 8, so it never reads past the window. Once the stream has ended, reads past the end are the same zeros a whole decode reads, so salvage and truncation behaviour match TryDecodeInto exactly. The last row is held back until the trailing markers are parsed.
  • Output goes into the caller's band. EmitRows stops at _emitLimit (which is OutY for the span decode), and rows not yet asked for stay pending in the strips.
  • Changes to the span path: _overrun bookkeeping, the _emitLimit / _destY0 row offset, and the per-MCU-row body of DecodeStreamingScan factored out. Nothing touches JpegIdct, JpegResample or JpegColor.
  • JpegCore is now partial; its instance fields stay in JpegCore.cs. A reflection test makes sure every field has a namesake in Suspended.
  • Review fix: an APP14 or JFIF segment between SOF and SOS does not change the colour transform, matching the whole decode, which picks it at SOF. A test covers this and was confirmed to fail without the fix.
  • Benchmark: AbBenchmarks.Streaming (16-row bands from a MemoryStream). Before timing it checks that its output equals DecodeTo byte for byte, and the result table gains a streaming ÷ current column.

Tests

  • JpegStreamingDecodeTests:
    • Every JpegDecoderOracleTests case (all subsamplings, gray, CMYK/YCCK, restarts, non-interleaved, progressive, truncated salvage) × 8 PixelFormats (incl. Gray8, GrayAlpha16, Rgba64, premultiplied) × every StreamingAssert feed, plus 1/2 scale. Encoder variants (restart 1/7, optimized Huffman, gray, 16×16, 67×1, 4:2:2, 4:1:1) at 1/1, 1/4 and 1/8.
    • Fallbacks are checked explicitly.
    • Exif orientation is reported in Info.
    • Reading the first row reads less than half the stream.
    • Truncation at every byte: either the same salvaged pixels or InvalidDataException, exactly where TryDecodeInto fails.
    • A 5000×8000 image allocates less than 1/8 of the image.
    • End-to-end test: a FileStream wrapped async-only through OpenRowReaderAsync / ReadRowsAsync.
  • JpegFuzzTests.MutatedStreams_StreamingMatchesDecodeInto: the reader must match TryDecodeInto exactly when it succeeds and throw InvalidDataException when it fails, over random scales, formats and feeds. Iterations come from JPEG_STREAM_FUZZ_ITERATIONS, falling back to JPEG_FUZZ_ITERATIONS.
  • I broke the code on purpose to check the tests catch it: with the overrun flag disabled 65 tests fail, and with the last-row holdback removed the stream fuzzer fails.
  • Full suite passes (7136, 0 failed). DOTNET_EnableAVX2=0 and DOTNET_EnableHWIntrinsic=0 runs of the JPEG classes pass. No new warnings. Goldens untouched.

Soaks (both ran clean at 300000):

JPEG_FUZZ_ITERATIONS=300000 JPEG_STREAM_FUZZ_ITERATIONS=300000 dotnet test tests/Sdcb.SimdCodecs.Tests -c Release --filter "FullyQualifiedName~JpegFuzz"

Perf (AMD Ryzen 7 5800X, Windows 11 26200, .NET 10.0.15, AVX2, no AVX-512; baseline 533b03e + ab, run from a worktree outside the repo)

Geomean over the quick subset: span decode current ÷ baseline 0.98×, streaming ÷ current 1.03×. The progressive file is the buffered fallback and comes out at 1.19×. The machine was shared with other agents, so single files swing ±10% between runs. In an earlier run, before streaming waited for about 1.5× the previous MCU row's bytes before starting the next row, streaming was 1.08×.

Needs outside this unit

  • AGENTS.md soak line could name JPEG_STREAM_FUZZ_ITERATIONS (it follows JPEG_FUZZ_ITERATIONS when unset, so the existing command already soaks it).
  • StreamingRowReader has no way to pass the caller's CancellationToken into the codec step. The JPEG reader therefore writes at most 256 rows per DecodeRows call, so the driver checks the token between calls.

🤖 Generated with Claude Code

sdcb and others added 2 commits November 23, 2026 19:41
JpegImageDecoder implements IStreamingImageDecoder (Registration.CreateRowReader),
plus OpenRowReader / OpenRowReaderAsync over a Stream. A sequential frame whose first
scan interleaves every component is decoded as it arrives, MCU row by MCU row, with the
existing two-MCU-row strips; rows go to the caller's band and the rest stay pending in
the strips. Each MCU row (and each marker step after the scan) is a unit: the entropy
state is checkpointed before it and rolled back when it read past the buffered input
and the stream has not ended, so the rows equal TryDecodeInto's byte for byte.
DCT-domain scales 2/4/8 stream too; progressive, multi-scan, region, orientation and
larger scales take the buffered fallback.

The span decode keeps its arithmetic and sequence: reads past the data now also set an
overrun flag, EmitRows stops at a row limit (OutY for a whole decode), and the
streaming scan's per-MCU-row body is factored out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g the next

A row started near the end of the buffered input is usually undone and decoded again;
waiting for about one row's worth of input first avoids the wasted work.

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