Skip to content

TIFF: streaming encode to a seekable Stream (byte-identical to the buffered encode) - #20

Merged
sdcb merged 1 commit into
mainfrom
streaming/tiff-encode
Nov 23, 2026
Merged

sdcb merged 1 commit into
mainfrom
streaming/tiff-encode

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

What

TiffImageEncoder.Create(Stream output, EncodeOptions? options = null, bool leaveOpen = false): a streaming IImageEncoderSession (IsStreaming true) for a writable, seekable stream.

  • The header is written first. Each strip, or each row of tiles, is compressed (Deflate / ZlibPkzip) or copied (Uncompressed) and written as its rows arrive. The Exif sub-IFDs and the page IFD follow the page's segments, whose offsets are known by then. The previous IFD's NextIFD pointer and, at Commit, the header's first-IFD offset are patched by seeking. Multi-page works as before (MaxFrames = int.MaxValue). Offsets count from the stream's position when the session starts.
  • A non-seekable stream throws ArgumentException; the message names the IBufferWriter<byte> overload. A read-only stream also throws ArgumentException.
  • The IBufferWriter<byte> overload stays buffered (IsStreaming false). I did not try the optional forward-only IBufferWriter variant.
  • An unsupported compression, or an Exif block that is not a TIFF structure, fails at AddFrame before any byte of the page is written.
  • If a write fails partway (I/O error, cancellation between segments, a file past 4 GiB), the session is marked faulted and later WriteRows / AddFrame / Commit calls throw InvalidOperationException. This prevents writing a file whose offsets don't match its data.
  • No option needs a buffered fallback. Every layout, compression and pixel format the writer supports streams.

Byte identity with the buffered encode

The streamed file is byte for byte the buffered session's for the same pixels and options. One change was needed for that. ZLibStream's output depends on how its input is split into Write calls: I measured differences on 37 of 108 split patterns for inputs of 300 KB and up. So TiffWriter.DeflateZlib now feeds each segment in 64 KiB slices, and the session feeds the deflater exactly the same slices, holding one 64 KiB slice instead of a whole strip.

Splitting into 64 KiB slices gave the same bytes as the old single whole-span write in all 24 cases I tried (64 KB to 20 MB, four data kinds). The existing TIFF tests pass unchanged and no golden was touched, so files written by older and newer versions should match. I have not proven that for every input.

IfdBuilder.Serialize (the IFD as bytes at a given offset) is now shared by TiffWriter and the session. The mapping from frame to page options moved to a shared internal helper.

Memory

An 8192 × 8192 RGB page (192 MiB of pixels) fed in 64-row bands to a FileStream allocates < 1 MiB in total (StreamingAssert.AllocatesLessThan). That covers a 64 KiB deflate slice, one converted row when the input format needs conversion, and the offset arrays. A tiled page holds one row of tiles.

Timing (throwaway Stopwatch, not committed)

AMD Ryzen 7 5800X, 128 GB, Windows 11, .NET 10.0.15. 8192 × 8192 RGB24 photo-like page, best of 3. "Buffered" is the IBufferWriter session plus writing the file; "streaming" is Create(FileStream) fed 64-row bands.

main buffered this PR buffered this PR streaming
Deflate, 1 strip 758 ms 738 ms 676 ms
Deflate, 64 rows/strip 757 ms 738 ms 687 ms
Uncompressed, 1 strip 442 ms 424 ms 66 ms
Uncompressed, 64 rows/strip 365 ms 359 ms 65 ms

The buffered path does not regress (same run, main built fresh in a separate worktree).

Tests (TiffStreamingEncodeTests)

  • Streamed bytes equal buffered bytes for every input PixelFormat (all 16), across Uncompressed / Deflate / ZlibPkzip, strips (1, 4, 5, 7 rows and whole page) and tiles. Sizes are odd (37 × 41, partial strips and tiles). Bands are random sizes, packed and padded. Our decoder returns the exact pixels.
  • Segments longer than one deflate slice (333 × 257 at 8/16-bit), with bands that cross slice boundaries.
  • Three pages with ICC / XMP / Exif: byte-identical, and libtiff (Magick.NET) reads every page to the exact pixels, plus the Make tag and the ICC profile.
  • A 2400 × 1600 BGRA photo streamed to a FileStream decodes exactly with our decoder and with Magick.NET.
  • Bytes reach the stream before Commit (checked after half the rows), including the single-strip Deflate case.
  • The 8192 × 8192 memory bound described above, plus byte identity and decode.
  • Prefix in the stream, dispose / leaveOpen, non-seekable / read-only / null / wrong options type, a failing page refused at AddFrame with zero bytes written, cancellation, and a stream that fails partway faulting the session.
  • I broke the code deliberately to confirm the tests catch it: removing the slice staging fails the long-segment tests, and wrong tile padding fails the tiled cases.

Runs: TIFF classes with REQUIRE_ORACLES=1 (613 tests, 1 skip: the local corpus needs SIMDCODECS_TESTIMAGES_DIR), the same with DOTNET_EnableAVX2=0 and with DOTNET_EnableHWIntrinsic=0, the full suite (7063 tests, 0 failures), and TIFF_FUZZ_ITERATIONS=300000 TiffRobustness. Build: 0 warnings. PublicAPI.Unshipped.txt is updated. I did not run the AOT or wasm smoke tests; the facade is untouched.

A machine issue to know about (not caused by this PR)

On this machine the 8192 × 8192 test failed now and then (about 1 run in 10): one file's deflate stream had a single byte with bit 1 flipped. It happened on either the streamed or the buffered side. I reproduced the same failure with a standalone program that uses only the BCL (ArrayPool + ZLibStream, no repo code): over 80 rounds it eventually wrote a corrupt zlib stream from intact input. So it is either a fault in the native zlib that ships with the runtime or a hardware problem on this box. WHEA logged nothing, and a pure memory pattern test found no flips. If CI shows the large test failing intermittently, look here first.

Follow-up (not in this PR)

The facade could send CreateEncoder(ImageFormat.Tiff, <seekable Stream>) to TiffImageEncoder.Create(Stream, …). This PR does not change the facade or Abstractions.

🤖 Generated with Claude Code

TiffImageEncoder.Create(Stream, EncodeOptions?, bool leaveOpen) returns a
streaming session (IsStreaming true): the header goes out first, each strip
(or row of tiles) is compressed and written as its rows arrive, a page's IFD
follows its segments, and the previous NextIFD / header first-IFD offsets are
patched by seeking. A non-seekable stream is an ArgumentException naming the
IBufferWriter overload, which stays buffered.

The file is byte for byte the buffered encoder's. ZLibStream's output depends
on how its input is split, so TiffWriter.DeflateZlib now feeds every segment
in 64 KiB slices and the session feeds the same slices, holding one slice, not
one strip. The 64 KiB split produces the same bytes as the old whole-span
write in every case checked, and the buffered timing is unchanged.

IfdBuilder gains Serialize (the IFD as bytes at a given offset), shared by
both paths; the page-options mapping moves to a shared internal helper.

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