Repository navigation
TIFF: streaming encode to a seekable Stream (byte-identical to the buffered encode) - #20
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
TiffImageEncoder.Create(Stream output, EncodeOptions? options = null, bool leaveOpen = false): a streamingIImageEncoderSession(IsStreamingtrue) for a writable, seekable stream.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.ArgumentException; the message names theIBufferWriter<byte>overload. A read-only stream also throwsArgumentException.IBufferWriter<byte>overload stays buffered (IsStreamingfalse). I did not try the optional forward-only IBufferWriter variant.AddFramebefore any byte of the page is written.WriteRows/AddFrame/Commitcalls throwInvalidOperationException. This prevents writing a file whose offsets don't match its data.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 intoWritecalls: I measured differences on 37 of 108 split patterns for inputs of 300 KB and up. SoTiffWriter.DeflateZlibnow 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 byTiffWriterand 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
FileStreamallocates < 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
IBufferWritersession plus writing the file; "streaming" isCreate(FileStream)fed 64-row bands.The buffered path does not regress (same run, main built fresh in a separate worktree).
Tests (
TiffStreamingEncodeTests)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.FileStreamdecodes exactly with our decoder and with Magick.NET.Commit(checked after half the rows), including the single-strip Deflate case.leaveOpen, non-seekable / read-only / null / wrong options type, a failing page refused atAddFramewith zero bytes written, cancellation, and a stream that fails partway faulting the session.Runs: TIFF classes with
REQUIRE_ORACLES=1(613 tests, 1 skip: the local corpus needsSIMDCODECS_TESTIMAGES_DIR), the same withDOTNET_EnableAVX2=0and withDOTNET_EnableHWIntrinsic=0, the full suite (7063 tests, 0 failures), andTIFF_FUZZ_ITERATIONS=300000TiffRobustness. 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>)toTiffImageEncoder.Create(Stream, …). This PR does not change the facade or Abstractions.🤖 Generated with Claude Code