diff --git a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs index 09e8f367..93cc5178 100644 --- a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs +++ b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs @@ -76,6 +76,8 @@ public static class TiffImageReader private const int CompressionAdobeDeflate = 32946, CompressionPackBits = 32773, CompressionLossyJpeg = 34892; private const int PhotometricMinIsWhite = 0, PhotometricRgb = 2, PhotometricPalette = 3, PhotometricYCbCr = 6; private const int PhotometricCfa = 32803, PhotometricLinearRaw = 34892; + private const int MaxChunks = 1 << 24; + private const long MaxChunkBytes = int.MaxValue / 2; /// Decodes the first full-resolution image of a TIFF (or a DNG whose main image is not CFA). public static ImageBuffer Decode(Stream stream, TiffDecodeOptions? options = null) @@ -138,6 +140,7 @@ public static class TiffImageReader var g = Geometry.Read(reader, ifd, o); var warnings = new List(); var count = g.ChunksPerPlane * g.Planes; + if (count > MaxChunks) throw new InvalidDataException($"TIFF: {count} strips/tiles"); var offsets = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets) ?? throw new InvalidDataException("TIFF: missing strip/tile offsets"); var counts = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts); if (counts is null && count == 1 && g.Compression == CompressionNone) counts = [(uint)Math.Min(int.MaxValue, g.RowBytes * (long)g.ChunkHeight)]; @@ -149,7 +152,7 @@ public static class TiffImageReader for (var i = 0; i < Math.Min(count, Math.Min(offsets.Length, counts.Length)); i++) { if (counts[i] == 0) continue; - chunks[i] = reader.ReadRelative(offsets[i], (int)Math.Min(counts[i], int.MaxValue)); + chunks[i] = ReadChunk(reader, offsets[i], counts[i]); if (chunks[i] is null) warnings.Add($"TIFF: strip/tile {i} lies outside the file"); } var tables = g.Compression is CompressionJpeg or CompressionLossyJpeg && ifd.Entries.TryGetValue(TiffTags.JpegTables, out var t) ? reader.ReadBytes(t) : null; @@ -253,7 +256,7 @@ public static class TiffImageReader g.ChunksPerPlane = (g.Height + g.ChunkHeight - 1) / g.ChunkHeight; } g.RowBytes = ((long)g.ChunkWidth * g.ChunkSpp * g.Bps + 7) / 8; - if (g.RowBytes * g.ChunkHeight > TiffReader.MaxValueBytes * 4) throw new InvalidDataException("TIFF: strip/tile too large"); + if (g.RowBytes * g.ChunkHeight > MaxChunkBytes) throw new InvalidDataException("TIFF: strip/tile too large"); return g; } } @@ -272,7 +275,7 @@ public static class TiffImageReader if (g.IsJpeg) return DecodeJpegChunk(g, data, tables, ints!, x0, y0, validW, validH, plane); var expected = (int)(g.RowBytes * rows); - var raw = new byte[expected]; + var raw = g.Compression == CompressionNone && data.Length >= expected ? data : new byte[expected]; var produced = g.Compression switch { CompressionNone => Copy(data, raw), @@ -309,10 +312,27 @@ public static class TiffImageReader private static int Copy(byte[] data, byte[] raw) { var n = Math.Min(data.Length, raw.Length); - data.AsSpan(0, n).CopyTo(raw); + if (!ReferenceEquals(data, raw)) data.AsSpan(0, n).CopyTo(raw); return n; } + /// Reads one strip/tile; large uncompressed strips (single-strip files) exceed TiffReader's per-read cap + /// and are read in pieces. + private static byte[]? ReadChunk(TiffReader reader, uint offset, uint length) + { + if (length <= TiffReader.MaxValueBytes) return reader.ReadRelative(offset, (int)length); + if (length > MaxChunkBytes || offset + (long)length > reader.StreamLength - reader.Base) return null; + var result = new byte[length]; + for (long done = 0; done < length;) + { + var piece = (int)Math.Min(TiffReader.MaxValueBytes, length - done); + if (reader.ReadRelative(offset + done, piece) is not { } part) return null; + part.CopyTo(result, done); + done += piece; + } + return result; + } + private static void Place(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane) { if (g.Planes == 1) diff --git a/tests/Titano.Core.Tests/Codecs/TiffTests.cs b/tests/Titano.Core.Tests/Codecs/TiffTests.cs index 92777536..c5414c95 100644 --- a/tests/Titano.Core.Tests/Codecs/TiffTests.cs +++ b/tests/Titano.Core.Tests/Codecs/TiffTests.cs @@ -127,6 +127,20 @@ public sealed class TiffTests(TestContext context) Assert.SequenceEqual(samples, Raster(tiff).Samples!); } + [Test] + public void SingleStripLargerThanTheReaderCapDecodes() + { + // Photoshop-style single uncompressed strip of 70 MB (TiffReader reads at most 64 MB per call). + const int w = 5000, h = 7000; + var strip = new byte[w * h * 2]; + for (var i = 0; i < strip.Length; i += 2) BinaryPrimitives.WriteUInt16LittleEndian(strip.AsSpan(i), (ushort)(i * 7)); + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 16, compression: 1), [strip], tiled: false); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.Equal(unchecked((ushort)((w * h - 1) * 2 * 7)), raster.Samples![^1]); + Assert.Equal(unchecked((ushort)(12345 * 2 * 7)), raster.Samples[12345]); + } + [Test] public void PackedTwelveBitSamplesUnpack() {