Skip to content

Jpeg: streaming encode for baseline with the standard tables - #11

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

sdcb merged 2 commits into
mainfrom
streaming/jpeg-encode

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

JPEG streaming encode (unit 5 of the streaming batch).

What changes

  • JpegImageEncoder.Create returns a StreamingEncoderSession for baseline encoding with the Annex K tables, which covers every JpegEncodeOptions field except OptimizeHuffman and Progressive (Quality, Subsampling, RestartInterval, Exif, Xmp, IccProfile and frame metadata all stream). The headers go out at AddFrame. Each MCU row (8 rows, or 16 for 4:2:0) is converted, transformed, coded and flushed to the writer as soon as its last row arrives, and EOI is written when the last row is in.
  • OptimizeHuffman / Progressive keep today's buffered session (IsStreaming == false) and produce unchanged bytes.
  • JpegEncoder.Transform's loop body moved into McuRowEncoder, which holds the state one MCU row passes to the next (DC predictors, restart count). JpegEncoder.Encode and the session drive the same code, so the streamed bytes are identical to JpegEncoder.Encode's for the same pixels and options, however WriteRows is chunked. The arithmetic and kernels are untouched.
  • Bit-writer flush: after each MCU row, [0, Position) of the bit writer is final, because every MCU ends with Stuff() and markers end on a byte boundary. The session writes those bytes out and resets Position / Mark to 0. The pending bits (fewer than 8) stay in the accumulator and the next store rewrites them at offset 0.
  • Memory: the session holds one MCU row of native-format pixels (copied only when the caller's band is partial or the input format needs conversion; otherwise rows are coded straight from the caller's span), the float planes, and one MCU row of output.
  • A WriteRows / AddFrame / trailer that fails part way (cancellation, or a writer exception) leaves the session faulted. Later calls and Commit throw InvalidOperationException, so the session never writes a corrupt or truncated file silently.
  • Behaviour change: invalid options (for example Quality 0, or a bad Exif blob in the options) now throw at AddFrame instead of at Commit for streaming sessions.
  • No public API change (PublicAPI files untouched). Goldens untouched.

Tests (JpegStreamingEncodeTests)

  • Byte equality against JpegEncoder.Encode for:
    • sizes 1×1, 17×9, 33×17, 40×31, 16×16, 2049×19, 4113×33 (widths that are not multiples of 16, and more than one 2048-column chunk);
    • 4:2:0, 4:4:4 and Auto subsampling, at q1, q50, q91 and q100;
    • six row-split patterns, with padded strides;
    • every PixelFormat;
    • grey input;
    • restart intervals 1, 2, 3, 5 and 130;
    • Exif + XMP + a two-chunk ICC profile, and frame-metadata overrides.
  • StreamingAssert.EncoderEmitsBeforeCommit, plus a check that the first MCU row is emitted exactly when its 16th row arrives.
  • AllocatesLessThan(1 MiB) for an 8192×8192 frame fed in 64-row bands.
  • IsStreaming is false for optimised / progressive sessions, and their bytes are unchanged.
  • Cancellation in the middle of a WriteRows call, and a writer failure at the trailer making Commit fail (checked by breaking the code: the test fails without the fix).
  • End to end: a 3001×2003 photo streamed in 37-row bands to a FileStream that is flushed on every write. The file is on disk after the first band. Decoded with our decoder and with Magick.NET, it equals the buffered encode's decode, and the bytes are identical.

Runs: full suite 7063 passed / 0 failed (559 skipped: HEIF, OpenJPEG and webp oracle tools are not installed in this worktree). The JPEG classes with REQUIRE_ORACLES=1: 777 passed. The *Jpeg* tests with DOTNET_EnableAVX2=0 and with DOTNET_EnableHWIntrinsic=0: 0 failures.

Benchmarks

Ryzen 7 5800X, Windows 11 (10.0.26200), .NET 10.0.15, AVX2 (no AVX-512). Other jobs were sharing the machine.

  • encode --mode all --gate --baseline: gate passed. There is no regression of the buffered encode against main 533b03e in any mode; the differences are within run-to-run noise.
  • The new streamed contestant (16-row bands; the run aborts unless its bytes equal ours) is within 1.00 to 1.01× of the buffered time at q75 to q95. At q50 4:2:0 it measured 1.05× in one run and 0.99× in another.
config buffered MP/s streamed MP/s
q50 4:2:0 636 604
q75 4:2:0 587 588
q90 4:2:0 505 500
q95 4:4:4 275 276

The numbers are in benchmarks/Sdcb.SimdCodecs.Jpeg.Benchmarks/README.md. The decode ab (BDN) was not run: it measures the decoder, which this change does not touch. The encoder's same-process A/B is encode --baseline, shown above.

Needs outside this unit

None for Abstractions or the facade.

🤖 Generated with Claude Code

sdcb and others added 2 commits November 23, 2026 19:02
JpegImageEncoder.Create now returns a StreamingEncoderSession for every
option set except OptimizeHuffman / Progressive: the headers go out at
AddFrame and each MCU row (8 rows, 16 for 4:2:0) is transformed, coded and
handed to the writer as soon as its last row arrives. Memory is one MCU row
of pixels and output. The transform loop moves into McuRowEncoder, which
both the buffered JpegEncoder.Encode and the session drive, so the bytes
are identical for the same pixels and options, however rows are split.
OptimizeHuffman / Progressive keep the buffered session (IsStreaming false).

The encode benchmark gains a "streamed" contestant (16-row bands) that must
produce JpegEncoder.Encode's bytes before it is timed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ecord timings

A writer failure while the headers or the EOI trailer go out left the
session looking complete: a retried AddFrame wrote the headers twice, and
Commit after a failed trailer succeeded with a truncated file. Both now
mark the session faulted, and Finish throws. The JPEG benchmark README
records streamed vs buffered encode time.

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