Skip to content

v2.1.0: streaming decode and encode

Latest

Choose a tag to compare

@sdcb sdcb released this 24 Nov 12:12
· 59 commits to main since this release

2.1 adds streaming image input and output for request bodies, pipes, and other streams that cannot be rewound. The release keeps the 2.0 facade and codec behavior while adding row readers, asynchronous frame operations, and encoder sessions that report whether the selected codec and options are truly streaming.

Highlights

  • ImageCodecs.OpenRowReader and OpenRowReaderAsync expose IImageRowReader, which reads decoded rows top to bottom and supports synchronous or asynchronous consumers.
  • ImageCodecs.CreateEncoder exposes StreamEncoderSession and StreamFrameEncoder, with WriteRowsAsync and CommitAsync for back-pressure-friendly output.
  • JPEG, PNG, WebP, BMP, TIFF, QOI, and Netpbm have streaming row-reader paths for the variants documented by each package. PNG, JPEG, BMP, TIFF, QOI, and Netpbm also have streaming encoder paths for their supported options.
  • Variants that need the complete image, such as progressive JPEG, interlaced or animated PNG, scaled or oriented reads, palette quantization, and other format-specific cases use the same API with a buffered fallback. Inspect IsStreaming when memory behavior matters.
  • ImageDecoder.Open and OpenAsync can decode frame zero from a forward-only stream as rows arrive. Use forwardOnly: true when the stream must not retain bytes for later frame operations.
  • The streaming implementation has dedicated equivalence, cancellation, truncation, async-only, facade, and benchmark coverage.
  • A new LINQPad sample in Sdcb.SimdCodecs, streaming, pipes an HTTP response through a row reader into an encoder and a file a band of rows at a time, checks the result against a whole-image decode, and lists IsStreaming for each variant and format.
dotnet add package Sdcb.SimdCodecs --version 2.1.0
await using IImageRowReader reader = await ImageCodecs.OpenRowReaderAsync(requestBody, PixelFormat.Rgb24);
await using StreamEncoderSession session = ImageCodecs.CreateEncoder(ImageFormat.Png, output);
StreamFrameEncoder frame = session.AddFrame(reader.Width, reader.Height, reader.Format);
byte[] band = new byte[reader.Width * reader.Format.BytesPerPixel * 16];
for (int rows; (rows = await reader.ReadRowsAsync(band, 16)) > 0;)
    await frame.WriteRowsAsync(band.AsMemory(), rows);
await session.CommitAsync();

Memory

Measured on a 12 MP (4000×3000) baseline JPEG, AMD Ryzen 7 5800X, .NET 10, median of three fresh processes (record):

operation peak working set, buffered peak working set, streamed
decode to RGBA, 16-row bands 76.9 MiB 30.0 MiB
encode RGB from a 16-row producer 71.9 MiB 38.0 MiB

The decoded pixels and the encoded bytes are identical on both paths. The saving needs the caller to work in row bands too: ImageDecoder.Open(stream, forwardOnly: true).GetFrame(0).Decode() still returns a complete 36 MB image, and its peak matched the byte-array decode.

Fixes and other changes

  • GainMap: NUL-padded XMP packets are read. Some writers pad or terminate the APP1 XMP packet with NUL bytes, which are not legal XML, so GainMapImageDecoder.CanDecode raised an internal XmlException for such JPEGs and missed their gain maps. Trailing NUL and whitespace are now trimmed before parsing, and a packet that contains neither the namespace being looked for nor a character reference is skipped without building an XML document, so sniffing ordinary photos no longer parses their XMP.
  • ImageDecoder.Open(Stream) reads the header only. In 2.0 it copied the whole stream at open. It now sniffs the format, reads the header through the codec's row reader, and reads the rest only when a frame operation needs it, so opening a large file to inspect its size, format or frame count no longer buffers it.
  • TiffReader.Read(Stream) reads by offset. On a seekable stream the header, directories, strips and tiles are read where they sit instead of copying the stream into memory first.
  • Whole-image reads through a row reader can be cancelled between bands. Each step decodes at most about 1 MiB of rows before checking the cancellation token.
  • Bottom-up BMP files stream from seekable inputs. The row reader seeks to the band it needs, starting from the end of the pixel data, so each pixel byte is read once and only one band is held at a time.
  • browser-wasm: byte shuffles use PackedSimd.Swizzle. PNG RGB→RGBA expansion, BMP channel swaps and PixelConverter previously fell back to the scalar loop on WebAssembly. Decoding a 1280×960 RGB PNG went from 36.7 ms to 14.2 ms (Mono AOT, O2), with identical output.

Breaking changes

  • PNG encoder sessions take one frame unless PngWriteOptions.Animation is set. PngImageEncoder.Create (and ImageCodecs.CreateEncoder(ImageFormat.Png, …)) now streams a still image by default, writing image data as rows arrive, so MaxFrames is 1 and a second AddFrame throws InvalidOperationException. In 2.0 the same session collected any number of frames and wrote an APNG at Commit. To write an animated PNG through a session, pass new PngWriteOptions { Animation = true }; that session buffers whole frames and writes the file at Commit (IsStreaming false), as before. PngAnimationEncoder and PngWriter are unaffected.

Compatibility

Apart from the change above, the existing 2.0 decode, encode, metadata, frame, and facade entry points remain available. The new public members are recorded in each package's public API baseline. Applications that only use the existing byte-array and buffered stream methods do not need source changes.

Third-party codec registrations can omit CreateRowReader. The facade then provides a buffered row reader. Codec authors implementing the new streaming abstractions should expose the concrete static method through ImageDecoderRegistration.CreateRowReader so NativeAOT and browser-wasm keep the same delegate binding rules.

Known limitations

Streaming support depends on the image variant and options. Read known gaps and the package README before relying on bounded memory. TIFF streaming requires a seekable input for the layouts that use directory offsets. HEIF remains an opt-in decode-only package because HEVC patent obligations are outside this project.

Validation

The release gate is dotnet build SimdCodecs.slnx -c Release, REQUIRE_ORACLES=1 dotnet test SimdCodecs.slnx -c Release, the SIMD-tier matrix, and the NativeAOT and browser-wasm smoke tests. Benchmark records for the streaming paths are under benchmarks/*/results/.