From f78557534c42caad15e70d97d16e1e2fb6108e98 Mon Sep 17 00:00:00 2001 From: sdcb Date: Mon, 23 Nov 2026 20:07:18 +0800 Subject: [PATCH] Tiff: streaming row reader for seekable streams; Read(Stream) reads by offset TiffImageDecoder implements IStreamingImageDecoder. On a seekable stream the reader parses the first page's directory by offset (the span parser, rerun over the ranges fetched so far), walks the IFD chain for FrameCount, then fetches one strip or row of tiles at a time (every plane's segments) and decodes it with the same DecodeBand / ConvertRow path as TryDecodeInto. Rewinds seek; forward moves read through, so files that would read more than twice their length (planes stored far apart, chains jumping back and forth) are decoded whole instead, as are non-seekable streams, float pages and non-full-image options. TiffReader.Read(Stream) on a seekable stream now reads the header, directories and segments by offset instead of copying the stream; ReadPage/ReadCore are generic over ITiffBytes, so the span path is the same code. Co-Authored-By: Claude Opus 5.5 --- .../PublicAPI.Unshipped.txt | 1 + src/Sdcb.SimdCodecs.Tiff/README.md | 2 + src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs | 53 +- src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs | 56 +- .../TiffReader.Segment.cs | 6 +- src/Sdcb.SimdCodecs.Tiff/TiffReader.cs | 98 ++- src/Sdcb.SimdCodecs.Tiff/TiffRowReader.cs | 474 +++++++++++++++ .../TiffRobustnessTests.cs | 2 +- .../TiffStreamingDecodeTests.cs | 557 ++++++++++++++++++ 9 files changed, 1192 insertions(+), 57 deletions(-) create mode 100644 src/Sdcb.SimdCodecs.Tiff/TiffRowReader.cs create mode 100644 tests/Sdcb.SimdCodecs.Tests/TiffStreamingDecodeTests.cs diff --git a/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt b/src/Sdcb.SimdCodecs.Tiff/PublicAPI.Unshipped.txt index 7dc5c58..a36a3da 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.TiffImageDecoder.CreateRowReader(Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamInput! input, Sdcb.SimdCodecs.Abstractions.PixelFormat format, Sdcb.SimdCodecs.Abstractions.DecodeOptions? options) -> Sdcb.SimdCodecs.Abstractions.CodecSupport.StreamingRowReader! diff --git a/src/Sdcb.SimdCodecs.Tiff/README.md b/src/Sdcb.SimdCodecs.Tiff/README.md index f656537..9137986 100644 --- a/src/Sdcb.SimdCodecs.Tiff/README.md +++ b/src/Sdcb.SimdCodecs.Tiff/README.md @@ -42,6 +42,8 @@ Old-style JPEG (Compression 6), CIELab, subsampled YCbCr stored in separate plan A `DecodeOptions.Region` reads only the strips or tiles it intersects, and `TryDecodeInto` writes integer pages band by band into the caller's buffer without a page raster; both give exactly the pixels of decoding the page whole and then cropping and converting it (`TiffRegionDecodeTests`). +`TiffImageDecoder.CreateRowReader` reads the first page from a stream, rows top to bottom, synchronously or asynchronously, with exactly `TryDecodeInto`'s rows (`TiffStreamingDecodeTests`). A TIFF needs random access, so it streams only from a seekable stream: it reads the directory by offset, then one strip or row of tiles at a time, holding that band and its coded bytes rather than the file or the page. A stream that cannot seek, a float page, an option other than the whole image at full size, and a file whose bands or directories lie so scattered that streaming would read through more than twice the file (separate planes stored one after another, as libtiff writes them) are read whole and decoded instead; `IsStreaming` says which. `TiffReader.Read(Stream)` reads a seekable stream by offset as well, without copying it. + ## 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. diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs b/src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs index 1c76c59..eb21cb0 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffIfd.cs @@ -13,6 +13,13 @@ internal interface ITiffBytes /// Fills from ; throws when the range is not inside the file. void Read(long offset, scoped Span destination); + + /// + /// bytes from , where the caller checked they lie inside the file: + /// a slice of the bytes when they are in memory, else read into (rented from the shared + /// pool, grown as needed; the caller returns it). Valid until the next call with the same buffer. + /// + ReadOnlySpan View(long offset, int length, ref byte[]? buffer); } internal readonly ref struct SpanBytes(ReadOnlySpan bytes) : ITiffBytes @@ -27,18 +34,44 @@ public void Read(long offset, scoped Span destination) throw new InvalidDataException("TIFF data extends past the end of the file"); _bytes.Slice((int)offset, destination.Length).CopyTo(destination); } + + public ReadOnlySpan View(long offset, int length, ref byte[]? buffer) + { + if (offset < 0 || offset + length > _bytes.Length) + throw new InvalidDataException("TIFF data extends past the end of the file"); + return _bytes.Slice((int)offset, length); + } } -/// A seekable stream as TIFF bytes. Every read seeks, so only what is asked for is touched. +internal static class TiffBuffers +{ + /// Rents from the shared pool at bytes or more; returns its first bytes. + public static Span Ensure(ref byte[]? buffer, int length) + { + if (buffer is null || buffer.Length < length) + { + if (buffer is not null) System.Buffers.ArrayPool.Shared.Return(buffer); + buffer = System.Buffers.ArrayPool.Shared.Rent(length); + } + return buffer.AsSpan(0, length); + } +} + +/// +/// A seekable stream as TIFF bytes, offsets counted from origin (where the TIFF starts in the stream). Every +/// read seeks, so only what is asked for is touched. +/// internal sealed class StreamBytes : ITiffBytes { private readonly Stream _stream; + private readonly long _origin; - public StreamBytes(Stream stream) + public StreamBytes(Stream stream, long origin = 0) { if (!stream.CanSeek) throw new ArgumentException("The stream must be seekable", nameof(stream)); _stream = stream; - Length = stream.Length; + _origin = origin; + Length = Math.Max(0, stream.Length - origin); } public long Length { get; } @@ -47,7 +80,7 @@ public void Read(long offset, scoped Span destination) { if (offset < 0 || offset + destination.Length > Length) throw new InvalidDataException("TIFF data extends past the end of the file"); - _stream.Position = offset; + _stream.Position = _origin + offset; var done = 0; while (done < destination.Length) { @@ -56,6 +89,13 @@ public void Read(long offset, scoped Span destination) done += n; } } + + public ReadOnlySpan View(long offset, int length, ref byte[]? buffer) + { + var span = TiffBuffers.Ensure(ref buffer, length); + Read(offset, span); + return span; + } } /// @@ -123,7 +163,7 @@ internal static class TiffIfdParser internal const int MaxSamplesPerPixel = 256; /// Entries a BigTIFF directory may declare (its count is 64-bit); a classic one holds at most 65535. - private const long MaxEntries = 1 << 20; + internal const long MaxEntries = 1 << 20; /// /// Parses the header at the start of : classic TIFF (TIFF 6.0 §2, 8 bytes) or BigTIFF (the @@ -575,7 +615,8 @@ private static byte[] Value(ref T src, ulong count, int elemSize, ReadOnlySpa var total = (long)count * elemSize; if (total <= f.OffsetSize) return valueSpan[..(int)total].ToArray(); var offset = Offset(valueSpan, f); - if (total > src.Length || offset > src.Length - total) + // A stream may be longer than an array holds; a span never is, so the last test changes nothing for it. + if (total > src.Length || offset > src.Length - total || total > Array.MaxLength) throw new InvalidDataException("Tag value extends past the end of the file"); var buffer = new byte[total]; src.Read(offset, buffer); diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs b/src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs index cb0b092..c97906d 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffImageDecoder.cs @@ -40,7 +40,7 @@ namespace Sdcb.SimdCodecs.Tiff; /// per row of tiles and per page. /// /// -public sealed class TiffImageDecoder : IMultiFrameImageDecoder +public sealed class TiffImageDecoder : IMultiFrameImageDecoder, IStreamingImageDecoder { /// The registration for ImageCodecs.Register, built from this type's method groups. public static ImageDecoderRegistration Registration { get; } = new() @@ -55,6 +55,7 @@ public sealed class TiffImageDecoder : IMultiFrameImageDecoder TryReadMetadata = TryReadMetadata, TryDecodeThumbnail = TryDecodeThumbnail, TryOpenFrames = TryOpenFrames, + CreateRowReader = CreateRowReader, }; /// @@ -117,6 +118,21 @@ public static bool TryOpenFrames(ReadOnlyMemory data, [NotNullWhen(true)] return true; } + /// + /// + /// The first page, a band of rows at a time. TIFF needs random access (the directory is usually written after the + /// pixels), so the reader streams only when the stream can seek: it reads the header, the first page's directory + /// and the IFD chain's next pointers by offset, then each strip, or row of tiles (every plane's segments, for a + /// planar page), decodes it exactly as does and hands out its rows; it holds one band + /// and its coded bytes, never the file or the page. The input moves forward only by reading, so a file whose bands + /// (or directories) would make it read through more than twice the file -- separate planes stored one after another, + /// a chain that jumps back and forth -- is decoded whole instead, as are a stream that cannot seek, a float page + /// (which has no integer projection for) and any option but the whole image at full + /// size ( false). The rows are 's either way. + /// + public static StreamingRowReader CreateRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) => + new TiffRowReader(input, format, options); + /// The layout gives page , from its directory alone. internal static bool TryReadPageInfo(ReadOnlySpan data, int pageIndex, out ImageInfo info) { @@ -126,14 +142,7 @@ internal static bool TryReadPageInfo(ReadOnlySpan data, int pageIndex, out var layout = TiffReader.ReadLayout(data, pageIndex); if (!TiffColor.TryCreate(layout, out var plan)) return false; - info = new ImageInfo(layout.Width, layout.Height, plan.OutChannels, plan.OutFormat) - { - Format = ImageFormat.Tiff, - BitDepth = layout.Photometric == TiffPhotometric.Palette ? (layout.StoredBitsPerSample == 16 ? 16 : 8) : layout.StoredBitsPerSample, - Orientation = (ImageOrientation)layout.Orientation, - ColorEncoding = ColorOf(layout), - Resolution = ResolutionOf(layout), - }; + info = InfoOf(layout, plan); return true; } catch (Exception e) when (e is InvalidDataException or ArgumentException or NotSupportedException) @@ -142,6 +151,17 @@ internal static bool TryReadPageInfo(ReadOnlySpan data, int pageIndex, out } } + /// The of the page describes (one frame). + internal static ImageInfo InfoOf(TiffPageLayout layout, TiffColor plan) => + new(layout.Width, layout.Height, plan.OutChannels, plan.OutFormat) + { + Format = ImageFormat.Tiff, + BitDepth = layout.Photometric == TiffPhotometric.Palette ? (layout.StoredBitsPerSample == 16 ? 16 : 8) : layout.StoredBitsPerSample, + Orientation = (ImageOrientation)layout.Orientation, + ColorEncoding = ColorOf(layout), + Resolution = ResolutionOf(layout), + }; + /// /// TIFF has no scaling. Integer pages are decoded strip by strip (or by row of tiles) straight into /// : only the segments a intersects are read, and @@ -187,6 +207,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan data, int pageIndex, S var bandRows = Math.Min(layout.Geometry.SegmentHeight, rect.Height); var bandStride = rect.Width * plan.OutBytesPerPixel; var band = ArrayPool.Shared.Rent(bandRows * bandStride); + var src = new SpanBytes(data); try { var first = layout.Geometry.DownIndexForRow(rect.Y); @@ -195,7 +216,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan data, int pageIndex, S { cancellationToken.ThrowIfCancellationRequested(); var (y0, rows) = BandRows(layout, rect, down); - DecodeBand(data, layout, plan, rect, down, band.AsSpan(0, rows * bandStride), bandStride); + DecodeBand(ref src, layout, plan, rect, down, band.AsSpan(0, rows * bandStride), bandStride); for (var r = 0; r < rows; r++) { PixelConverter.ConvertRow(band.AsSpan(r * bandStride, bandStride), plan.OutChannels, plan.OutFormat, @@ -215,7 +236,7 @@ internal static bool TryDecodePageInto(ReadOnlySpan data, int pageIndex, S } /// The first image row of segment row inside , and how many there are. - private static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect, int down) + internal static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect, int down) { var g = layout.Geometry; var y0 = Math.Max(rect.Y, g.FirstRow(down)); @@ -231,8 +252,8 @@ private static (int Y0, int Rows) BandRows(TiffPageLayout layout, PixelRect rect /// equals the same rectangle of the whole page; a chunky strip the file does not list (a short strip list, which /// the whole-page read tolerates) is left as zeros, as the whole-page read leaves it. /// - private static void DecodeBand(ReadOnlySpan data, TiffPageLayout layout, TiffColor plan, PixelRect rect, - int down, Span band, int bandStride) + internal static void DecodeBand(ref T src, TiffPageLayout layout, TiffColor plan, PixelRect rect, + int down, Span band, int bandStride) where T : ITiffBytes, allows ref struct { var g = layout.Geometry; var (y0, rows) = BandRows(layout, rect, down); @@ -261,7 +282,7 @@ private static void DecodeBand(ReadOnlySpan data, TiffPageLayout layout, T if (segment is not null) ArrayPool.Shared.Return(segment); segment = ArrayPool.Shared.Rent(need); } - TiffReader.ReadSegment(data, layout, index, segment); + TiffReader.ReadSegmentCore(ref src, layout, index, segment); var segStride = seg.Width * inBpp; for (var r = 0; r < rows; r++) { @@ -369,6 +390,7 @@ internal static IDecodedImage DecodePage(ReadOnlySpan data, int pageIndex, try { var target = result.WritablePixels; + var src = new SpanBytes(data); var bandStride = region.Width * plan.OutBytesPerPixel; var first = layout.Geometry.DownIndexForRow(region.Y); var last = layout.Geometry.DownIndexForRow(region.Y + region.Height - 1); @@ -376,7 +398,7 @@ internal static IDecodedImage DecodePage(ReadOnlySpan data, int pageIndex, { cancellationToken.ThrowIfCancellationRequested(); var (y0, rows) = BandRows(layout, region, down); - DecodeBand(data, layout, plan, region, down, + DecodeBand(ref src, layout, plan, region, down, target.Slice((y0 - region.Y) * bandStride, rows * bandStride), bandStride); } } @@ -427,12 +449,12 @@ internal static IDecodedImage DecodePage(ReadOnlySpan data, int pageIndex, // A reader exception other than InvalidDataException (an argument the file's numbers make invalid, a compression // or layout the reader does not support) as the InvalidDataException Decode throws for untrusted input. - private static InvalidDataException Undecodable(Exception e) => + internal static InvalidDataException Undecodable(Exception e) => new(e is NotSupportedException ? $"The TIFF uses a feature this decoder does not support: {e.Message}" : $"The TIFF data is invalid: {e.Message}", e); // The refusal of TiffColor.TryCreate, named: what the page stores that IDecodedImage has no layout for. - private static InvalidDataException Unpresentable(TiffPageLayout layout, int pageIndex) => + internal static InvalidDataException Unpresentable(TiffPageLayout layout, int pageIndex) => new($"Page {pageIndex + 1} stores {layout.SamplesPerPixel} sample(s) per pixel of {layout.BitsPerSample}-bit " + $"{layout.SampleFormat} data as {layout.Photometric}, a layout this decoder does not present (it decodes grey, " + "RGB, palette, CMYK and YCbCr with 8- or 16-bit unsigned samples, and grey or RGB with 16- or 32-bit float samples)."); diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffReader.Segment.cs b/src/Sdcb.SimdCodecs.Tiff/TiffReader.Segment.cs index daff0ce..e9406da 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffReader.Segment.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffReader.Segment.cs @@ -253,7 +253,7 @@ public static TiffSegmentRect ReadSegment(string path, TiffPageLayout layout, in private static FileStream OpenForSegments(string path) => new(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1); - private static TiffPageLayout ReadLayoutCore(ref T src, int pageIndex) where T : ITiffBytes, allows ref struct + internal static TiffPageLayout ReadLayoutCore(ref T src, int pageIndex) where T : ITiffBytes, allows ref struct { ArgumentOutOfRangeException.ThrowIfNegative(pageIndex); var (format, ifdOffset) = TiffIfdParser.ReadHeader(ref src); @@ -273,7 +273,7 @@ private static TiffPageLayout ReadLayoutCore(ref T src, int pageIndex) where return new TiffPageLayout(pageIndex, format, TiffIfdParser.Parse(ref src, ifdOffset, format), ifdOffset); } - private static TiffSegmentRect ReadSegmentCore(ref T src, TiffPageLayout layout, int segmentIndex, + internal static TiffSegmentRect ReadSegmentCore(ref T src, TiffPageLayout layout, int segmentIndex, Span destination) where T : ITiffBytes, allows ref struct { var rect = layout.SegmentRectangle(segmentIndex); // throws ArgumentOutOfRangeException @@ -349,7 +349,7 @@ private static TiffSegmentRect ReadSegmentCore(ref T src, TiffPageLayout layo publiclyVisible: true); } - var samples = DecodeSegment(raw, 0, count, index, format, staging, false, scratch, inflateSource, + var samples = DecodeSegment(raw.AsSpan(0, (int)count), format, staging, false, scratch, inflateSource, scratchStream, capacity); // The same normalisation ReadInto applies, at the same widths. diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffReader.cs b/src/Sdcb.SimdCodecs.Tiff/TiffReader.cs index fd89b4b..e13d894 100644 --- a/src/Sdcb.SimdCodecs.Tiff/TiffReader.cs +++ b/src/Sdcb.SimdCodecs.Tiff/TiffReader.cs @@ -58,7 +58,8 @@ public static TiffDocument Read(ReadOnlySpan tiff) var (format, firstIfd) = ReadHeader(tiff); var sink = new BufferingSink(); - return ReadCore(tiff, format, firstIfd, ref sink, attachPixels: true); + var src = new SpanBytes(tiff); + return ReadCore(ref src, format, firstIfd, ref sink, attachPixels: true); } /// @@ -81,11 +82,13 @@ public static TiffDocument ReadInto(ReadOnlySpan tiff, ref TSink si where TSink : ITiffStripSink { var (format, firstIfd) = ReadHeader(tiff); - return ReadCore(tiff, format, firstIfd, ref sink, attachPixels: false); + var src = new SpanBytes(tiff); + return ReadCore(ref src, format, firstIfd, ref sink, attachPixels: false); } - private static TiffDocument ReadCore(ReadOnlySpan tiff, TiffFormat format, long firstIfd, + private static TiffDocument ReadCore(ref TSrc src, TiffFormat format, long firstIfd, ref TSink sink, bool attachPixels) + where TSrc : ITiffBytes, allows ref struct where TSink : ITiffStripSink { var pages = new List(); @@ -96,7 +99,7 @@ private static TiffDocument ReadCore(ReadOnlySpan tiff, TiffFormat var visited = new HashSet(); while (ifdOffset != 0 && visited.Add(ifdOffset)) { - var (page, nextOffset) = ReadPage(tiff, ifdOffset, format, pageIndex, ref sink); + var (page, nextOffset) = ReadPage(ref src, ifdOffset, format, pageIndex, ref sink); // Only the buffering path re-attaches pixels, and it is the sink that holds them: a // streaming caller has already consumed them and gets metadata alone. pages.Add(attachPixels && sink is BufferingSink buffered @@ -181,7 +184,7 @@ public static TiffPage ReadPage(ReadOnlySpan tiff, int pageIndex = 0, Canc throw new ArgumentOutOfRangeException(nameof(pageIndex), "The file has fewer pages"); var sink = new BufferingSink(); - var (page, _) = ReadPage(tiff, ifdOffset, format, pageIndex, ref sink, cancellationToken); + var (page, _) = ReadPage(ref src, ifdOffset, format, pageIndex, ref sink, cancellationToken); return page with { Pixels = sink.TakePixels() }; } @@ -193,6 +196,12 @@ public static TiffPage ReadPage(ReadOnlySpan tiff, int pageIndex = 0, Canc internal static int CountPages(ReadOnlySpan tiff) { var src = new SpanBytes(tiff); + return CountPages(ref src); + } + + /// + internal static int CountPages(ref T src) where T : ITiffBytes, allows ref struct + { var (format, ifdOffset) = TiffIfdParser.ReadHeader(ref src); var visited = new HashSet(); var pages = 0; @@ -211,28 +220,44 @@ internal static int CountPages(ReadOnlySpan tiff) return pages; } - /// Decode every page from a TIFF stream (slurped to a byte array). + /// Decode every page from a TIFF stream, which starts at the stream's current position. + /// A seekable stream is read by offset -- the header, each directory and its tag arrays, then each strip + /// or tile -- and never copied whole; the stream is left at its end, as reading it through would. Any other stream + /// is read to its end first. Either way the pages are those of over the + /// same bytes. public static TiffDocument Read(Stream stream) { - // TIFF readers need random access via the IFD chain — slurp the stream - // and operate on the in-memory span. For very large TIFFs the caller - // should map the file (MemoryMappedFile) and pass that span instead. - // Pre-size when the length is known: MemoryStream grows by doubling, so slurping a - // 100 MB TIFF into a default-capacity stream reallocates a dozen times and copies - // roughly twice the file before the first byte is ever decoded. - var capacity = stream.CanSeek ? (int)Math.Min(int.MaxValue, stream.Length - stream.Position) : 0; - using var ms = new MemoryStream(capacity); + ArgumentNullException.ThrowIfNull(stream); + if (stream.CanSeek) + { + var origin = stream.Position; + var bytes = new StreamBytes(stream, origin); + try + { + var (format, firstIfd) = TiffIfdParser.ReadHeader(ref bytes); + var sink = new BufferingSink(); + return ReadCore(ref bytes, format, firstIfd, ref sink, attachPixels: true); + } + finally + { + stream.Position = Math.Max(origin, stream.Length); + } + } + + // TIFF readers need random access via the IFD chain: a stream that cannot seek is read whole, then decoded as + // a span. + using var ms = new MemoryStream(); stream.CopyTo(ms); return Read(ms.GetBuffer().AsSpan(0, (int)ms.Length)); } - private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan tiff, long ifdOffset, + private static (TiffPage Page, long NextIfdOffset) ReadPage(ref TSrc src, long ifdOffset, TiffFormat fileFormat, int pageIndex, ref TSink sink, CancellationToken cancellationToken = default) + where TSrc : ITiffBytes, allows ref struct where TSink : ITiffStripSink { cancellationToken.ThrowIfCancellationRequested(); // ---- Parse and validate the IFD (shared with the on-demand segment read) ---- - var src = new SpanBytes(tiff); var ifd = TiffIfdParser.Parse(ref src, ifdOffset, fileFormat); var fileIsLE = fileFormat.LittleEndian; var width = ifd.Width; @@ -350,6 +375,7 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< byte[]? inflateSource = null; MemoryStream? scratchStream = null; + byte[]? coded = null; // a segment's coded bytes, when the source is not in memory var staging = format.NeedsStaging ? new SegmentStaging() : null; if (compression is TiffCompression.Deflate or TiffCompression.ZlibPkzip) { @@ -357,7 +383,7 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< // past the end of the file is clamped to the file, since DecodeSegment refuses it before any copy. var maxSegment = 0L; foreach (var byteCount in segmentByteCounts) - maxSegment = Math.Max(maxSegment, Math.Min(byteCount, tiff.Length)); + maxSegment = Math.Max(maxSegment, Math.Min(byteCount, Math.Min(src.Length, Array.MaxLength))); inflateSource = ArrayPool.Shared.Rent((int)maxSegment); // writable + publiclyVisible so each segment is presented by moving Length/Position // rather than by constructing a new stream over a new array. @@ -385,8 +411,9 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< for (var plane = 0; plane < planes; plane++) { var index = geometry.SegmentIndex(plane, tileY, tileX); - var samples = DecodeSegment(tiff, segmentOffsets[index], segmentByteCounts[index], - index, format, staging, passFileBytesThrough, scratch, inflateSource, scratchStream, + var samples = DecodeSegment( + SegmentView(ref src, segmentOffsets[index], segmentByteCounts[index], index, ref coded), + format, staging, passFileBytesThrough, scratch, inflateSource, scratchStream, segmentCapacity); // Normalise the TILE, at the TILE's width. Horizontal differencing restarts at @@ -420,7 +447,8 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< var index = geometry.SegmentIndex(0, strip); // A chunky strip list may be short (truncated file): deliver the rows it covers. if (index >= segmentOffsets.Length) break; - var samples = DecodeSegment(tiff, segmentOffsets[index], segmentByteCounts[index], index, + var samples = DecodeSegment( + SegmentView(ref src, segmentOffsets[index], segmentByteCounts[index], index, ref coded), format, staging, passFileBytesThrough, scratch, inflateSource, scratchStream, rowCount * bytesPerRow); @@ -440,7 +468,8 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< for (var plane = 0; plane < planes; plane++) { var index = geometry.SegmentIndex(plane, strip); - var samples = DecodeSegment(tiff, segmentOffsets[index], segmentByteCounts[index], index, + var samples = DecodeSegment( + SegmentView(ref src, segmentOffsets[index], segmentByteCounts[index], index, ref coded), format, staging, passFileBytesThrough, scratch, inflateSource, scratchStream, rowCount * width * segBytesPerPixel); if (needsSwap) @@ -465,16 +494,29 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< ArrayPool.Shared.Return(scratch); if (band is not null) ArrayPool.Shared.Return(band); + if (coded is not null) + ArrayPool.Shared.Return(coded); staging?.Dispose(); } return (page, nextIfdOffset); } + /// The coded bytes of segment , refused when the file does not hold them. + private static ReadOnlySpan SegmentView(ref T src, long offset, long byteCount, int index, ref byte[]? buffer) + where T : ITiffBytes, allows ref struct + { + // Both are non-negative (the parser refuses offsets past long.MaxValue), so the test cannot wrap. A stream can be + // longer than an array holds, so the count is bounded by that too (a span never is, so it changes nothing there). + if (offset > src.Length || byteCount > src.Length - offset || byteCount > Array.MaxLength) + throw new InvalidDataException($"Segment {index} extents out of bounds"); + return src.View(offset, (int)byteCount, ref buffer); + } + /// /// One SEGMENT -- a strip or a tile, the two being the same thing to every stage but geometry -- - /// from the file into decoded samples, returned as a slice of or, on - /// the pass-through path, of the file itself. Shared by both layouts so that a tile can never + /// from its coded bytes into decoded samples, returned as a slice of or, on + /// the pass-through path, of itself. Shared by both layouts so that a tile can never /// come to decompress differently from a strip. /// /// @@ -482,15 +524,11 @@ private static (TiffPage Page, long NextIfdOffset) ReadPage(ReadOnlySpan< /// as packed rows first and then expanded into the scratch at one byte per /// sample, so from the caller's side it is an 8-bit page like any other. /// - private static ReadOnlySpan DecodeSegment(ReadOnlySpan tiff, long offset, long byteCount, - int index, SegmentFormat format, SegmentStaging? staging, bool passFileBytesThrough, byte[]? scratch, + private static ReadOnlySpan DecodeSegment(ReadOnlySpan segment, SegmentFormat format, + SegmentStaging? staging, bool passFileBytesThrough, byte[]? scratch, byte[]? inflateSource, MemoryStream? scratchStream, int capacity) { - // Both are non-negative (the parser refuses offsets past long.MaxValue), so the test cannot wrap. - if (offset > tiff.Length || byteCount > tiff.Length - offset) - throw new InvalidDataException($"Segment {index} extents out of bounds"); - var length = (int)byteCount; - var segment = tiff.Slice((int)offset, length); + var length = segment.Length; if (passFileBytesThrough) return segment[..Math.Min(segment.Length, capacity)]; diff --git a/src/Sdcb.SimdCodecs.Tiff/TiffRowReader.cs b/src/Sdcb.SimdCodecs.Tiff/TiffRowReader.cs new file mode 100644 index 0000000..41cc63c --- /dev/null +++ b/src/Sdcb.SimdCodecs.Tiff/TiffRowReader.cs @@ -0,0 +1,474 @@ +using System.Buffers; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; + +namespace Sdcb.SimdCodecs.Tiff; + +/// +/// : the first page of a TIFF from a seekable stream, a band (one strip, +/// or one row of tiles) at a time. +/// +/// A TIFF is read by offset, so the reader moves its itself: back by +/// (a seek, or nothing when the bytes are still buffered) and forward by consuming +/// what lies in between. Each step asks for one range; when the input does not hold it yet, the step returns +/// and the driver reads more, synchronously or asynchronously, +/// so neither path blocks the other. A range is never asked for past the stream's length (it is checked against +/// first), so the input never reaches its end and a stale end-of-stream flag cannot +/// meet a rewind. +/// +/// +/// The directory parser is the span decoder's (), run over the ranges read +/// so far: a read outside them stops it, the range is fetched (with a little read-ahead) and it runs again. That +/// repeats a few times for a real file (header, directory, each tag array kept out of line) and is capped for a hostile +/// one. The bands are decoded by over the band's segments, the code +/// runs, and converted by the same +/// call, so the rows are its rows. +/// +/// +internal sealed class TiffRowReader(StreamInput input, PixelFormat format, DecodeOptions? options) + : StreamingRowReader(input, format) +{ + /// Bytes read past what the directory parser asked for, so that neighbouring tag arrays come in one fetch. + private const int ReadAhead = 4096; + + /// Fetches one directory may take. A real one takes a handful (one per tag array kept out of line). + private const int MaxDirectoryFetches = 256; + + private readonly WindowBytes _windows = new(); + private int _fetches; + private long _skipped; // bytes read through, not used, to reach a range further on + private long _skipBudget; + private bool _whole; // read the file whole after all + private TiffPageLayout? _layout; + private TiffColor? _plan; + + // The IFD chain walk behind ImageInfo.FrameCount, resumable between fetches. + private HashSet? _visited; + private long _walkIfd; + private int _pages; + + // Rows: the band being handed out and the coded segments of the next one. + private byte[]? _band; + private int _bandStride; + private int _bandRows; + private int _bandCursor; + private int _down; + private readonly List<(long Offset, int Count)> _ranges = []; + private int _rangesFetched; + private readonly List _copies = []; + private BandBytes? _bandBytes; + + protected override OperationStatus DecodeHeader(ReadOnlySpan input, bool isFinal, out int consumed, + out ImageInfo info, out int width, out int height) + { + consumed = 0; + info = default; + width = height = 0; + var length = Input.Length; + if (length < 0 || _whole) + { + // Read whole and decoded as a span: a stream that cannot seek (the directory may be anywhere), or a file + // whose streaming would read far more than the file (see EnterWholeMode). + if (!isFinal) + return OperationStatus.NeedMoreData; + if (!TiffImageDecoder.TryReadInfo(input, out info)) + throw new InvalidDataException("The TIFF's first page could not be read."); + return Fallback(info, out width, out height); + } + + _windows.Length = length; + _skipBudget = (2 * length) + (1 << 20); + if (_layout is null) + { + while (true) + { + try + { + var windows = _windows; + _layout = TiffReader.ReadLayoutCore(ref windows, 0); + break; + } + catch (MissingBytesException missing) + { + if (!FetchWindow(missing.Offset, missing.Count)) + return NeedMoreHeader(); + } + catch (ArgumentOutOfRangeException e) when (e.ParamName == "pageIndex") + { + throw new InvalidDataException("The TIFF has no pages.", e); + } + catch (Exception e) when (e is NotSupportedException or ArgumentException) + { + throw TiffImageDecoder.Undecodable(e); + } + } + if (!TiffColor.TryCreate(_layout, out var plan)) + throw TiffImageDecoder.Unpresentable(_layout, 0); + _plan = plan; + _windows.Clear(); + _visited = []; + _walkIfd = _layout.IfdOffset; + } + + // TiffReader.CountPages one directory at a time, reading only each entry count and next pointer (the checks of + // TiffIfdParser.ReadNextIfdOffset): a directory it cannot read ends the chain uncounted. + var f = _layout.Format; + while (_walkIfd != 0 && !_visited!.Contains(_walkIfd)) + { + if (_walkIfd <= 0 || _walkIfd > length - f.CountSize) + break; + if (!Fetch(_walkIfd, f.CountSize)) + return NeedMoreHeader(); + var countBytes = Input.Buffered[..f.CountSize]; + var count = f.BigTiff ? TiffIfdParser.U64(countBytes, f.LittleEndian) : TiffIfdParser.U16(countBytes, f.LittleEndian); + // count <= MaxEntries, so the directory's extent cannot overflow a long. + if (count > TiffIfdParser.MaxEntries + || _walkIfd + f.CountSize + ((long)count * f.EntrySize) + f.OffsetSize > length) + break; + var nextAt = _walkIfd + f.CountSize + ((long)count * f.EntrySize); + if (!Fetch(nextAt, f.OffsetSize)) + return NeedMoreHeader(); + long next; + try + { + next = TiffIfdParser.Offset(Input.Buffered[..f.OffsetSize], f); + } + catch (InvalidDataException) + { + break; + } + _visited.Add(_walkIfd); + _pages++; + _walkIfd = next; + } + _walkIfd = 0; + + var layout = _layout; + info = TiffImageDecoder.InfoOf(layout, _plan!) with { FrameCount = Math.Max(1, _pages) }; + if (_plan!.OutFormat == SampleFormat.Float32 || !IsFullImage(options) || ForwardBytes(layout) > _skipBudget) + { + // Float output is defined through the decoded image, and options other than the whole image are the + // span decoder's; a page whose bands lie scattered (planes stored one after another) would have to be read + // through for every band. Decode the file whole, from its first byte. + Input.Rewind(0); + return Fallback(info, out width, out height); + } + + var bandRows = Math.Min(layout.Geometry.SegmentHeight, layout.Height); + var bandStride = (long)layout.Width * _plan.OutBytesPerPixel; + if (bandStride * bandRows > Array.MaxLength) + throw new InvalidDataException($"A {layout.Width}-pixel band of {bandRows} rows is larger than an array can hold."); + _bandStride = (int)bandStride; + _band = ArrayPool.Shared.Rent(_bandStride * bandRows); + _bandBytes = new BandBytes(length); + width = layout.Width; + height = layout.Height; + return OperationStatus.Done; + } + + /// + /// NeedMoreData from the header, unless reaching the bytes it wants has read through more than twice the file + /// (a directory, or an IFD chain, that jumps back and forth): then the file is read whole instead. + /// + private OperationStatus NeedMoreHeader() + { + if (_skipped > _skipBudget) + { + // The input never reached the stream's end (no range past Length is asked for), so the driver's + // end-of-stream flag is still false; it reads on from the first byte. + _whole = true; + _windows.Clear(); + Input.Rewind(0); + } + return OperationStatus.NeedMoreData; + } + + /// + /// The bytes the bands would read through without using them: the forward gaps between their ranges, in the order + /// the reader fetches them (a backward jump is a seek, and costs no reading). Without a forward seek on the input, + /// that is what streaming costs beyond the segments themselves. + /// + private long ForwardBytes(TiffPageLayout layout) + { + var ranges = new List<(long Offset, int Count)>(); + long position = 0, gaps = 0; + for (var down = 0; down < layout.Geometry.SegmentsDown; down++) + { + ranges.Clear(); + CollectRanges(layout, down, ranges); + foreach (var (offset, count) in ranges) + { + if (offset > position) + gaps += offset - position; + position = offset + count; + } + if (gaps > _skipBudget) + break; + } + return gaps; + } + + protected override OperationStatus DecodeRows(ReadOnlySpan input, bool isFinal, out int consumed, + Span destination, int stride, int rowCount, out int rowsWritten) + { + consumed = 0; + rowsWritten = 0; + var layout = _layout!; + var plan = _plan!; + while (rowsWritten < rowCount) + { + if (_bandCursor == _bandRows) + { + if (!ReadBand(layout, plan)) + return OperationStatus.NeedMoreData; + } + var n = Math.Min(rowCount - rowsWritten, _bandRows - _bandCursor); + for (var r = 0; r < n; r++) + { + PixelConverter.ConvertRow(_band.AsSpan((_bandCursor + r) * _bandStride, _bandStride), plan.OutChannels, + plan.OutFormat, destination[((rowsWritten + r) * stride)..], Format, layout.Width); + } + _bandCursor += n; + rowsWritten += n; + } + return OperationStatus.Done; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (_band is not null) ArrayPool.Shared.Return(_band); + _band = null; + for (var i = 0; i < _copies.Count; i++) + { + if (_copies[i] is { } copy) ArrayPool.Shared.Return(copy); + _copies[i] = null; + } + } + base.Dispose(disposing); + } + + private OperationStatus Fallback(ImageInfo info, out int width, out int height) + { + UseBufferedFallback(TiffImageDecoder.TryDecodeInto, options); + (width, height) = (options ?? DecodeOptions.Default).GetOutputSize(info); + return OperationStatus.Done; + } + + /// + /// Fetches the coded segments of segment row and decodes it into the band. False when the input + /// does not hold the next range yet (the ranges fetched so far are kept). + /// + private bool ReadBand(TiffPageLayout layout, TiffColor plan) + { + var bandBytes = _bandBytes!; + if (_ranges.Count == 0 && _rangesFetched == 0) + CollectRanges(layout, _down, _ranges); + while (_rangesFetched < _ranges.Count) + { + var (offset, count) = _ranges[_rangesFetched]; + if (!Fetch(offset, count)) + return false; + if (_ranges.Count == 1) + { + // The band's only segment: read in place, before the input moves again. + bandBytes.Add(offset, Input.BufferedMemory[..count]); + } + else + { + while (_copies.Count <= _rangesFetched) _copies.Add(null); + var copy = _copies[_rangesFetched]; + var span = TiffBuffers.Ensure(ref copy, count); + _copies[_rangesFetched] = copy; + Input.Buffered[..count].CopyTo(span); + bandBytes.Add(offset, copy.AsMemory(0, count)); + } + _rangesFetched++; + } + + var rect = new PixelRect(0, 0, layout.Width, layout.Height); + var (_, rows) = TiffImageDecoder.BandRows(layout, rect, _down); + try + { + TiffImageDecoder.DecodeBand(ref bandBytes, layout, plan, rect, _down, + _band.AsSpan(0, rows * _bandStride), _bandStride); + } + catch (NotSupportedException e) + { + throw TiffImageDecoder.Undecodable(e); + } + finally + { + // Whether it decoded or not, the band's ranges are spent: a read after a failure fetches them again + // (an in-place range is valid only until the input moves). + _ranges.Clear(); + _rangesFetched = 0; + bandBytes.Clear(); + } + _bandRows = rows; + _bandCursor = 0; + _down++; + return true; + } + + /// + /// The coded byte ranges reads for segment row , + /// in file order, into . A segment it refuses before reading (not listed, out of the file) + /// is left out: it throws for it, as over a span. + /// + private void CollectRanges(TiffPageLayout layout, int down, List<(long Offset, int Count)> ranges) + { + var g = layout.Geometry; + var length = Input.Length; + for (var across = 0; across < g.SegmentsAcross; across++) + { + var index = (down * g.SegmentsAcross) + across; + if (!layout.IsTiled && !layout.IsPlanar && index >= layout.Offsets.Length) + continue; // a short strip list: DecodeBand zero-fills, reading nothing + for (var plane = 0; plane < g.PlaneCount; plane++) + { + var segment = g.SegmentIndex(plane, down, across); + if (segment >= layout.Offsets.Length || segment >= layout.ByteCounts.Length) + break; + var offset = layout.Offsets[segment]; + var count = layout.ByteCounts[segment]; + if (count > Array.MaxLength || offset > length || count > length - offset) + break; + if (count > 0) + ranges.Add((offset, (int)count)); + } + } + ranges.Sort(static (a, b) => a.Offset.CompareTo(b.Offset)); + } + + /// Fetches at least bytes from into the directory windows. + private bool FetchWindow(long offset, int count) + { + // WindowBytes refused the range before it reported it missing unless it lies inside the file. + var want = (int)Math.Min(_windows.Length - offset, Math.Max(count, ReadAhead)); + if (!Fetch(offset, want)) + return false; + // Each fetch reruns the parser over the directory, so a directory spread over many places is refused. + if (++_fetches > MaxDirectoryFetches) + throw new InvalidDataException($"A TIFF directory is spread over more than {MaxDirectoryFetches} places."); + // The windows hold what one directory reads; overlapping read-ahead aside, never more than the file. + if (_windows.Total + want > _windows.Length + (MaxDirectoryFetches * (long)ReadAhead)) + throw new InvalidDataException("A TIFF directory reads more than the file holds."); + _windows.Add(offset, Input.Buffered[..want].ToArray()); + return true; + } + + /// + /// Moves the input to and reports whether bytes from there are + /// buffered; false means the driver must read more first. The range lies inside the stream. + /// + private bool Fetch(long offset, int count) + { + var position = Input.Position; + if (offset < position) + { + Input.Rewind(offset); + } + else if (offset > position) + { + var skip = (int)Math.Min(offset - position, Input.Buffered.Length); + Input.Consume(skip); + _skipped += skip; + if (Input.Position < offset) + return false; + } + return Input.Buffered.Length >= count; + } + + /// A read outside the bytes fetched so far: what the directory parser needs next. + private sealed class MissingBytesException(long offset, int count) : Exception + { + public long Offset { get; } = offset; + public int Count { get; } = count; + } + + /// The directory ranges fetched so far, as TIFF bytes; a read outside them throws . + private sealed class WindowBytes : ITiffBytes + { + private readonly List<(long Offset, byte[] Bytes)> _windows = []; + + public long Length { get; set; } + + /// Bytes held. + public long Total { get; private set; } + + public void Add(long offset, byte[] bytes) + { + _windows.Add((offset, bytes)); + Total += bytes.Length; + } + + public void Clear() + { + _windows.Clear(); + Total = 0; + } + + public void Read(long offset, scoped Span destination) + { + // The checks of SpanBytes, so the parser fails exactly where it fails over the whole file. + if (offset < 0 || offset + destination.Length > Length) + throw new InvalidDataException("TIFF data extends past the end of the file"); + if (destination.Length == 0) + return; + foreach (var (start, bytes) in _windows) + { + if (offset >= start && offset + destination.Length <= start + bytes.Length) + { + bytes.AsSpan((int)(offset - start), destination.Length).CopyTo(destination); + return; + } + } + throw new MissingBytesException(offset, destination.Length); + } + + public ReadOnlySpan View(long offset, int length, ref byte[]? buffer) + { + var span = TiffBuffers.Ensure(ref buffer, length); + Read(offset, span); + return span; + } + } + + /// The coded segments of one band, as TIFF bytes. + private sealed class BandBytes(long length) : ITiffBytes + { + private readonly List<(long Offset, ReadOnlyMemory Bytes)> _ranges = []; + + public long Length { get; } = length; + + public void Add(long offset, ReadOnlyMemory bytes) => _ranges.Add((offset, bytes)); + + public void Clear() => _ranges.Clear(); + + public void Read(long offset, scoped Span destination) + { + if (offset < 0 || offset + destination.Length > Length) + throw new InvalidDataException("TIFF data extends past the end of the file"); + if (destination.Length == 0) + return; + foreach (var (start, bytes) in _ranges) + { + if (offset >= start && offset + destination.Length <= start + bytes.Length) + { + bytes.Span.Slice((int)(offset - start), destination.Length).CopyTo(destination); + return; + } + } + throw new InvalidOperationException($"Segment bytes at {offset} were not fetched for this band."); + } + + public ReadOnlySpan View(long offset, int length, ref byte[]? buffer) + { + var span = TiffBuffers.Ensure(ref buffer, length); + Read(offset, span); + return span; + } + } +} diff --git a/tests/Sdcb.SimdCodecs.Tests/TiffRobustnessTests.cs b/tests/Sdcb.SimdCodecs.Tests/TiffRobustnessTests.cs index 855f4a1..5ac1e07 100644 --- a/tests/Sdcb.SimdCodecs.Tests/TiffRobustnessTests.cs +++ b/tests/Sdcb.SimdCodecs.Tests/TiffRobustnessTests.cs @@ -205,7 +205,7 @@ public async Task Mutations_decode_or_throw_invalid_data() /// The directories hold the meaning, and libtiff writes them after the image data, so a third of the mutations /// land in the header, a third in the last 512 bytes (directories and tag arrays) and a third anywhere. /// - private static byte[] Mutate(byte[] seed, Random random, out string description) + internal static byte[] Mutate(byte[] seed, Random random, out string description) { var data = seed.ToArray(); var at = random.Next(3) switch diff --git a/tests/Sdcb.SimdCodecs.Tests/TiffStreamingDecodeTests.cs b/tests/Sdcb.SimdCodecs.Tests/TiffStreamingDecodeTests.cs new file mode 100644 index 0000000..29b8f8a --- /dev/null +++ b/tests/Sdcb.SimdCodecs.Tests/TiffStreamingDecodeTests.cs @@ -0,0 +1,557 @@ +using System.Diagnostics; +using ImageMagick; +using Sdcb.SimdCodecs.Abstractions; +using Sdcb.SimdCodecs.Abstractions.CodecSupport; +using Sdcb.SimdCodecs.Tests.Streaming; +using Sdcb.SimdCodecs.Tiff; +using Shouldly; +using B = Sdcb.SimdCodecs.Tests.TestTiffBuilder; +using Feed = Sdcb.SimdCodecs.Tests.Streaming.StreamingAssert.Feed; + +namespace Sdcb.SimdCodecs.Tests; + +/// +/// : rows equal byte for byte +/// for every layout the reader handles; a seekable stream streams (bounded memory), anything else falls back; malformed +/// input throws only. Also , which reads a +/// seekable stream by offset and must return what returns. +/// The fuzz loop's length scales with TIFF_STREAM_FUZZ_ITERATIONS (default 200). +/// +public sealed class TiffStreamingDecodeTests +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static readonly PixelFormat[] Formats = + [ + PixelFormat.Rgba32, PixelFormat.Bgr24, PixelFormat.Gray8, PixelFormat.GrayAlpha16, PixelFormat.Rgba64, + PixelFormat.Gray16, PixelFormat.Rgba32Premultiplied, + ]; + + /// True when writes in (a float page has no integer projection, so it never does). + private static bool Decodes(byte[] data, PixelFormat format) => + TiffImageDecoder.TryReadInfo(data, out var info) + && TiffImageDecoder.TryDecodeInto(data, new byte[info.Width * info.Height * format.BytesPerPixel], 0, format, null, Ct); + + private static readonly Feed[] NonSeekable = [Feed.OneByte, Feed.RandomChunks, Feed.AsyncOnly]; + + private static int Iterations => int.TryParse(Environment.GetEnvironmentVariable("TIFF_STREAM_FUZZ_ITERATIONS"), out var n) ? n : 200; + + /// The robustness corpus (libtiff-written and hand-assembled) plus layouts it lacks. + private static List<(string Name, byte[] Data)> Corpus() + { + var corpus = new List<(string, byte[])>(TiffRobustnessTests.Seeds()); + var random = new Random(11); + const int w = 41, h = 29; + + // Planar tiles, big-endian, 16-bit, hand-assembled: one tile row needs every plane's tiles. + var tiles = new List(); + for (var p = 0; p < 3; p++) + { + for (var ty = 0; ty < 2; ty++) + for (var tx = 0; tx < 3; tx++) + { + var tile = new byte[16 * 16 * 2]; + random.NextBytes(tile); + tiles.Add(tile); + } + } + var tags = B.Basic(w, h, 3, 16, TiffCompression.Uncompressed, TiffPhotometric.Rgb); + tags.Add(B.Short(TiffTag.PlanarConfig, 2)); + tags.Add(B.Long(TiffTag.TileWidth, 16)); + tags.Add(B.Long(TiffTag.TileLength, 16)); + corpus.Add(("hand MM planar tiled 16-bit", new B(littleEndian: false).AddPage(tags, [.. tiles], tiled: true).Build())); + + // Strips listed out of file order, and two strips sharing their bytes. + var gray = new byte[w * h]; + random.NextBytes(gray); + var strips = TiffRobustnessTests.Strips(gray, w, h, 4); + var file = new B().AddPage(B.Basic(w, h, 1, 8, TiffCompression.Uncompressed, TiffPhotometric.MinIsBlack, rowsPerStrip: 4), strips).Build(); + corpus.Add(("strips reversed", PermuteStrips(file, strips.Length, reverse: true))); + corpus.Add(("strips shared", PermuteStrips(file, strips.Length, reverse: false))); + + // A short strip list: the rows past it decode as zeros. + var tagsShort = B.Basic(w, h, 1, 8, TiffCompression.Uncompressed, TiffPhotometric.MinIsBlack, rowsPerStrip: 4); + corpus.Add(("short strip list", new B().AddPage(tagsShort, strips[..3]).Build())); + + // BigTIFF and a single-strip page. + corpus.Add(("BigTIFF single strip", new B(bigTiff: true).AddPage( + B.Basic(w, h, 1, 8, TiffCompression.Uncompressed, TiffPhotometric.MinIsWhite, rowsPerStrip: h), [gray]).Build())); + return corpus; + } + + /// Rewrites the StripOffsets array of a file built: reversed, or every strip pointing at the first's bytes (with its byte count). + private static byte[] PermuteStrips(byte[] file, int count, bool reverse) + { + var layout = TiffReader.ReadLayout(file); + var offsets = layout.Offsets.ToArray(); + var counts = layout.ByteCounts.ToArray(); + var data = file.ToArray(); + // Find the StripOffsets array (LONGs, out of line) by its contents. + var needle = offsets.SelectMany(o => BitConverter.GetBytes((uint)o)).ToArray(); + var at = data.AsSpan().IndexOf(needle); + at.ShouldBeGreaterThan(0); + var countNeedle = counts.SelectMany(c => BitConverter.GetBytes((uint)c)).ToArray(); + var countAt = data.AsSpan().IndexOf(countNeedle); + countAt.ShouldBeGreaterThan(0); + for (var i = 0; i < count; i++) + { + var source = reverse ? count - 1 - i : 0; + BitConverter.GetBytes((uint)offsets[source]).CopyTo(data, at + (i * 4)); + BitConverter.GetBytes((uint)counts[source]).CopyTo(data, countAt + (i * 4)); + } + return data; + } + + private static bool IsFloat(byte[] file) => + TiffImageDecoder.TryReadInfo(file, out var info) && info.SampleFormat == SampleFormat.Float32; + + [Fact] + public void Rows_equal_TryDecodeInto_streaming_on_seekable_streams_only() + { + foreach (var (name, data) in Corpus()) + { + var streams = !IsFloat(data); + var tested = 0; + foreach (var format in Formats) + { + if (!Decodes(data, format)) + continue; + tested++; + try + { + StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, data, format, + expectStreaming: streams, feeds: [Feed.Whole]); + StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, data, format, + expectStreaming: false, feeds: NonSeekable); + if (streams) + { + foreach (var async in new[] { false, true }) + SeekableRowsEqual(data, format, async, seed: format.GetHashCode()); + } + } + catch (Exception e) + { + throw new ShouldAssertException($"{name} as {format}: {e.Message}", e); + } + } + if (streams) + tested.ShouldBeGreaterThan(0, name); + } + } + + /// + /// A seekable stream that returns 1..997 bytes per read, read in random bands of 1..17 rows through a 16-byte first + /// buffer (synchronously or asynchronously): every fetch, rewind and partial band of the streaming path. + /// + private static void SeekableRowsEqual(byte[] data, PixelFormat format, bool async, int seed) + { + TiffImageDecoder.TryReadInfo(data, out var info).ShouldBeTrue(); + var rowBytes = info.Width * format.BytesPerPixel; + var expected = new byte[rowBytes * info.Height]; + TiffImageDecoder.TryDecodeInto(data, expected, 0, format, null, Ct).ShouldBeTrue(); + var stream = new SeekableChunkedStream(data, maxChunk: 997, seed); + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(stream, initialCapacity: 16), format, null); + var random = new Random(seed); + var actual = new byte[expected.Length]; + while (reader.RowsRead < info.Height) + { + var at = reader.RowsRead * rowBytes; + var band = random.Next(1, 18); + var n = async + ? reader.ReadRowsAsync(actual.AsMemory(at), band, 0, Ct).AsTask().GetAwaiter().GetResult() + : reader.ReadRows(actual.AsSpan(at), band, 0, Ct); + n.ShouldBeGreaterThan(0); + } + reader.IsStreaming.ShouldBeTrue("seekable: IsStreaming"); + if (!actual.AsSpan().SequenceEqual(expected)) + { + var first = actual.AsSpan().CommonPrefixLength(expected); + throw new ShouldAssertException($"seekable chunked (async {async}): rows differ at byte {first} (row {first / rowBytes})."); + } + } + + /// A seekable whose reads return a seeded-random 1..maxChunk bytes, synchronously or after a yield. + private sealed class SeekableChunkedStream(byte[] data, int maxChunk, int seed) : MemoryStream(data, writable: false) + { + private readonly Random _random = new(seed); + + public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, _random.Next(1, maxChunk + 1))); + + public override int Read(Span buffer) => base.Read(buffer[..Math.Min(buffer.Length, _random.Next(1, maxChunk + 1))]); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Yield(); + return Read(buffer.Span); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } + + /// + /// libtiff's separate planes put each plane's strips after the previous plane's, so every band of rows needs bytes + /// from three far-apart places; without a forward seek that means reading through the file per band, and the + /// reader decodes such a file whole instead. A small planar page (the corpus) still streams. + /// + [Fact] + public void Planes_stored_far_apart_fall_back_when_large() + { + const int w = 1500, h = 1200; + var rgb = new byte[w * h * 3]; + new Random(9).NextBytes(rgb); + using var image = new MagickImage(); + image.ReadPixels(rgb, new PixelReadSettings(w, h, StorageType.Char, "RGB")); + image.Settings.Interlace = Interlace.Plane; + image.Settings.Compression = CompressionMethod.NoCompression; + image.Settings.SetDefine(MagickFormat.Tiff, "rows-per-strip", "8"); + var file = image.ToByteArray(MagickFormat.Tiff); + TiffReader.ReadLayout(file).IsPlanar.ShouldBeTrue(); + StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, file, PixelFormat.Rgb24, + expectStreaming: false, feeds: [Feed.Whole]); + } + + /// + /// An IFD chain that jumps between the start and the end of the file: every forward jump reads through the gap, so + /// once that passes twice the file the reader stops and decodes the file whole (no unbounded reading). + /// + [Fact] + public void A_chain_jumping_back_and_forth_is_read_whole() + { + const int pages = 20, spacing = 128, gap = 300_000; + long IfdAt(int k) => k % 2 == 0 ? 64 + (k / 2 * spacing) : 64 + (pages * spacing) + gap + (k / 2 * spacing); + var file = new byte[IfdAt(pages - 1) + spacing]; + file[0] = file[1] = (byte)'I'; + BitConverter.GetBytes((ushort)42).CopyTo(file, 2); + BitConverter.GetBytes((uint)IfdAt(0)).CopyTo(file, 4); + file[8] = 200; // the one pixel every page points at + for (var k = 0; k < pages; k++) + { + var at = (int)IfdAt(k); + (ushort Tag, ushort Type, uint Value)[] entries = + [ + (TiffTag.ImageWidth, 4, 1), (TiffTag.ImageLength, 4, 1), (TiffTag.BitsPerSample, 3, 8), + (TiffTag.Compression, 3, 1), (TiffTag.PhotometricInterp, 3, 1), (TiffTag.StripOffsets, 4, 8), + (TiffTag.RowsPerStrip, 4, 1), (TiffTag.StripByteCounts, 4, 1), + ]; + BitConverter.GetBytes((ushort)entries.Length).CopyTo(file, at); + for (var i = 0; i < entries.Length; i++) + { + var e = at + 2 + (i * 12); + BitConverter.GetBytes(entries[i].Tag).CopyTo(file, e); + BitConverter.GetBytes(entries[i].Type).CopyTo(file, e + 2); + BitConverter.GetBytes(1u).CopyTo(file, e + 4); + if (entries[i].Type == 3) BitConverter.GetBytes((ushort)entries[i].Value).CopyTo(file, e + 8); + else BitConverter.GetBytes(entries[i].Value).CopyTo(file, e + 8); + } + BitConverter.GetBytes(k + 1 < pages ? (uint)IfdAt(k + 1) : 0u).CopyTo(file, at + 2 + (entries.Length * 12)); + } + TiffReader.CountPages(file).ShouldBe(pages); + StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, file, PixelFormat.Gray8, + expectStreaming: false, feeds: [Feed.Whole]); + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(file), initialCapacity: 4096), + PixelFormat.Gray8, null); + reader.Initialize(Ct); + reader.Info.FrameCount.ShouldBe(pages); + reader.IsStreaming.ShouldBeFalse(); + } + + [Fact] + public void Options_other_than_the_whole_image_fall_back() + { + var (_, data) = TiffRobustnessTests.Seeds()[0]; + foreach (var options in new[] + { + new DecodeOptions { Region = new PixelRect(3, 2, 20, 11) }, + new DecodeOptions { ScaleDenominator = 2 }, + new DecodeOptions { ApplyOrientation = true }, + }) + { + StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, data, PixelFormat.Rgba32, options, + expectStreaming: false, feeds: [Feed.Whole, Feed.RandomChunks]); + } + } + + [Fact] + public void Info_equals_TryReadInfo() + { + foreach (var (name, data) in Corpus()) + { + TiffImageDecoder.TryReadInfo(data, out var expected).ShouldBeTrue(name); + if (IsFloat(data)) + continue; // no integer format to read it in + foreach (var seekable in new[] { true, false }) + { + Stream stream = seekable ? new MemoryStream(data, writable: false) : new ChunkedStream(data, maxChunk: 777, seed: 3); + var format = Formats.First(f => Decodes(data, f)); + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(stream), format, null); + reader.Initialize(Ct); + reader.Info.ShouldBe(expected, $"{name} seekable {seekable}"); + } + } + } + + [Fact] + public void Multi_page_reads_page_zero() + { + var (_, data) = TiffRobustnessTests.Seeds().Single(s => s.Name == "multi-page"); + var rows = StreamingAssert.RowsEqualDecodeInto(TiffImageDecoder.Registration, data, PixelFormat.Rgb24, + expectStreaming: true, feeds: [Feed.Whole]); + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(new MemoryStream(data)), PixelFormat.Rgb24, null); + reader.Initialize(Ct); + reader.Info.FrameCount.ShouldBe(3); + rows.Length.ShouldBe(reader.Width * reader.Height * 3); + } + + [Fact] + public void A_stream_not_at_its_start_is_read_from_its_position() + { + var (_, data) = TiffRobustnessTests.Seeds().First(s => s.Name.StartsWith("LZW tiled True")); + var prefixed = new byte[100 + data.Length]; + data.CopyTo(prefixed, 100); + var expected = new byte[37 * 23 * 4]; + TiffImageDecoder.TryDecodeInto(data, expected, 0, PixelFormat.Rgba32, null, Ct).ShouldBeTrue(); + var stream = new MemoryStream(prefixed, writable: false) { Position = 100 }; + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(stream), PixelFormat.Rgba32, null); + var actual = new byte[expected.Length]; + reader.ReadRows(actual, 23, 0, Ct).ShouldBe(23); + reader.IsStreaming.ShouldBeTrue(); + actual.ShouldBe(expected); + + var document = TiffReader.Read(new MemoryStream(prefixed, writable: false) { Position = 100 }); + document.Pages[0].Pixels.ShouldBe(TiffReader.Read(data).Pages[0].Pixels); + } + + [Fact] + public void Segments_past_the_end_throw_invalid_data() + { + var gray = new byte[37 * 23]; + new Random(5).NextBytes(gray); + var strips = TiffRobustnessTests.Strips(gray, 37, 23, 4); + var file = new B().AddPage(B.Basic(37, 23, 1, 8, TiffCompression.Uncompressed, TiffPhotometric.MinIsBlack, rowsPerStrip: 4), strips).Build(); + var layout = TiffReader.ReadLayout(file); + var needle = layout.Offsets.SelectMany(o => BitConverter.GetBytes((uint)o)).ToArray(); + var at = file.AsSpan().IndexOf(needle); + foreach (var bad in new uint[] { (uint)file.Length, (uint)file.Length - 3, uint.MaxValue }) + { + var broken = file.ToArray(); + BitConverter.GetBytes(bad).CopyTo(broken, at + (3 * 4)); + TiffImageDecoder.TryDecodeInto(broken, new byte[37 * 23], 0, PixelFormat.Gray8, null, Ct).ShouldBeFalse(); + foreach (var feed in new[] { Feed.Whole, Feed.RandomChunks }) + { + var e = Should.Throw(() => StreamingAssert.ReadAll(broken, feed, + input => TiffImageDecoder.CreateRowReader(input, PixelFormat.Gray8, null), out _, out _, out _)); + e.ShouldNotBeNull(); + } + } + + // The first IFD past the end, and a file cut inside its directory. + var noIfd = file.ToArray(); + BitConverter.GetBytes((uint)file.Length + 10).CopyTo(noIfd, 4); + foreach (var broken in new[] { noIfd, file[..^7], file[..5], Array.Empty() }) + { + foreach (var feed in new[] { Feed.Whole, Feed.RandomChunks }) + { + Should.Throw(() => StreamingAssert.ReadAll(broken, feed, + input => TiffImageDecoder.CreateRowReader(input, PixelFormat.Gray8, null), out _, out _, out _)); + } + } + } + + [Fact] + public void Read_stream_equals_read_span() + { + foreach (var (name, data) in Corpus()) + { + var expected = TiffReader.Read(data); + var actual = TiffReader.Read(new MemoryStream(data, writable: false)); + AssertSameDocument(expected, actual, name); + var slurped = TiffReader.Read(new ChunkedStream(data, maxChunk: 4096, seed: 1)); + AssertSameDocument(expected, slurped, name); + } + } + + private static void AssertSameDocument(TiffDocument expected, TiffDocument actual, string name) + { + actual.Pages.Count.ShouldBe(expected.Pages.Count, name); + for (var p = 0; p < expected.Pages.Count; p++) + { + var (e, a) = (expected.Pages[p], actual.Pages[p]); + a.Pixels.ShouldBe(e.Pixels, $"{name} page {p}"); + (a with { Pixels = [], IccProfile = null }).ShouldBe(e with { Pixels = [], IccProfile = null }, $"{name} page {p}"); + a.IccProfile.ShouldBe(e.IccProfile, $"{name} page {p}"); + } + } + + [Fact] + public async Task Mutations_stream_like_the_span_decoder() + { + var seeds = Corpus(); + var iterations = Iterations; + var budget = TimeSpan.FromSeconds(Math.Max(60, iterations / 20)); + var current = ""; + var run = Task.Run(() => + { + var random = new Random(20261123); + for (var i = 0; i < iterations; i++) + { + var (name, seed) = seeds[random.Next(seeds.Count)]; + var data = TiffRobustnessTests.Mutate(seed, random, out var description); + current = $"#{i} {name}: {description}"; + StreamOne(data, current, random.Next(4) == 0 ? Feed.RandomChunks : Feed.Whole); + } + }, Ct); + if (await Task.WhenAny(run, Task.Delay(budget, Ct)) != run) + throw new ShouldAssertException($"The fuzz loop is stuck at {current}"); + await run; + } + + /// + /// The streaming reader on succeeds exactly when + /// does, with its rows; otherwise it throws . + /// over a seekable stream matches the span read the same way. + /// + private static void StreamOne(byte[] data, string context, Feed feed) + { + var timer = Stopwatch.StartNew(); + try + { + byte[]? expected = null; + var size = 0L; + if (TiffImageDecoder.TryReadInfo(data, out var info)) + { + size = (long)info.Width * info.Height * 4; + if (size > 1 << 24) return; // the harness's memory, not the reader's + expected = new byte[size]; + if (!TiffImageDecoder.TryDecodeInto(data, expected, 0, PixelFormat.Rgba32, null, Ct)) + expected = null; + } + else + { + // TryReadInfo refuses a page the span decoder would also refuse; it may still be large. + try + { + var layout = TiffReader.ReadLayout(data); + if ((long)layout.Width * layout.Height * 4 > 1 << 24) return; + } + catch (Exception e) when (e is InvalidDataException or NotSupportedException or ArgumentException) + { + } + } + + byte[]? actual; + try + { + actual = StreamingAssert.ReadAll(data, feed, + input => TiffImageDecoder.CreateRowReader(input, PixelFormat.Rgba32, null), out _, out _, out _); + } + catch (InvalidDataException) + { + actual = null; + } + if (expected is null) + actual.ShouldBeNull("streaming decoded what TryDecodeInto refused"); + else + (actual is not null && actual.AsSpan().SequenceEqual(expected)).ShouldBeTrue("rows differ from TryDecodeInto"); + + if (TiffReaderPagesFit(data)) + { + Exception? spanError = null, streamError = null; + TiffDocument? fromSpan = null, fromStream = null; + try { fromSpan = TiffReader.Read(data); } catch (Exception e) when (e is InvalidDataException or NotSupportedException) { spanError = e; } + try { fromStream = TiffReader.Read(new MemoryStream(data, writable: false)); } catch (Exception e) when (e is InvalidDataException or NotSupportedException) { streamError = e; } + (streamError?.GetType()).ShouldBe(spanError?.GetType(), "Read(Stream) and Read(span) disagree"); + if (fromSpan is not null) + AssertSameDocument(fromSpan, fromStream!, "Read(Stream)"); + } + } + catch (Exception e) + { + throw new ShouldAssertException($"{context} ({feed}): {e.GetType().Name}: {e.Message}", e); + } + timer.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5), context); + } + + // Every page small enough for the harness to hold as a raster. + private static bool TiffReaderPagesFit(byte[] data) + { + int pages; + try { pages = TiffReader.CountPages(data); } + catch (InvalidDataException) { return false; } + for (var p = 0; p < pages; p++) + { + try + { + var layout = TiffReader.ReadLayout(data, p); + if ((long)layout.Width * layout.Height * layout.BytesPerPixel > 1 << 24) return false; + } + catch (Exception e) when (e is InvalidDataException or NotSupportedException or ArgumentException) + { + } + } + return true; + } + + /// + /// End to end: a large libtiff-written (Magick.NET) multi-strip TIFF in a file, its directory after the pixels, + /// read from a asynchronously equals , and read + /// synchronously allocates far less than the file or the page. + /// + [Theory] + [InlineData("zip")] + [InlineData("none")] + public async Task Large_file_streams_with_bounded_memory(string compression) + { + const int w = 8192, h = 4096; + var dir = Directory.CreateTempSubdirectory("sdcb-tiffstream-"); + try + { + var path = Path.Combine(dir.FullName, "large.tif"); + var gray = new byte[w * h]; + var random = new Random(7); + for (var y = 0; y < h; y++) + for (var x = 0; x < w; x++) + gray[(y * w) + x] = (byte)((x / 3) + (y / 5) + random.Next(16)); + using (var image = new MagickImage(gray, new MagickReadSettings { Format = MagickFormat.Gray, Width = w, Height = h, Depth = 8 })) + { + image.Settings.Compression = compression == "zip" ? CompressionMethod.Zip : CompressionMethod.NoCompression; + image.Settings.SetDefine(MagickFormat.Tiff, "rows-per-strip", "16"); + image.Write(path, MagickFormat.Tiff); + } + var file = await File.ReadAllBytesAsync(path, Ct); + TiffReader.ReadLayout(file).IfdOffset.ShouldBeGreaterThan(file.Length / 2, "libtiff writes the directory after the pixels"); + var expected = new byte[w * h]; + TiffImageDecoder.TryDecodeInto(file, expected, 0, PixelFormat.Gray8, null, Ct).ShouldBeTrue(); + + var band = new byte[w * 100]; + await using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true)) + await using (var reader = TiffImageDecoder.CreateRowReader(new StreamInput(stream), PixelFormat.Gray8, null)) + { + await reader.InitializeAsync(Ct); + reader.IsStreaming.ShouldBeTrue(); + while (reader.RowsRead < h) + { + var at = reader.RowsRead; + var n = await reader.ReadRowsAsync(band, 100, 0, Ct); + n.ShouldBeGreaterThan(0); + if (!band.AsSpan(0, n * w).SequenceEqual(expected.AsSpan(at * w, n * w))) + throw new ShouldAssertException($"rows {at}..{at + n} differ from TryDecodeInto"); + } + } + + const long bound = 4 << 20; + ((long)file.Length).ShouldBeGreaterThan(2 * bound); + StreamingAssert.AllocatesLessThan(bound, () => + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096); + using var reader = TiffImageDecoder.CreateRowReader(new StreamInput(stream), PixelFormat.Gray8, null); + while (reader.RowsRead < h) + reader.ReadRows(band, 100, 0, Ct); + }, "streaming a large TIFF"); + } + finally + { + dir.Delete(recursive: true); + } + } +}