diff --git a/src/Sdcb.SimdCodecs.Tiff/IfdBuilder.cs b/src/Sdcb.SimdCodecs.Tiff/IfdBuilder.cs index 9f0c3da..40ac341 100644 --- a/src/Sdcb.SimdCodecs.Tiff/IfdBuilder.cs +++ b/src/Sdcb.SimdCodecs.Tiff/IfdBuilder.cs @@ -94,52 +94,57 @@ public async Task WriteAsync(TiffFileTarget target, CancellationToken ct = { await target.AlignAsync(ct).ConfigureAwait(false); var ifdStart = target.Position; + var bytes = Serialize(ifdStart, out var nextIfdField); + await target.WriteAsync(bytes, ct).ConfigureAwait(false); + return ifdStart + nextIfdField; + } - var entryCount = (ushort)_entries.Count; + /// + /// The IFD as it is stored at file offset (a word boundary): the entry count, the + /// entries in tag order, the NextIFD pointer (0; the caller patches it) and then every value longer than four bytes, + /// in entry order. is the NextIFD pointer's offset within the returned bytes. + /// + public byte[] Serialize(long ifdStart, out int nextIfdField) + { const int entrySize = 12; // tag(2) + type(2) + count(4) + value/offset(4) - - // Entry count - await target.WriteUInt16Async(entryCount, ct).ConfigureAwait(false); - - // Compute where overflow data starts (after all entries + NextIFD pointer) - var overflowOffset = (uint)(ifdStart + 2 + entryCount * entrySize + 4); - - // Collect overflow data to write after the directory - var overflowData = new List(); - var entryBytes = new byte[entrySize]; - + var entryCount = (ushort)_entries.Count; + nextIfdField = 2 + entryCount * entrySize; + var length = (long)nextIfdField + 4; + foreach (var (_, (_, _, valueBytes)) in _entries) + if (valueBytes.Length > 4) + length += valueBytes.Length; + if (ifdStart + length > uint.MaxValue) + throw new IOException("The TIFF file would pass 4 GiB, the most a classic TIFF offset addresses."); + + var bytes = new byte[length]; + var span = bytes.AsSpan(); + MemoryMarshal.Write(span, in entryCount); + + // Overflow data starts after all entries + NextIFD pointer. + var overflowOffset = (uint)(ifdStart + nextIfdField + 4); + var at = 2; + var overflowAt = nextIfdField + 4; foreach (var (tag, (type, count, valueBytes)) in _entries) { var typeShort = (ushort)type; - MemoryMarshal.Write(entryBytes.AsSpan(0, 2), in tag); - MemoryMarshal.Write(entryBytes.AsSpan(2, 2), in typeShort); - MemoryMarshal.Write(entryBytes.AsSpan(4, 4), in count); - + MemoryMarshal.Write(span.Slice(at, 2), in tag); + MemoryMarshal.Write(span.Slice(at + 2, 2), in typeShort); + MemoryMarshal.Write(span.Slice(at + 4, 4), in count); if (valueBytes.Length <= 4) { - // Inline: pad to 4 bytes - entryBytes.AsSpan(8, 4).Clear(); - valueBytes.CopyTo(entryBytes.AsSpan(8)); + // Inline: padded to 4 bytes (the array is zeroed). + valueBytes.CopyTo(span.Slice(at + 8)); } else { - // Overflow: write offset to data area - MemoryMarshal.Write(entryBytes.AsSpan(8, 4), in overflowOffset); + MemoryMarshal.Write(span.Slice(at + 8, 4), in overflowOffset); overflowOffset += (uint)valueBytes.Length; - overflowData.Add(valueBytes); + valueBytes.CopyTo(span.Slice(overflowAt)); + overflowAt += valueBytes.Length; } - - await target.WriteAsync(entryBytes, ct).ConfigureAwait(false); + at += entrySize; } - - // NextIFD pointer (0 = no next page; caller patches this) - var nextIfdPatchOffset = target.Position; - await target.WriteUInt32Async(0, ct).ConfigureAwait(false); - - // Write overflow value data - foreach (var data in overflowData) - await target.WriteAsync(data, ct).ConfigureAwait(false); - - return nextIfdPatchOffset; + // NextIFD pointer stays 0 (no next page) until the caller patches it. + return bytes; } } diff --git a/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt index 7dc5c58..a3845f2 100644 --- a/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt +++ b/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static Sdcb.SimdCodecs.Tiff.TiffImageEncoder.Create(System.IO.Stream! output, Sdcb.SimdCodecs.Abstractions.EncodeOptions? options = null, bool leaveOpen = false) -> Sdcb.SimdCodecs.Abstractions.IImageEncoderSession! diff --git a/src/Sdcb.SimdCodecs.Tiff/README.md b/src/Sdcb.SimdCodecs.Tiff/README.md index f656537..61e0633 100644 --- a/src/Sdcb.SimdCodecs.Tiff/README.md +++ b/src/Sdcb.SimdCodecs.Tiff/README.md @@ -45,3 +45,14 @@ A `DecodeOptions.Region` reads only the strips or tiles it intersects, and `TryD ## Writing `TiffWriter` writes classic TIFF (never BigTIFF): uncompressed or Deflate, strips or tiles, 8/16/32-bit integer and float samples, with ICC, XMP and Exif. + +`TiffImageEncoder.Create(Stream)` streams a file to a writable, seekable stream as the rows arrive: each strip, or each row of tiles, is compressed and written once its rows are in, and a page's IFD follows its last segment. Memory is one band of rows (a 64 KiB deflate input slice for strips, one row of tiles for a tiled page), whatever the page size. The header's and each IFD's forward offsets are patched by seeking, so a non-seekable stream is refused with `ArgumentException`; encode into an `IBufferWriter` (`TiffImageEncoder.Create(IBufferWriter)`, buffered) and copy instead. The streamed file is byte for byte the buffered encoder's for the same pixels and options (`TiffStreamingEncodeTests`). + +```csharp +using var file = File.Create("scan.tif"); +using var session = TiffImageEncoder.Create(file, new TiffEncodeOptions { Page = new TiffPageOptions { RowsPerStrip = 64 } }); +var page = session.AddFrame(width, height, PixelFormat.Rgb24); +foreach (var (band, rows) in Bands()) // any band size + page.WriteRows(band, rows); +session.Commit(); // patches the first-IFD offset; the file is complete +``` diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffImageEncoder.cs b/src/Sdcb.SimdCodecs.Tiff/TiffImageEncoder.cs index 7d727ce..50eaa2c 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffImageEncoder.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffImageEncoder.cs @@ -36,14 +36,43 @@ public sealed class TiffImageEncoder : IImageEncoder /// is a (null means the defaults; any other type /// throws ). public static IImageEncoderSession Create(IBufferWriter output, EncodeOptions? options = null) => - new Session(output, options switch - { - null => new TiffEncodeOptions(), - TiffEncodeOptions o => o, - _ => throw new ArgumentException($"TIFF encoding takes TiffEncodeOptions, not {options.GetType().Name}.", nameof(options)), - }); + new Session(output, Options(options)); + + /// + /// Starts a streaming session that writes the file to as the rows arrive + /// ( is true): each strip, or each row of tiles, is compressed and written + /// once its rows are in, and a page's IFD follows its last segment, so memory stays at a band of rows whatever the + /// image size. The file is byte for byte the one writes. + /// + /// + /// A TIFF header and each IFD point forward to an IFD written later, so the session patches those offsets by seeking: + /// must be writable and seekable (for a non-seekable stream, encode into an + /// and copy). The file starts at the stream's current position, and offsets count from + /// there. The file is complete once returns; a session disposed before that + /// leaves a truncated file behind. Disposing the session disposes unless + /// is set. is a (null means the + /// defaults; any other type throws ). A compression the writer cannot apply, or an Exif + /// block in that is not a TIFF structure, fails at + /// , before the page is written. + /// + public static IImageEncoderSession Create(Stream output, EncodeOptions? options = null, bool leaveOpen = false) + { + ArgumentNullException.ThrowIfNull(output); + if (!output.CanWrite) + throw new ArgumentException("The stream is not writable.", nameof(output)); + if (!output.CanSeek) + throw new ArgumentException("A streaming TIFF session patches offsets and needs a seekable stream; for a non-seekable one, use Create(IBufferWriter, EncodeOptions?) and copy the result.", nameof(output)); + return TiffStreamingEncoderSession.Create(output, Options(options), leaveOpen); + } + + private static TiffEncodeOptions Options(EncodeOptions? options) => options switch + { + null => new TiffEncodeOptions(), + TiffEncodeOptions o => o, + _ => throw new ArgumentException($"TIFF encoding takes TiffEncodeOptions, not {options.GetType().Name}.", nameof(options)), + }; - private static PixelFormat Native(PixelFormat f) => f.Layout switch + internal static PixelFormat Native(PixelFormat f) => f.Layout switch { ChannelLayout.Rgba or ChannelLayout.Bgra => new PixelFormat(ChannelLayout.Rgba, f.Sample), ChannelLayout.Rgb or ChannelLayout.Bgr => new PixelFormat(ChannelLayout.Rgb, f.Sample), @@ -67,7 +96,7 @@ protected override void Encode(IReadOnlyList frames, Cancellation cancellationToken.ThrowIfCancellationRequested(); var native = Native(frame.Format); var pixels = frame.PixelsAs(native).ToArray(); - writer.AddPageAsync(pixels, frame.Width, frame.Height, PageOptions(native, frame), cancellationToken) + writer.AddPageAsync(pixels, frame.Width, frame.Height, PageOptions(options, native, frame.Metadata), cancellationToken) .GetAwaiter().GetResult(); } } @@ -77,29 +106,31 @@ protected override void Encode(IReadOnlyList frames, Cancellation } WriteOutput(stream.ToArray()); } + } - private TiffPageOptions PageOptions(PixelFormat native, BufferedFrame frame) + /// The page a frame in format becomes: the template with the frame's sample layout + /// and metadata (shared by the buffered and the streaming session). + internal static TiffPageOptions PageOptions(TiffEncodeOptions options, PixelFormat native, ImageMetadata? metadata) + { + var gray = native.Layout is ChannelLayout.Gray or ChannelLayout.GrayAlpha; + var alpha = native.Layout is ChannelLayout.GrayAlpha or ChannelLayout.Rgba; + var o = (options.Page ?? TiffPageOptions.Default) with { - var gray = native.Layout is ChannelLayout.Gray or ChannelLayout.GrayAlpha; - var alpha = native.Layout is ChannelLayout.GrayAlpha or ChannelLayout.Rgba; - var o = (options.Page ?? TiffPageOptions.Default) with - { - SamplesPerPixel = native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, ChannelLayout.GrayAlpha => 2, _ => 1 }, - BitsPerSample = native.Sample == SampleFormat.UInt16 ? 16 : 8, - SampleFormat = TiffSampleFormat.Uint, - Photometric = gray ? TiffPhotometric.MinIsBlack : TiffPhotometric.Rgb, - ExtraSamples = alpha ? TiffExtraSamples.UnassociatedAlpha : null, - }; - if (frame.Metadata is { } m) - { - if (!m.Icc.IsEmpty) - o = o with { IccProfile = m.Icc }; - if (!m.Xmp.IsEmpty) - o = o with { Xmp = m.Xmp }; - if (!m.Exif.IsEmpty && TiffExif.ParseBlock(m.Exif.Span) is not null) - o = o with { Exif = m.Exif }; - } - return o; + SamplesPerPixel = native.Layout switch { ChannelLayout.Rgba => 4, ChannelLayout.Rgb => 3, ChannelLayout.GrayAlpha => 2, _ => 1 }, + BitsPerSample = native.Sample == SampleFormat.UInt16 ? 16 : 8, + SampleFormat = TiffSampleFormat.Uint, + Photometric = gray ? TiffPhotometric.MinIsBlack : TiffPhotometric.Rgb, + ExtraSamples = alpha ? TiffExtraSamples.UnassociatedAlpha : null, + }; + if (metadata is { } m) + { + if (!m.Icc.IsEmpty) + o = o with { IccProfile = m.Icc }; + if (!m.Xmp.IsEmpty) + o = o with { Xmp = m.Xmp }; + if (!m.Exif.IsEmpty && TiffExif.ParseBlock(m.Exif.Span) is not null) + o = o with { Exif = m.Exif }; } + return o; } } diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffStreamingEncoderSession.cs b/src/Sdcb.SimdCodecs.Tiff/TiffStreamingEncoderSession.cs new file mode 100644 index 0000000..015628e --- /dev/null +++ b/src/Sdcb.SimdCodecs.Tiff/TiffStreamingEncoderSession.cs @@ -0,0 +1,460 @@ +using System.Buffers; +using System.IO.Compression; +using System.Runtime.InteropServices; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Tiff; + +/// +/// The streaming behind : +/// it writes the file writes for the same pixels and options, byte for byte, in the same order +/// (header, then each page's segments, Exif sub-IFDs and IFD), but as the rows arrive. +/// +/// A strip goes to the stream as its rows come in: uncompressed rows are written as they are, deflated ones pass through +/// one -byte slice (the deflater's input pieces, the same ones +/// uses). A tiled page holds one row of tiles. The offsets and byte counts are known +/// once a page's segments are written, so its IFD follows them; the previous IFD's NextIFD pointer and, at +/// , the header's first-IFD offset are patched by seeking, which is why the +/// stream must be seekable. Offsets count from where the stream was when the session started. +/// +/// +internal sealed class TiffStreamingEncoderSession : StreamingEncoderSession +{ + private readonly Stream _stream; + private readonly bool _leaveOpen; + private readonly long _origin; + private readonly TiffEncodeOptions _options; + private bool _headerWritten; + private bool _faulted; + private long _firstIfdOffset = -1; + private long _prevNextIfdPatchOffset = -1; + + // The current frame. + private int _width, _height; + private PixelFormat _format, _native; + private TiffPageOptions _page = TiffPageOptions.Default; + private TiffExifDirectories? _exif; + private int _rowBytes; + private int _rowsDone; + private uint[] _offsets = []; + private uint[] _byteCounts = []; + private int _segment; + private byte[]? _converted; + + // Strips. + private int _rowsPerStrip; + private int _rowInStrip; + + // Tiles: one row of tiles is collected in _band, each tile cut into _tile. + private int _tileWidth, _tileHeight, _tilesX; + private byte[]? _band; + private int _bandRows; + private byte[]? _tile; + + // The open segment's deflater and its input slice. + private ZLibStream? _deflater; + private byte[]? _chunk; + private int _chunkFill; + + private TiffStreamingEncoderSession(Stream stream, StreamWriter writer, TiffEncodeOptions options, bool leaveOpen) + : base(writer) + { + _stream = stream; + _leaveOpen = leaveOpen; + _options = options; + _origin = stream.Position; + } + + public static TiffStreamingEncoderSession Create(Stream stream, TiffEncodeOptions options, bool leaveOpen) => + new(stream, new StreamWriter(stream), options, leaveOpen); + + public override int MaxFrames => int.MaxValue; + + /// Where the file stands, counted from its first byte. + private long Position => _stream.Position - _origin; + + private bool Deflate => _page.Compression is TiffCompression.Deflate or TiffCompression.ZlibPkzip; + + /// + /// Set when a write failed partway (an I/O error, cancellation between segments, a file past 4 GiB): the stream then + /// holds part of a band the base session does not count as written, so the session refuses to go on rather than + /// write a file whose offsets disagree with its data. + /// + private void ThrowIfFaulted() + { + if (_faulted) + throw new InvalidOperationException("An earlier write failed partway; the TIFF file is incomplete and the session cannot continue."); + } + + protected override void BeginFrame(int index, int width, int height, PixelFormat format, ColorEncoding? color, + ImageMetadata? metadata, TimeSpan? duration) + { + ThrowIfFaulted(); + var native = TiffImageEncoder.Native(format); + var page = TiffImageEncoder.PageOptions(_options, native, metadata); + + // Everything that can refuse the page is checked before a byte of it is written. + if (page.Compression is not (TiffCompression.Uncompressed or TiffCompression.Deflate or TiffCompression.ZlibPkzip)) + throw new NotSupportedException($"TiffWriter cannot encode {page.Compression}. Supported: Uncompressed, Deflate, ZlibPkzip."); + TiffExifDirectories? exif = null; + if (!page.Exif.IsEmpty) + { + exif = TiffExif.ParseBlock(page.Exif.Span) + ?? throw new InvalidDataException("TiffPageOptions.Exif is not a TIFF structure (no II*\\0 or MM\\0* header)"); + } + var rowBytes = width * native.BytesPerPixel; + long segments; + if (page.Layout == TiffLayout.Tiled) + { + if (page.TileWidth <= 0 || page.TileHeight <= 0) + throw new ArgumentException($"Tiles are at least 1x1 pixel, not {page.TileWidth}x{page.TileHeight}.", "options"); + var tilesX = ((long)width + page.TileWidth - 1) / page.TileWidth; + segments = tilesX * (((long)height + page.TileHeight - 1) / page.TileHeight); + if ((long)page.TileHeight * rowBytes > Array.MaxLength || (long)page.TileHeight * page.TileWidth * native.BytesPerPixel > Array.MaxLength) + throw new ArgumentException($"A row of {page.TileWidth}x{page.TileHeight} tiles {width} pixels wide does not fit in memory.", "options"); + _tileWidth = page.TileWidth; + _tileHeight = page.TileHeight; + _tilesX = (int)tilesX; + } + else + { + _rowsPerStrip = page.RowsPerStrip > 0 ? page.RowsPerStrip : height; + segments = ((long)height + _rowsPerStrip - 1) / _rowsPerStrip; + } + if (segments > Array.MaxLength) + throw new ArgumentException($"A {width}x{height} page has more segments than fit in memory.", "options"); + + try + { + StartFrame(width, height, format, native, page, exif, rowBytes, segments); + } + catch + { + _faulted = true; + throw; + } + } + + private void StartFrame(int width, int height, PixelFormat format, PixelFormat native, TiffPageOptions page, + TiffExifDirectories? exif, int rowBytes, long segments) + { + if (!_headerWritten) + { + // As TiffWriter: the host's byte order, magic 42, and the first IFD's offset (patched at Commit). + _headerWritten = true; + var order = (byte)(BitConverter.IsLittleEndian ? 'I' : 'M'); + Span header = [order, order, 0, 0, 0, 0, 0, 0]; + MemoryMarshal.Write(header[2..], (ushort)42); + _stream.Write(header); + } + + (_width, _height, _format, _native, _page, _exif, _rowBytes) = (width, height, format, native, page, exif, rowBytes); + _rowsDone = 0; + _segment = 0; + _rowInStrip = 0; + _bandRows = 0; + _offsets = new uint[segments]; + _byteCounts = new uint[segments]; + if (format != native) + _converted = ArrayPool.Shared.Rent(rowBytes); + if (page.Layout == TiffLayout.Tiled) + { + _band = ArrayPool.Shared.Rent(_tileHeight * rowBytes); + _tile = ArrayPool.Shared.Rent(_tileHeight * _tileWidth * native.BytesPerPixel); + } + if (Deflate) + _chunk ??= ArrayPool.Shared.Rent(TiffWriter.DeflateChunk); + } + + protected override void EncodeRows(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + ThrowIfFaulted(); + try + { + Encode(rows, rowCount, stride, cancellationToken); + } + catch + { + _faulted = true; + throw; + } + } + + private void Encode(ReadOnlySpan rows, int rowCount, int stride, CancellationToken cancellationToken) + { + var tiled = _page.Layout == TiffLayout.Tiled; + var y = 0; + while (y < rowCount) + { + if (_format == _native && !tiled && stride == _rowBytes) + { + // Packed rows in the stored format: hand the strip's share of the band over in one piece. + if (_rowInStrip == 0) + BeginSegment(cancellationToken); + var n = Math.Min(rowCount - y, _rowsPerStrip - _rowInStrip); + AppendSegment(rows.Slice(y * stride, n * _rowBytes)); + y += n; + AdvanceStrip(n); + continue; + } + + var row = rows.Slice(y * stride, _format.BytesPerPixel * _width); + if (_converted is not null) + { + PixelConverter.ConvertRow(row, _format, _converted, _native, _width); + row = _converted.AsSpan(0, _rowBytes); + } + if (tiled) + { + row.CopyTo(_band.AsSpan(_bandRows * _rowBytes)); + _bandRows++; + _rowsDone++; + if (_bandRows == _tileHeight || _rowsDone == _height) + EmitTileRow(cancellationToken); + } + else + { + if (_rowInStrip == 0) + BeginSegment(cancellationToken); + AppendSegment(row); + AdvanceStrip(1); + } + y++; + } + } + + private void AdvanceStrip(int rows) + { + _rowInStrip += rows; + _rowsDone += rows; + if (_rowInStrip == _rowsPerStrip || _rowsDone == _height) + { + EndSegment(); + _rowInStrip = 0; + } + } + + /// Cuts the collected row of tiles into tiles as does (edges zero-padded) and + /// writes each. + private void EmitTileRow(CancellationToken cancellationToken) + { + var bpp = _native.BytesPerPixel; + var tileRowBytes = _tileWidth * bpp; + var tile = _tile.AsSpan(0, tileRowBytes * _tileHeight); + var band = _band.AsSpan(0, _bandRows * _rowBytes); + for (var tx = 0; tx < _tilesX; tx++) + { + var startCol = tx * _tileWidth; + var colBytes = Math.Min(_tileWidth, _width - startCol) * bpp; + if (colBytes < tileRowBytes || _bandRows < _tileHeight) + tile.Clear(); + for (var r = 0; r < _bandRows; r++) + band.Slice(r * _rowBytes + startCol * bpp, colBytes).CopyTo(tile[(r * tileRowBytes)..]); + BeginSegment(cancellationToken); + AppendSegment(tile); + EndSegment(); + } + _bandRows = 0; + } + + private void BeginSegment(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Align(); + _offsets[_segment] = CheckedOffset(Position); + if (Deflate) + { + _deflater = TiffWriter.NewDeflater(_stream); + _chunkFill = 0; + } + } + + private void AppendSegment(ReadOnlySpan data) + { + if (_deflater is null) + { + _stream.Write(data); + return; + } + // The deflater sees the segment in whole DeflateChunk-byte slices and then the rest, exactly as DeflateZlib + // feeds it, however the rows arrive: a full slice goes straight from the caller's span when the buffer is empty, + // anything shorter waits in _chunk. + var chunk = _chunk.AsSpan(0, TiffWriter.DeflateChunk); + while (!data.IsEmpty) + { + if (_chunkFill == 0 && data.Length >= chunk.Length) + { + _deflater.Write(data[..chunk.Length]); + data = data[chunk.Length..]; + continue; + } + var n = Math.Min(chunk.Length - _chunkFill, data.Length); + data[..n].CopyTo(chunk[_chunkFill..]); + _chunkFill += n; + data = data[n..]; + if (_chunkFill == chunk.Length) + { + _deflater.Write(chunk); + _chunkFill = 0; + } + } + } + + private void EndSegment() + { + if (_deflater is not null) + { + if (_chunkFill > 0) + _deflater.Write(_chunk.AsSpan(0, _chunkFill)); + _chunkFill = 0; + _deflater.Dispose(); // writes the stream's tail and Adler-32 + _deflater = null; + } + _byteCounts[_segment] = CheckedOffset(Position - _offsets[_segment]); + _segment++; + } + + protected override void EndFrame(CancellationToken cancellationToken) + { + try + { + WriteIfd(); + } + catch + { + _faulted = true; + throw; + } + } + + private void WriteIfd() + { + // As TiffWriter.AddPageAsync: the Exif block's sub-IFDs, then the page's IFD, chained to the previous one. + long? exifIfdOffset = null, gpsIfdOffset = null; + if (_exif is { } exif) + { + long? interopOffset = exif.HasExifIfd && exif.Interop.Count > 0 ? WriteSubIfd(exif.Interop, null) : null; + if (exif.HasExifIfd) + exifIfdOffset = WriteSubIfd(exif.Exif, interopOffset); + if (exif.HasGpsIfd) + gpsIfdOffset = WriteSubIfd(exif.Gps, null); + } + var ifd = TiffWriter.BuildIfd(_width, _height, _page.Compression, _page.Photometric, _page, _offsets, _byteCounts, _exif?.Ifd0); + if (exifIfdOffset is { } e) ifd.SetLong(TiffTag.ExifIfd, (uint)e); + if (gpsIfdOffset is { } g) ifd.SetLong(TiffTag.GpsInfoIfd, (uint)g); + + Align(); + var ifdOffset = Position; + _stream.Write(ifd.Serialize(ifdOffset, out var nextIfdField)); + if (_prevNextIfdPatchOffset >= 0) + Patch(_prevNextIfdPatchOffset, (uint)ifdOffset); + if (_firstIfdOffset < 0) + _firstIfdOffset = ifdOffset; + _prevNextIfdPatchOffset = ifdOffset + nextIfdField; + ReleaseFrame(); + } + + private long WriteSubIfd(List entries, long? interopOffset) + { + var builder = new IfdBuilder(); + foreach (var entry in entries) + builder.Set(entry); + if (interopOffset is { } i) + builder.SetLong(TiffExif.InteropIfd, (uint)i); + Align(); + var at = Position; + _stream.Write(builder.Serialize(at, out _)); + return at; + } + + protected override void Finish(CancellationToken cancellationToken) + { + ThrowIfFaulted(); + if (_firstIfdOffset < 0) + throw new InvalidOperationException("No page was written."); + Patch(4, (uint)_firstIfdOffset); + _stream.Flush(); + } + + /// Pads to a word boundary, as TIFF 6.0 asks of every offset. + private void Align() + { + if ((Position & 1) != 0) + _stream.WriteByte(0); + } + + private void Patch(long offset, uint value) + { + var end = _stream.Position; + Span bytes = stackalloc byte[4]; + MemoryMarshal.Write(bytes, value); + _stream.Seek(_origin + offset, SeekOrigin.Begin); + _stream.Write(bytes); + _stream.Seek(end, SeekOrigin.Begin); + } + + private static uint CheckedOffset(long value) => value <= uint.MaxValue + ? (uint)value + : throw new IOException("The TIFF file would pass 4 GiB, the most a classic TIFF offset addresses."); + + private void ReleaseFrame() + { + Return(ref _converted); + Return(ref _band); + Return(ref _tile); + } + + private static void Return(ref byte[]? array) + { + if (array is not null) + ArrayPool.Shared.Return(array); + array = null; + } + + protected override void Dispose(bool disposing) + { + if (!disposing) return; + try + { + // Only a segment left open by an unfinished or failed session has a deflater; its tail is of no use to a + // truncated file, and a failure writing it must not replace the exception that ended the session. + _deflater?.Dispose(); + } + catch (Exception e) when (e is IOException or ObjectDisposedException or NotSupportedException) + { + } + finally + { + _deflater = null; + ReleaseFrame(); + Return(ref _chunk); + if (!_leaveOpen) + _stream.Dispose(); + } + } + + /// The base session's : each advanced span goes straight to the + /// stream. + private sealed class StreamWriter(Stream stream) : IBufferWriter + { + private byte[] _buffer = []; + + public void Advance(int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, _buffer.Length); + stream.Write(_buffer, 0, count); + } + + public Memory GetMemory(int sizeHint = 0) + { + var size = Math.Max(sizeHint, 1); + if (_buffer.Length < size) + _buffer = new byte[Math.Max(size, 256)]; + return _buffer; + } + + public Span GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; + } +} diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffWriter.cs b/src/Sdcb.SimdCodecs.Tiff/TiffWriter.cs index 035737f..32bd2d4 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffWriter.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffWriter.cs @@ -136,7 +136,13 @@ private async Task WriteSubIfdAsync(List entries, long? int } private static IfdBuilder BuildIfd(IImageSource source, TiffPageOptions options, - uint[] offsets, uint[] byteCounts, List? exifIfd0 = null) + uint[] offsets, uint[] byteCounts, List? exifIfd0 = null) => + BuildIfd(source.Width, source.Height, source.IsPreCompressed ? source.Compression : options.Compression, + source.Photometric, options, offsets, byteCounts, exifIfd0); + + /// The page's IFD; shared with the streaming encoder session, whose files equal this writer's. + internal static IfdBuilder BuildIfd(int width, int height, TiffCompression compression, TiffPhotometric photometric, + TiffPageOptions options, uint[] offsets, uint[] byteCounts, List? exifIfd0) { var ifd = new IfdBuilder(); // The Exif block's IFD0 tags first, so every tag the page sets below (resolution, and Artist / Software when the @@ -145,10 +151,10 @@ private static IfdBuilder BuildIfd(IImageSource source, TiffPageOptions options, foreach (var entry in exifIfd0) ifd.Set(entry); - ifd.SetLong(TiffTag.ImageWidth, (uint)source.Width); - ifd.SetLong(TiffTag.ImageLength, (uint)source.Height); - ifd.SetShort(TiffTag.Compression, (ushort)(source.IsPreCompressed ? source.Compression : options.Compression)); - ifd.SetShort(TiffTag.PhotometricInterp, (ushort)source.Photometric); + ifd.SetLong(TiffTag.ImageWidth, (uint)width); + ifd.SetLong(TiffTag.ImageLength, (uint)height); + ifd.SetShort(TiffTag.Compression, (ushort)compression); + ifd.SetShort(TiffTag.PhotometricInterp, (ushort)photometric); ifd.SetShort(TiffTag.SamplesPerPixel, (ushort)options.SamplesPerPixel); ifd.SetShort(TiffTag.PlanarConfig, (ushort)TiffPlanarConfig.Contig); @@ -175,7 +181,7 @@ private static IfdBuilder BuildIfd(IImageSource source, TiffPageOptions options, } else { - var rowsPerStrip = options.RowsPerStrip > 0 ? options.RowsPerStrip : source.Height; + var rowsPerStrip = options.RowsPerStrip > 0 ? options.RowsPerStrip : height; ifd.SetLong(TiffTag.RowsPerStrip, (uint)rowsPerStrip); ifd.SetLongArray(TiffTag.StripOffsets, offsets); ifd.SetLongArray(TiffTag.StripByteCounts, byteCounts); @@ -292,12 +298,28 @@ private async Task EnsureHeaderAsync(CancellationToken ct) await _target.WriteAsync(header, ct).ConfigureAwait(false); } - /// Deflate data with ZLIB framing, using BCL ZLibStream. + /// + /// How many bytes at a time a segment is handed to the deflater. The deflater's output depends on how its input is + /// split, so every path feeds it the same pieces: whole -byte slices of the segment, then + /// the rest. That makes a segment's compressed bytes a function of its pixels alone, so the streaming session + /// (which sees rows a band at a time) writes the very bytes this writer does, holding one slice, not one strip. + /// + internal const int DeflateChunk = 64 * 1024; + + /// Deflate data with ZLIB framing, using BCL ZLibStream, fed bytes at a time. internal static byte[] DeflateZlib(ReadOnlySpan data) { using var ms = new MemoryStream(); - using (var z = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) - z.Write(data); + using (var z = NewDeflater(ms)) + while (!data.IsEmpty) + { + var n = Math.Min(DeflateChunk, data.Length); + z.Write(data[..n]); + data = data[n..]; + } return ms.ToArray(); } + + /// The deflater every segment goes through (ZLIB framing, ). + internal static ZLibStream NewDeflater(Stream output) => new(output, CompressionLevel.Optimal, leaveOpen: true); } diff --git a/tests/Sdcb.SimdCodecs.Tests/TiffStreamingEncodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/TiffStreamingEncodeTests.cs new file mode 100644 index 0000000..786925b --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/TiffStreamingEncodeTests.cs @@ -0,0 +1,451 @@ +using System.Buffers; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Tests.Streaming; +using Sdcb.SimdCodecs.Tiff; +using Shouldly; +using MagickExifTag = ImageMagick.ExifTag; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// , the streaming TIFF session over a seekable stream: +/// its file equals the buffered session's byte for byte for every input format, compression, layout and page count, it +/// decodes (with our reader and with libtiff through Magick.NET) to exactly the stored pixels, bytes reach the stream +/// before Commit, and its memory is a band, not the image. +/// +public sealed class TiffStreamingEncodeTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// Photo-like samples (smooth gradients plus a little noise), so deflate has work to do and a strip is not a + /// run of one value. + private static byte[] Photo(PixelFormat format, int width, int height, int seed) + { + var bytes = new byte[width * height * format.BytesPerPixel]; + FillPhotoRows(bytes, format, width, 0, height, seed); + return bytes; + } + + private static void FillPhotoRows(Span rows, PixelFormat format, int width, int y0, int count, int seed) + { + var bpp = format.BytesPerPixel; + var rowBytes = width * bpp; + for (var y = 0; y < count; y++) + { + var row = rows.Slice(y * rowBytes, rowBytes); + var yy = y0 + y; + for (var i = 0; i < rowBytes; i++) + { + var x = i / bpp; + var c = i % bpp; + var noise = (uint)((x * 73856093) ^ (yy * 19349663) ^ (c * 83492791) ^ seed) * 2654435761u >> 29; + row[i] = (byte)((x * (c + 1) + yy * (3 - c % 3)) / 4 + noise); + } + } + } + + /// Feeds to in random bands of 1..17 rows at a padded stride. + private static void Push(IImageFrameEncoder frame, byte[] pixels, int width, int height, PixelFormat format, int seed) + { + var rowBytes = width * format.BytesPerPixel; + var stride = rowBytes + 3; + var random = new Random(seed); + var y = 0; + while (y < height) + { + var n = Math.Min(height - y, random.Next(1, 18)); + var band = new byte[stride * n]; + for (var r = 0; r < n; r++) + pixels.AsSpan((y + r) * rowBytes, rowBytes).CopyTo(band.AsSpan(r * stride)); + // Half the bands packed (the session's one-piece path), half padded (its row-at-a-time path). + if (random.Next(2) == 0) + { + var packed = new byte[rowBytes * n]; + pixels.AsSpan(y * rowBytes, rowBytes * n).CopyTo(packed); + frame.WriteRows(packed, n, 0, Ct); + } + else + { + frame.WriteRows(band, n, stride, Ct); + } + y += n; + } + } + + private sealed record Page(byte[] Pixels, int Width, int Height, PixelFormat Format, ImageMetadata? Metadata = null); + + private static byte[] Buffered(TiffEncodeOptions? options, params Page[] pages) + { + var output = new ArrayBufferWriter(); + using (var session = TiffImageEncoder.Create(output, options)) + { + session.IsStreaming.ShouldBeFalse(); + foreach (var p in pages) + Push(session.AddFrame(p.Width, p.Height, p.Format, null, p.Metadata), p.Pixels, p.Width, p.Height, p.Format, 7); + session.Commit(Ct); + } + return output.WrittenSpan.ToArray(); + } + + private static byte[] Streamed(TiffEncodeOptions? options, params Page[] pages) + { + using var stream = new MemoryStream(); + using (var session = TiffImageEncoder.Create(stream, options, leaveOpen: true)) + { + session.IsStreaming.ShouldBeTrue(); + var seed = 11; + foreach (var p in pages) + Push(session.AddFrame(p.Width, p.Height, p.Format, null, p.Metadata), p.Pixels, p.Width, p.Height, p.Format, seed++); + session.Commit(Ct); + } + return stream.ToArray(); + } + + private static void ShouldBeSameFile(byte[] actual, byte[] expected, string what) + { + if (actual.AsSpan().SequenceEqual(expected)) return; + var at = actual.AsSpan().CommonPrefixLength(expected); + throw new ShouldAssertException($"{what}: streamed file ({actual.Length} B) differs from the buffered one ({expected.Length} B) at byte {at}."); + } + + /// Our reader's pixels of page , which must be . + private static void DecodesTo(byte[] file, int index, byte[] expected, PixelFormat native, string what) + { + TiffImageDecoder.TryOpenFrames(file, out var reader).ShouldBeTrue(what); + using (reader) + { + reader!.TryDecodeFrame(index, out var image, cancellationToken: Ct).ShouldBeTrue(what); + using (image) + { + image!.Channels.ShouldBe(native.Channels, what); + image.SampleFormat.ShouldBe(native.Sample, what); + image.Pixels.SequenceEqual(expected).ShouldBeTrue($"{what}: decoded pixels differ"); + } + } + } + + public static TheoryData Layouts() => new() + { + { TiffCompression.Uncompressed, TiffLayout.Strip, 0 }, + { TiffCompression.Uncompressed, TiffLayout.Strip, 1 }, + { TiffCompression.Uncompressed, TiffLayout.Strip, 5 }, + { TiffCompression.Uncompressed, TiffLayout.Tiled, 0 }, + { TiffCompression.Deflate, TiffLayout.Strip, 0 }, + { TiffCompression.Deflate, TiffLayout.Strip, 1 }, + { TiffCompression.Deflate, TiffLayout.Strip, 7 }, + { TiffCompression.Deflate, TiffLayout.Tiled, 0 }, + { TiffCompression.ZlibPkzip, TiffLayout.Strip, 4 }, + { TiffCompression.ZlibPkzip, TiffLayout.Tiled, 0 }, + }; + + [Theory] + [MemberData(nameof(Layouts))] + public void Every_format_streams_the_buffered_file(TiffCompression compression, TiffLayout layout, int rowsPerStrip) + { + var options = new TiffEncodeOptions + { + Page = new TiffPageOptions { Compression = compression, Layout = layout, RowsPerStrip = rowsPerStrip, TileWidth = 16, TileHeight = 32 }, + }; + foreach (var format in PixelFormat.All) + { + const int w = 37, h = 41; // odd: partial strips, partial tiles on the right and bottom, odd segment lengths + var pixels = Photo(format, w, h, 1); + var page = new Page(pixels, w, h, format); + var streamed = Streamed(options, page); + ShouldBeSameFile(streamed, Buffered(options, page), format.ToString()); + var native = TiffImageEncoder.GetClosestInputFormat(format); + DecodesTo(streamed, 0, PixelConverter.ToPacked(pixels, 0, format, native, w, h), native, format.ToString()); + } + } + + /// Strips and tiles longer than the deflater's input slice, fed in bands that straddle its boundaries. + [Theory] + [InlineData(TiffLayout.Strip, 0)] + [InlineData(TiffLayout.Strip, 61)] + [InlineData(TiffLayout.Tiled, 0)] + public void Segments_longer_than_a_deflate_slice_stream_the_buffered_file(TiffLayout layout, int rowsPerStrip) + { + var options = new TiffEncodeOptions + { + Page = new TiffPageOptions { Layout = layout, RowsPerStrip = rowsPerStrip, TileWidth = 160, TileHeight = 128 }, + }; + foreach (var format in new[] { PixelFormat.Rgba64, PixelFormat.Bgr24, PixelFormat.Gray8 }) + { + const int w = 333, h = 257; + var page = new Page(Photo(format, w, h, 2), w, h, format); + ShouldBeSameFile(Streamed(options, page), Buffered(options, page), $"{format} {layout}"); + } + } + + [Fact] + public void Multi_page_with_metadata_streams_the_buffered_file_and_libtiff_reads_every_page() + { + var exif = new ExifProfile(); + exif.SetValue(MagickExifTag.Make, "TestCam"); + exif.SetValue(MagickExifTag.DateTimeOriginal, "2026:11:23 10:20:30"); + exif.SetValue(MagickExifTag.GPSLatitudeRef, "N"); + var icc = new byte[300]; + new Random(3).NextBytes(icc); + var metadata = new ImageMetadata { Icc = icc, Xmp = ""u8.ToArray(), Exif = exif.ToByteArray()! }; + + var pages = new[] + { + new Page(Photo(PixelFormat.Rgb24, 51, 33, 4), 51, 33, PixelFormat.Rgb24, metadata), + new Page(Photo(PixelFormat.Gray16, 20, 70, 5), 20, 70, PixelFormat.Gray16), + new Page(Photo(PixelFormat.Bgra32, 64, 9, 6), 64, 9, PixelFormat.Bgra32, new ImageMetadata { Xmp = ""u8.ToArray() }), + }; + var options = new TiffEncodeOptions { Page = new TiffPageOptions { RowsPerStrip = 8, Software = "streaming test" } }; + var streamed = Streamed(options, pages); + ShouldBeSameFile(streamed, Buffered(options, pages), "three pages"); + + using var collection = new MagickImageCollection(streamed); + collection.Count.ShouldBe(pages.Length); + for (var i = 0; i < pages.Length; i++) + { + var p = pages[i]; + var native = TiffImageEncoder.GetClosestInputFormat(p.Format); + var expected = PixelConverter.ToPacked(p.Pixels, 0, p.Format, native, p.Width, p.Height); + DecodesTo(streamed, i, expected, native, $"page {i}"); + MagickPixels(collection[i], native).ShouldBe(expected, $"page {i} through libtiff"); + } + collection[0].GetAttribute("tiff:make").ShouldBe("TestCam"); // libtiff reports IFD0's Make as tiff:make + collection[0].GetColorProfile()!.ToByteArray().ShouldBe(icc); + } + + /// libtiff's (Magick.NET's) reading of a page, packed in layout. + private static byte[] MagickPixels(IMagickImage image, PixelFormat native) + { + var map = native.Layout switch + { + ChannelLayout.Rgba => "RGBA", + ChannelLayout.Rgb => "RGB", + ChannelLayout.GrayAlpha => "RA", + _ => "R", + }; + using var px = image.GetPixelsUnsafe(); + if (native.Sample == SampleFormat.UInt8) + return px.ToByteArray(map)!; + var shorts = px.ToShortArray(map)!; + var bytes = new byte[shorts.Length * 2]; + Buffer.BlockCopy(shorts, 0, bytes, 0, bytes.Length); + return bytes; + } + + [Fact] + public void Bytes_reach_the_stream_before_commit() + { + const int w = 300, h = 200; + var pixels = Photo(PixelFormat.Rgb24, w, h, 8); + foreach (var (compression, rowsPerStrip) in new[] { (TiffCompression.Deflate, 16), (TiffCompression.Uncompressed, 16), (TiffCompression.Deflate, 0) }) + { + var options = new TiffEncodeOptions { Page = new TiffPageOptions { Compression = compression, RowsPerStrip = rowsPerStrip } }; + using var stream = new MemoryStream(); + using var session = TiffImageEncoder.Create(stream, options, leaveOpen: true); + var frame = session.AddFrame(w, h, PixelFormat.Rgb24); + var half = h / 2; + frame.WriteRows(pixels.AsSpan(0, half * w * 3), half, 0, Ct); + // Six strips are complete by now; a default strip (the whole page) still streams, as the deflater has had + // 90 KB of input. Either way more than the 8-byte header is out. + stream.Length.ShouldBeGreaterThan(compression == TiffCompression.Uncompressed ? 8 + 6 * 16 * w * 3 : 8, + $"{compression} / {rowsPerStrip} rows per strip"); + frame.WriteRows(pixels.AsSpan(half * w * 3), h - half, 0, Ct); + session.Commit(Ct); + ShouldBeSameFile(stream.ToArray(), Buffered(options, new Page(pixels, w, h, PixelFormat.Rgb24)), $"{compression}"); + } + } + + /// + /// End to end over a file: an 8192 × 8192 RGB page (192 MiB of pixels) fed in 64-row bands to a + /// allocates a fraction of one strip-free band, the file equals the buffered encode, and our reader decodes it to the + /// pixels. + /// + [Fact] + public void Large_page_streams_to_a_file_in_bounded_memory() + { + const int w = 8192, h = 8192, band = 64; + var format = PixelFormat.Rgb24; + var rowBytes = w * 3; + var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "SimdCodecs-TiffStreamingEncode-" + Guid.NewGuid().ToString("N"))); + try + { + var path = Path.Combine(dir.FullName, "large.tif"); + var rows = new byte[rowBytes * band]; + void Encode() + { + using var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16); + using var session = TiffImageEncoder.Create(file); + var frame = session.AddFrame(w, h, format); + for (var y = 0; y < h; y += band) + { + FillPhotoRows(rows, format, w, y, band, 9); + frame.WriteRows(rows, band, 0, Ct); + } + session.Commit(Ct); + } + // One band is 1.5 MiB (the caller's); the session holds a 64 KiB deflate slice. + StreamingAssert.AllocatesLessThan(1 << 20, Encode, "streaming an 8192x8192 page"); + + var streamed = File.ReadAllBytes(path); + var pixels = Photo(format, w, h, 9); + ShouldBeSameFile(streamed, Buffered(null, new Page(pixels, w, h, format)), "8192x8192"); + DecodesTo(streamed, 0, pixels, format, "8192x8192"); + } + finally + { + dir.Delete(recursive: true); + } + } + + /// A large synthetic photo streamed to a file decodes, with our reader and with libtiff, to the exact pixels. + [Fact] + public void Photo_streamed_to_a_file_decodes_exactly_with_libtiff() + { + const int w = 2400, h = 1600; + var format = PixelFormat.Bgra32; + var pixels = Photo(format, w, h, 10); + var native = TiffImageEncoder.GetClosestInputFormat(format); + var expected = PixelConverter.ToPacked(pixels, 0, format, native, w, h); + var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "SimdCodecs-TiffStreamingEncode-" + Guid.NewGuid().ToString("N"))); + try + { + var path = Path.Combine(dir.FullName, "photo.tif"); + var options = new TiffEncodeOptions { Page = new TiffPageOptions { RowsPerStrip = 32 } }; + using (var file = File.Create(path)) + using (var session = TiffImageEncoder.Create(file, options)) + { + Push(session.AddFrame(w, h, format), pixels, w, h, format, 12); + session.Commit(Ct); + } + var streamed = File.ReadAllBytes(path); + ShouldBeSameFile(streamed, Buffered(options, new Page(pixels, w, h, format)), "photo"); + DecodesTo(streamed, 0, expected, native, "photo"); + using var magick = new MagickImage(path); + MagickPixels(magick, native).ShouldBe(expected); + } + finally + { + dir.Delete(recursive: true); + } + } + + [Fact] + public void File_starts_at_the_streams_position() + { + const int w = 40, h = 30; + var page = new Page(Photo(PixelFormat.Rgb24, w, h, 13), w, h, PixelFormat.Rgb24); + var options = new TiffEncodeOptions { Page = new TiffPageOptions { RowsPerStrip = 7 } }; + using var stream = new MemoryStream(); + stream.Write("prefix-"u8); + using (var session = TiffImageEncoder.Create(stream, options, leaveOpen: true)) + { + Push(session.AddFrame(w, h, page.Format), page.Pixels, w, h, page.Format, 1); + Push(session.AddFrame(w, h, page.Format), page.Pixels, w, h, page.Format, 2); + session.Commit(Ct); + } + var all = stream.ToArray(); + all.AsSpan(0, 7).SequenceEqual("prefix-"u8).ShouldBeTrue(); + ShouldBeSameFile(all[7..], Buffered(options, page, page), "after a prefix"); + } + + [Fact] + public void Disposing_closes_the_stream_unless_left_open() + { + var closed = new MemoryStream(); + TiffImageEncoder.Create(closed).Dispose(); + closed.CanWrite.ShouldBeFalse(); + var open = new MemoryStream(); + TiffImageEncoder.Create(open, leaveOpen: true).Dispose(); + open.CanWrite.ShouldBeTrue(); + } + + [Fact] + public void Non_seekable_or_read_only_stream_is_refused() + { + var e = Should.Throw(() => TiffImageEncoder.Create(new NonSeekableStream())); + e.Message.ShouldContain("IBufferWriter"); + Should.Throw(() => TiffImageEncoder.Create(new MemoryStream([], writable: false))); + Should.Throw(() => TiffImageEncoder.Create((Stream)null!)); + Should.Throw(() => TiffImageEncoder.Create(new MemoryStream(), new Sdcb.SimdCodecs.Jpeg.JpegEncodeOptions())); + } + + [Fact] + public void A_page_the_writer_cannot_encode_fails_at_AddFrame_before_a_byte_is_written() + { + using var stream = new MemoryStream(); + using (var session = TiffImageEncoder.Create(stream, new TiffEncodeOptions { Page = new TiffPageOptions { Compression = TiffCompression.Lzw } }, leaveOpen: true)) + Should.Throw(() => session.AddFrame(4, 4, PixelFormat.Rgb24)); + using (var session = TiffImageEncoder.Create(stream, new TiffEncodeOptions { Page = new TiffPageOptions { Exif = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 } } }, leaveOpen: true)) + Should.Throw(() => session.AddFrame(4, 4, PixelFormat.Rgb24)); + stream.Length.ShouldBe(0); + } + + [Fact] + public void Cancellation_stops_the_session() + { + using var cts = new CancellationTokenSource(); + cts.Cancel(); + using var stream = new MemoryStream(); + using var session = TiffImageEncoder.Create(stream, leaveOpen: true); + var frame = session.AddFrame(8, 8, PixelFormat.Rgb24); + var rows = new byte[8 * 8 * 3]; + Should.Throw(() => frame.WriteRows(rows, 8, 0, cts.Token)); + frame.WriteRows(rows, 8, 0, Ct); + Should.Throw(() => session.Commit(cts.Token)); + } + + [Fact] + public void A_write_that_fails_partway_ends_the_session() + { + const int w = 64, h = 64; + var rows = Photo(PixelFormat.Rgb24, w, h, 14); + var options = new TiffEncodeOptions { Page = new TiffPageOptions { Compression = TiffCompression.Uncompressed, RowsPerStrip = 4 } }; + using var stream = new FailingStream(failAfter: 8 + 3 * 4 * w * 3); // fails inside the fourth strip of the first band + using var session = TiffImageEncoder.Create(stream, options, leaveOpen: true); + var frame = session.AddFrame(w, h, PixelFormat.Rgb24); + Should.Throw(() => frame.WriteRows(rows, 32, 0, Ct)); + frame.RowsWritten.ShouldBe(0); + Should.Throw(() => frame.WriteRows(rows, 32, 0, Ct)); + } + + private sealed class FailingStream(long failAfter) : MemoryStream + { + public override void Write(ReadOnlySpan buffer) + { + Check(buffer.Length); + base.Write(buffer); + } + + public override void Write(byte[] buffer, int offset, int count) + { + Check(count); + base.Write(buffer, offset, count); + } + + public override void WriteByte(byte value) + { + Check(1); + base.WriteByte(value); + } + + private void Check(int count) + { + if (Position + count > failAfter) + throw new IOException("disk full"); + } + } + + private sealed class NonSeekableStream : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) { } + } +}