From 6d9ede0c47becf7342b16d21e06a0343ad1dc368 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:02:27 +0000 Subject: [PATCH] feat(codecs): add TIFF raster reader and TIFF writer TiffImageReader decodes strips and tiles (chunky or planar) with none, LZW (old-style bit order tolerated), Deflate, PackBits and JPEG compression (JPEGTables, YCbCr or RGB, lossless SOF3 tiles reshaped as DNG writes them), predictors 2/3 and the DNG x2/x4 variants, 1-16 bit integer and 16/32-bit float samples; tiles decode in parallel. Output is a raw TiffRaster or a linear ImageBuffer. JPEG strips match libtiff bit for bit. TiffWriter writes 8/16-bit gray/RGB/RGBA, uncompressed or Deflate with horizontal predictor, and embeds capture metadata from an Exif block. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs | 9 + .../Codecs/Tiff/TiffDecompressors.cs | 121 +++++ src/Titano.Core/Codecs/Tiff/TiffDirectory.cs | 189 ++++++++ .../Codecs/Tiff/TiffImageReader.cs | 425 ++++++++++++++++++ src/Titano.Core/Codecs/Tiff/TiffWriter.cs | 222 +++++++++ .../Codecs/TiffTestEncoders.cs | 127 ++++++ tests/Titano.Core.Tests/Codecs/TiffTests.cs | 315 +++++++++++++ tests/fixtures/codecs/make-fixtures.sh | 1 + tests/fixtures/codecs/tiff/jpeg-rgb.ppm | Bin 0 -> 8248 bytes tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm | Bin 0 -> 8248 bytes 10 files changed, 1409 insertions(+) create mode 100644 src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffDirectory.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffImageReader.cs create mode 100644 src/Titano.Core/Codecs/Tiff/TiffWriter.cs create mode 100644 tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs create mode 100644 tests/Titano.Core.Tests/Codecs/TiffTests.cs create mode 100644 tests/fixtures/codecs/tiff/jpeg-rgb.ppm create mode 100644 tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm diff --git a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs index 00f32884..63afe5c9 100644 --- a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs +++ b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs @@ -44,6 +44,15 @@ public static class JpegDecoder return new JpegRenderer(parser).RenderLinear(expandGray); } + /// Decodes a TIFF/DNG tile: lossless streams return raw samples (any component count), DCT streams pixels. + internal static (JpegImage? Image, JpegLosslessImage Raw) DecodeTile(ReadOnlySpan data, JpegDecodeOptions options) + { + var parser = Parse(data, options); + return parser.Frame!.Process == JpegProcess.Lossless + ? (null, JpegLosslessDecoder.Finish(parser)) + : (new JpegRenderer(parser).RenderInterleaved(parser.Info()), default); + } + private static JpegParser Parse(ReadOnlySpan data, JpegDecodeOptions? options) { var parser = new JpegParser(options ?? JpegDecodeOptions.Default); diff --git a/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs b/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs new file mode 100644 index 00000000..da328f6f --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffDecompressors.cs @@ -0,0 +1,121 @@ +using System.IO.Compression; + +namespace Titano.Core.Codecs.Tiff; + +/// +/// Strip/tile decompressors. Each fills exactly output.Length bytes when the data allows and returns the number +/// of bytes produced; damaged data ends early instead of throwing out of range. +/// +internal static class TiffDecompressors +{ + /// TIFF LZW (MSB-first codes, "early change"). Old-style streams (pre-6.0 libtiff, LSB-first codes, + /// no early change) are recognised by their first byte as libtiff does. + public static int Lzw(ReadOnlySpan input, Span output) + { + const int clear = 256, eoi = 257, maxCodes = 4096; + var oldStyle = input.Length >= 2 && input[0] == 0 && (input[1] & 1) != 0; + Span prefix = stackalloc ushort[maxCodes]; + Span suffix = stackalloc byte[maxCodes]; + Span first = stackalloc byte[maxCodes]; + Span length = stackalloc ushort[maxCodes]; + for (var i = 0; i < 256; i++) + { + suffix[i] = first[i] = (byte)i; + length[i] = 1; + } + int next = 258, width = 9, old = -1, written = 0, inPos = 0, bits = 0; + uint acc = 0; + var early = oldStyle ? 0 : 1; + while (written < output.Length) + { + while (bits < width && inPos < input.Length) + { + if (oldStyle) acc |= (uint)input[inPos++] << bits; + else acc = acc << 8 | input[inPos++]; + bits += 8; + } + if (bits < width) break; + int code; + if (oldStyle) + { + code = (int)(acc & ((1u << width) - 1)); + acc >>= width; + } + else + { + code = (int)(acc >> (bits - width)) & ((1 << width) - 1); + } + bits -= width; + if (code == eoi) break; + if (code == clear) + { + next = 258; + width = 9; + old = -1; + continue; + } + if (old < 0) + { + if (code > 255) break; // the first code after a clear must be a literal + } + else + { + if (code > next || next >= maxCodes && code == next) break; // corrupt: code beyond the table + if (next < maxCodes) + { + // New entry: old string + first byte of the current string (KwKwK when code == next). + prefix[next] = (ushort)old; + suffix[next] = code < next ? first[code] : first[old]; + first[next] = first[old]; + length[next] = (ushort)Math.Min(ushort.MaxValue, length[old] + 1); + next++; + } + } + // Strings are prefix chains: write back to front, clipped to the output. + var len = length[code]; + var end = Math.Min(written + len, output.Length); + var c = code; + for (var p = written + len - 1; p >= written; p--) + { + if (p < end) output[p] = suffix[c]; + c = prefix[c]; + } + written = end; + old = code; + if (next + early >= 1 << width && width < 12) width++; + } + return written; + } + + /// Macintosh PackBits run-length decoding. + public static int PackBits(ReadOnlySpan input, Span output) + { + int i = 0, o = 0; + while (i < input.Length && o < output.Length) + { + var n = (sbyte)input[i++]; + if (n >= 0) + { + var count = Math.Min(n + 1, Math.Min(input.Length - i, output.Length - o)); + input.Slice(i, count).CopyTo(output[o..]); + i += n + 1; + o += count; + } + else if (n != -128) + { + if (i >= input.Length) break; + var count = Math.Min(1 - n, output.Length - o); + output.Slice(o, count).Fill(input[i++]); + o += count; + } + } + return o; + } + + /// zlib (Adobe Deflate, TIFF compression 8/32946). + public static int Deflate(byte[] input, Span output) + { + using var z = new ZLibStream(new MemoryStream(input, writable: false), CompressionMode.Decompress); + return z.ReadAtLeast(output, output.Length, throwOnEndOfStream: false); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs b/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs new file mode 100644 index 00000000..05fb8c80 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffDirectory.cs @@ -0,0 +1,189 @@ +using System.Buffers.Binary; +using System.Text; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// +/// A little-endian IFD under construction for and the DNG writer: entries kept sorted by +/// tag, values ≤ 4 bytes inline, larger ones word-aligned after the entry table, child IFDs (Exif, GPS, Interop) +/// laid out after their parent. +/// +internal sealed class TiffDirectory +{ + private readonly SortedDictionary _entries = []; + private readonly SortedDictionary _children = []; + private long _offset = -1; + + public bool Has(ushort tag) => _entries.ContainsKey(tag) || _children.ContainsKey(tag); + + /// Adds an entry whose value bytes are already little-endian. + public void Add(ushort tag, TiffType type, int count, byte[] value) => _entries[tag] = (type, count, value); + + public void Short(ushort tag, params ReadOnlySpan values) + { + var b = new byte[values.Length * 2]; + for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(b.AsSpan(2 * i), values[i]); + Add(tag, TiffType.Short, values.Length, b); + } + + public void Long(ushort tag, params ReadOnlySpan values) + { + var b = new byte[values.Length * 4]; + for (var i = 0; i < values.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4 * i), values[i]); + Add(tag, TiffType.Long, values.Length, b); + } + + public void Rational(ushort tag, params ReadOnlySpan<(uint Numerator, uint Denominator)> values) + { + var b = new byte[values.Length * 8]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator); + } + Add(tag, TiffType.Rational, values.Length, b); + } + + public void SRational(ushort tag, params ReadOnlySpan<(int Numerator, int Denominator)> values) + { + var b = new byte[values.Length * 8]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i), values[i].Numerator); + BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(8 * i + 4), values[i].Denominator); + } + Add(tag, TiffType.SRational, values.Length, b); + } + + public void Ascii(ushort tag, string value) + { + var b = Encoding.UTF8.GetBytes(value + "\0"); + Add(tag, TiffType.Ascii, b.Length, b); + } + + public void Bytes(ushort tag, params ReadOnlySpan values) => Add(tag, TiffType.Byte, values.Length, values.ToArray()); + + /// Links a sub-IFD through a LONG pointer entry (resolved during ). + public void Child(ushort tag, TiffDirectory child) => _children[tag] = child; + + private int OwnSize + { + get + { + var size = 2 + 12 * (_entries.Count + _children.Count) + 4; + foreach (var (_, (_, _, value)) in _entries) + { + if (value.Length > 4) size += (value.Length + 1) & ~1; + } + return size; + } + } + + /// Assigns file offsets to this directory and its children (depth first); returns the end offset. + public long Layout(long offset) + { + _offset = (offset + 1) & ~1L; + var end = _offset + OwnSize; + foreach (var child in _children.Values) end = child.Layout(end); + if (end > uint.MaxValue) throw new InvalidOperationException("TIFF exceeds 4 GB"); + return end; + } + + /// Writes this directory and its children at the offsets chosen by . + /// Positioned at or before this directory's offset. + public void Write(Stream output) + { + if (_offset < 0) throw new InvalidOperationException("Layout must run before Write"); + while (output.Position < _offset) output.WriteByte(0); + var buffer = new byte[OwnSize]; + var count = _entries.Count + _children.Count; + BinaryPrimitives.WriteUInt16LittleEndian(buffer, (ushort)count); + var valueAt = 2 + 12 * count + 4; + var e = 2; + var all = _entries.Select(kv => (kv.Key, kv.Value.Type, kv.Value.Count, kv.Value.Value, Child: (TiffDirectory?)null)) + .Concat(_children.Select(kv => (kv.Key, TiffType.Long, 1, Array.Empty(), Child: (TiffDirectory?)kv.Value))) + .OrderBy(x => x.Key); + foreach (var (tag, type, n, value, child) in all) + { + var entry = buffer.AsSpan(e, 12); + BinaryPrimitives.WriteUInt16LittleEndian(entry, tag); + BinaryPrimitives.WriteUInt16LittleEndian(entry[2..], (ushort)type); + BinaryPrimitives.WriteUInt32LittleEndian(entry[4..], (uint)n); + if (child is not null) + { + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)child._offset); + } + else if (value.Length <= 4) + { + value.CopyTo(entry[8..]); + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)(_offset + valueAt)); + value.CopyTo(buffer.AsSpan(valueAt)); + valueAt += (value.Length + 1) & ~1; + } + e += 12; + } + output.Write(buffer); + foreach (var child in _children.Values) child.Write(output); + } + + /// + /// Copies capture metadata from a TIFF-structured Exif block (a JPEG APP1 payload, with or without the + /// "Exif\0\0" prefix): IFD0 descriptive tags plus the Exif (with Interop) and GPS sub-IFDs, converted to + /// little-endian. Maker notes are copied as opaque bytes (offsets inside them are not rebased). + /// + public void AttachExif(byte[] exif) + { + var start = exif.AsSpan().StartsWith("Exif\0\0"u8) ? 6 : 0; + using var stream = new MemoryStream(exif, start, exif.Length - start, writable: false); + var reader = TiffReader.Open(stream) ?? throw new ArgumentException("Exif block is not TIFF-structured", nameof(exif)); + var chain = reader.ReadChain(); + if (chain.Count == 0) throw new ArgumentException("Exif block has no IFD", nameof(exif)); + var ifd0 = chain[0]; + foreach (var tag in (ReadOnlySpan)[TiffTags.ImageDescription, TiffTags.Make, TiffTags.Model, TiffTags.DateTime, TiffTags.Artist, TiffTags.Copyright]) + { + if (!Has(tag) && ifd0.Entries.TryGetValue(tag, out var entry)) CopyEntry(reader, entry); + } + var visited = new HashSet { ifd0.Position }; + foreach (var pointer in (ReadOnlySpan)[TiffTags.ExifIfd, TiffTags.GpsIfd]) + { + if (reader.GetUInt(ifd0, pointer) is { } offset && reader.ReadIfd(offset, visited) is { } sub) Child(pointer, CopyDirectory(reader, sub, visited, 0)); + } + } + + private static TiffDirectory CopyDirectory(TiffReader reader, Ifd source, HashSet visited, int depth) + { + var copy = new TiffDirectory(); + foreach (var entry in source.Entries.Values) + { + if (entry.Tag == TiffTags.InteropIfd) + { + if (depth < 2 && reader.GetUInts(entry) is [var offset, ..] && reader.ReadIfd(offset, visited) is { } interop) + copy.Child(entry.Tag, CopyDirectory(reader, interop, visited, depth + 1)); + continue; + } + copy.CopyEntry(reader, entry); + } + return copy; + } + + private void CopyEntry(TiffReader reader, IfdEntry entry) + { + if (reader.ReadBytes(entry) is not { } value) return; + if (!reader.LittleEndian) + { + var size = entry.Type switch + { + TiffType.Short or TiffType.SShort => 2, + TiffType.Long or TiffType.SLong or TiffType.Float or TiffType.Ifd or TiffType.Rational or TiffType.SRational => 4, + TiffType.Double => 8, + _ => 1, + }; + for (var i = 0; size > 1 && i + size <= value.Length; i += size) value.AsSpan(i, size).Reverse(); + } + Add(entry.Tag, entry.Type, (int)entry.Count, value); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs new file mode 100644 index 00000000..09e8f367 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs @@ -0,0 +1,425 @@ +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// TIFF SampleFormat values handled by . +public enum TiffSampleFormat +{ + UnsignedInteger = 1, + Float = 3, +} + +/// Decoded samples of one IFD: chunky (interleaved), top-down, cropped to the image size. +public sealed class TiffRaster +{ + internal TiffRaster(int width, int height, int samplesPerPixel, int bitsPerSample, TiffSampleFormat format, int photometric, ushort[]? samples, float[]? floats, IReadOnlyList warnings) + { + Width = width; + Height = height; + SamplesPerPixel = samplesPerPixel; + BitsPerSample = bitsPerSample; + SampleFormat = format; + Photometric = photometric; + Samples = samples; + FloatSamples = floats; + Warnings = warnings; + } + + public int Width { get; } + public int Height { get; } + public int SamplesPerPixel { get; } + + /// Significant bits per sample (integer samples are 0..2^bits−1; JPEG tiles report their precision). + public int BitsPerSample { get; } + + public TiffSampleFormat SampleFormat { get; } + + /// PhotometricInterpretation of the samples as returned (JPEG-coded YCbCr is delivered as RGB = 2). + public int Photometric { get; } + + /// Integer samples (). + public ushort[]? Samples { get; } + + /// Floating-point samples (16/32-bit float TIFF and DNG). + public float[]? FloatSamples { get; } + + /// Recoverable problems (missing or truncated strips/tiles, JPEG warnings). + public IReadOnlyList Warnings { get; } +} + +/// Options for . +public sealed record TiffDecodeOptions +{ + public static TiffDecodeOptions Default { get; } = new(); + + /// Integer samples are linear light (otherwise sRGB-encoded is assumed; LinearRaw is always linear). + public bool AssumeLinear { get; init; } + + /// Upper bound on width × height × samples per pixel, checked before allocation. + public long MaxSamples { get; init; } = 1L << 29; + + /// Worker limit for strip/tile decoding (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// TIFF/DNG pixel data on top of : strips and tiles, chunky and planar, compression none / LZW +/// (old-style bit order tolerated) / Deflate / PackBits / JPEG (with JPEGTables; YCbCr or RGB; lossless SOF3 for DNG, +/// including tiles whose JPEG frame is laid out as e.g. 2 components × width/2), predictors 2 and 3 (and the DNG ×2/×4 +/// variants), 1–16-bit integer and 16/32-bit float samples. Strips and tiles decode in parallel. +/// +public static class TiffImageReader +{ + private const int CompressionNone = 1, CompressionLzw = 5, CompressionJpeg = 7, CompressionDeflate = 8; + 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; + + /// 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) + { + var reader = TiffReader.Open(stream) ?? throw new InvalidDataException("TIFF: missing header"); + var chain = reader.ReadChain(); + if (chain.Count == 0) throw new InvalidDataException("TIFF: no image directory"); + var ifd = chain.FirstOrDefault(i => ((reader.GetUInt(i, TiffTags.NewSubfileType) ?? 0) & 1) == 0) ?? chain[0]; + var o = options ?? TiffDecodeOptions.Default; + return ToImageBuffer(ReadRaster(reader, ifd, o), o); + } + + public static ImageBuffer Decode(byte[] data, TiffDecodeOptions? options = null) => Decode(new MemoryStream(data, writable: false), options); + + /// Converts a gray/RGB raster to linear light (min-is-white inverted; extra samples dropped). + public static ImageBuffer ToImageBuffer(TiffRaster raster, TiffDecodeOptions? options = null) + { + var o = options ?? TiffDecodeOptions.Default; + if (raster.Photometric is PhotometricCfa or PhotometricPalette) + throw new InvalidDataException($"TIFF: photometric {raster.Photometric} needs colour reconstruction (CFA/palette) not done here"); + int w = raster.Width, h = raster.Height, spp = raster.SamplesPerPixel; + var colour = spp >= 3 && raster.Photometric is PhotometricRgb or PhotometricLinearRaw; + var channels = colour ? 3 : 1; + if (raster.FloatSamples is { } floats) + { + var image = new ImageBuffer(w, h, channels, clear: false); + for (var c = 0; c < channels; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = floats[i * spp + c]; + } + return image; + } + var samples = raster.Samples!; + var max = (1 << raster.BitsPerSample) - 1; + var packedChannels = colour ? Math.Min(spp, 4) : Math.Min(spp, 2); + if (raster.Photometric == PhotometricMinIsWhite || packedChannels != spp) + { + var packed = new ushort[w * h * packedChannels]; + var invert = raster.Photometric == PhotometricMinIsWhite; + for (var i = 0; i < w * h; i++) + { + for (var c = 0; c < packedChannels; c++) + { + var v = samples[i * spp + c]; + packed[i * packedChannels + c] = invert && c == 0 ? (ushort)(max - v) : v; + } + } + samples = packed; + } + var transfer = o.AssumeLinear || raster.Photometric == PhotometricLinearRaw ? TransferFunction.Linear : TransferFunction.Srgb; + return PixelConvert.FromInterleaved16(samples, w, h, packedChannels, transfer, max, channels); + } + + /// Decodes every strip or tile of into one raster. + /// Missing or inconsistent layout tags, or an unsupported encoding. + public static TiffRaster ReadRaster(TiffReader reader, Ifd ifd, TiffDecodeOptions? options = null) + { + var o = options ?? TiffDecodeOptions.Default; + var g = Geometry.Read(reader, ifd, o); + var warnings = new List(); + var count = g.ChunksPerPlane * g.Planes; + 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)]; + if (counts is null) throw new InvalidDataException("TIFF: missing strip/tile byte counts"); + if (offsets.Length < count || counts.Length < count) warnings.Add($"TIFF: {count} strips/tiles expected, {Math.Min(offsets.Length, counts.Length)} present"); + + // I/O is sequential (one stream); decoding is parallel. + var chunks = new byte[]?[count]; + 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)); + 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; + + var total = (long)g.Width * g.Height * g.Spp; + var ints = g.Format == TiffSampleFormat.UnsignedInteger ? new ushort[total] : null; + var floats = ints is null ? new float[total] : null; + var bits = g.Bps; + var gate = new Lock(); + Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }, i => + { + if (chunks[i] is not { } data) return; + try + { + var decoded = DecodeChunk(g, i, data, tables, ints, floats, reader.LittleEndian); + if (decoded.Warning is { } warning) + { + lock (gate) warnings.Add(warning); + } + if (decoded.Bits > 0) bits = decoded.Bits; + } + catch (InvalidDataException ex) + { + lock (gate) warnings.Add($"TIFF: strip/tile {i}: {ex.Message}"); + } + }); + var photometric = g.Photometric == PhotometricYCbCr && g.IsJpeg ? PhotometricRgb : g.Photometric; + return new TiffRaster(g.Width, g.Height, g.Spp, bits, g.Format, photometric, ints, floats, warnings); + } + + /// Layout of the image data of one IFD. + private sealed class Geometry + { + public int Width, Height, Spp, Bps, Compression, Photometric, Planes, ChunkSpp, Predictor, PredictorStride; + public int ChunkWidth, ChunkHeight, Across, ChunksPerPlane; + public long RowBytes; + public bool Tiled, FloatPredictor; + public TiffSampleFormat Format; + public bool IsJpeg => Compression is CompressionJpeg or CompressionLossyJpeg; + + public static Geometry Read(TiffReader r, Ifd ifd, TiffDecodeOptions o) + { + var g = new Geometry + { + Width = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageWidth) ?? 0, int.MaxValue), + Height = (int)Math.Min(r.GetUInt(ifd, TiffTags.ImageLength) ?? 0, int.MaxValue), + Spp = (int)Math.Min(r.GetUInt(ifd, TiffTags.SamplesPerPixel) ?? 1, 64), + Compression = (int)(r.GetUInt(ifd, TiffTags.Compression) ?? CompressionNone), + Predictor = (int)(r.GetUInt(ifd, TiffTags.Predictor) ?? 1), + }; + if (g.Width == 0 || g.Height == 0 || g.Spp == 0) throw new InvalidDataException("TIFF: missing or zero image size"); + if ((long)g.Width * g.Height * g.Spp > o.MaxSamples) throw new InvalidDataException($"TIFF: {g.Width}x{g.Height}x{g.Spp} exceeds the sample limit"); + var bps = r.GetUInts(ifd, TiffTags.BitsPerSample) ?? [1]; + if (bps.Length == 0 || bps.Any(b => b != bps[0])) throw new InvalidDataException("TIFF: mixed bits per sample are not supported"); + g.Bps = (int)Math.Min(bps[0], 64); + g.Format = (r.GetUInt(ifd, TiffTags.SampleFormat) ?? 1) switch + { + 1 => TiffSampleFormat.UnsignedInteger, + 3 => TiffSampleFormat.Float, + var f => throw new InvalidDataException($"TIFF: sample format {f} is not supported"), + }; + if (g.Format == TiffSampleFormat.Float ? g.Bps is not (16 or 32) : g.Bps is < 1 or > 16) + throw new InvalidDataException($"TIFF: {g.Bps}-bit {g.Format} samples are not supported"); + if (g.Compression is not (CompressionNone or CompressionLzw or CompressionJpeg or CompressionDeflate or CompressionAdobeDeflate or CompressionPackBits or CompressionLossyJpeg)) + throw new InvalidDataException($"TIFF: compression {g.Compression} is not supported"); + if (g.IsJpeg && g.Format == TiffSampleFormat.Float) throw new InvalidDataException("TIFF: JPEG-compressed float data"); + g.Photometric = (int)(r.GetUInt(ifd, TiffTags.PhotometricInterpretation) ?? (uint)(g.Spp >= 3 ? PhotometricRgb : 1)); + if (g.Photometric == PhotometricYCbCr && !g.IsJpeg) throw new InvalidDataException("TIFF: uncompressed YCbCr is not supported"); + + // Predictor 2/3 and the DNG 1.4 ×2/×4 variants (34892–34895) differ only in the differencing stride. + (g.FloatPredictor, var factor) = g.Predictor switch + { + 1 => (false, 0), + 2 => (false, 1), + 3 => (true, 1), + 34892 => (false, 2), + 34893 => (false, 4), + 34894 => (true, 2), + 34895 => (true, 4), + var p => throw new InvalidDataException($"TIFF: predictor {p} is not supported"), + }; + if (factor > 0 && g.FloatPredictor != (g.Format == TiffSampleFormat.Float)) throw new InvalidDataException("TIFF: predictor does not match the sample format"); + g.Planes = (r.GetUInt(ifd, TiffTags.PlanarConfiguration) ?? 1) == 2 ? g.Spp : 1; + g.ChunkSpp = g.Planes == 1 ? g.Spp : 1; + g.PredictorStride = g.ChunkSpp * factor; + + g.Tiled = ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets); + if (g.Tiled) + { + g.ChunkWidth = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileWidth) ?? 0, 1 << 16); + g.ChunkHeight = (int)Math.Min(r.GetUInt(ifd, TiffTags.TileLength) ?? 0, 1 << 16); + if (g.ChunkWidth == 0 || g.ChunkHeight == 0) throw new InvalidDataException("TIFF: zero tile size"); + g.Across = (g.Width + g.ChunkWidth - 1) / g.ChunkWidth; + g.ChunksPerPlane = checked(g.Across * ((g.Height + g.ChunkHeight - 1) / g.ChunkHeight)); + } + else + { + g.ChunkWidth = g.Width; + g.ChunkHeight = (int)Math.Clamp(r.GetUInt(ifd, TiffTags.RowsPerStrip) ?? (uint)g.Height, 1, (uint)g.Height); + g.Across = 1; + 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"); + return g; + } + } + + private readonly record struct ChunkResult(string? Warning, int Bits); + + private static ChunkResult DecodeChunk(Geometry g, int index, byte[] data, byte[]? tables, ushort[]? ints, float[]? floats, bool littleEndian) + { + var plane = index / g.ChunksPerPlane; + var local = index % g.ChunksPerPlane; + var x0 = local % g.Across * g.ChunkWidth; + var y0 = local / g.Across * g.ChunkHeight; + var rows = g.Tiled ? g.ChunkHeight : Math.Min(g.ChunkHeight, g.Height - y0); + var validW = Math.Min(g.ChunkWidth, g.Width - x0); + var validH = Math.Min(rows, g.Height - y0); + 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 produced = g.Compression switch + { + CompressionNone => Copy(data, raw), + CompressionLzw => TiffDecompressors.Lzw(data, raw), + CompressionPackBits => TiffDecompressors.PackBits(data, raw), + _ => TiffDecompressors.Deflate(data, raw), + }; + var rowBytes = (int)g.RowBytes; + var rowSamples = g.ChunkWidth * g.ChunkSpp; + var ushorts = ints is null ? null : new ushort[rowSamples]; + var singles = floats is null ? null : new float[rowSamples]; + for (var r = 0; r < validH; r++) + { + var row = raw.AsSpan(r * rowBytes, rowBytes); + if (ushorts is not null) + { + UnpackIntegers(row, g.Bps, littleEndian, ushorts); + if (g.PredictorStride > 0) + { + var mask = (1 << g.Bps) - 1; + for (var i = g.PredictorStride; i < rowSamples; i++) ushorts[i] = (ushort)((ushorts[i] + ushorts[i - g.PredictorStride]) & mask); + } + Place(ushorts, ints!, g, x0, y0 + r, validW, plane); + } + else + { + UnpackFloats(row, g, littleEndian, singles!); + Place(singles!, floats!, g, x0, y0 + r, validW, plane); + } + } + return new ChunkResult(produced < expected ? $"TIFF: strip/tile {index} truncated ({produced}/{expected} bytes)" : null, 0); + } + + private static int Copy(byte[] data, byte[] raw) + { + var n = Math.Min(data.Length, raw.Length); + data.AsSpan(0, n).CopyTo(raw); + return n; + } + + private static void Place(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane) + { + if (g.Planes == 1) + { + row.AsSpan(0, validW * g.Spp).CopyTo(target.AsSpan((int)(((long)y * g.Width + x0) * g.Spp))); + return; + } + var start = (int)(((long)y * g.Width + x0) * g.Spp + plane); + for (var x = 0; x < validW; x++) target[start + x * g.Spp] = row[x]; + } + + /// MSB-first unpacking of 1–16-bit samples (8/16-bit in file byte order). + private static void UnpackIntegers(ReadOnlySpan row, int bps, bool littleEndian, ushort[] dst) + { + switch (bps) + { + case 8: + for (var i = 0; i < dst.Length; i++) dst[i] = row[i]; + return; + case 16: + for (var i = 0; i < dst.Length; i++) + { + dst[i] = littleEndian ? (ushort)(row[2 * i] | row[2 * i + 1] << 8) : (ushort)(row[2 * i] << 8 | row[2 * i + 1]); + } + return; + } + long bit = 0; + for (var i = 0; i < dst.Length; i++) + { + var v = 0; + for (var b = 0; b < bps; b++, bit++) v = v << 1 | (row[(int)(bit >> 3)] >> (7 - (int)(bit & 7)) & 1); + dst[i] = (ushort)v; + } + } + + /// 16/32-bit floats; the floating-point predictor stores byte planes MSB-first after byte differencing. + private static void UnpackFloats(Span row, Geometry g, bool littleEndian, float[] dst) + { + var size = g.Bps / 8; + var count = dst.Length; + if (g.PredictorStride > 0) + { + for (var i = g.PredictorStride; i < row.Length; i++) row[i] += row[i - g.PredictorStride]; + for (var i = 0; i < count; i++) + { + uint bits = 0; + for (var k = 0; k < size; k++) bits = bits << 8 | row[k * count + i]; + dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits); + } + return; + } + for (var i = 0; i < count; i++) + { + uint bits = 0; + for (var k = 0; k < size; k++) bits = bits << 8 | row[i * size + (littleEndian ? size - 1 - k : k)]; + dst[i] = size == 4 ? BitConverter.UInt32BitsToSingle(bits) : (float)BitConverter.UInt16BitsToHalf((ushort)bits); + } + } + + private static ChunkResult DecodeJpegChunk(Geometry g, byte[] data, byte[]? tables, ushort[] ints, int x0, int y0, int validW, int validH, int plane) + { + var options = new JpegDecodeOptions + { + Tables = tables, + MaxDegreeOfParallelism = 1, + ColorTransform = g.Photometric switch + { + PhotometricYCbCr => JpegColorTransform.YCbCr, + PhotometricRgb when g.Compression == CompressionJpeg => JpegColorTransform.None, + _ => JpegColorTransform.Auto, + }, + }; + var (image, raw) = JpegDecoder.DecodeTile(data, options); + string? warning = null; + if (image is not null) + { + var comps = Math.Min(image.Components, g.ChunkSpp); + var w = Math.Min(validW, image.Width); + for (var r = 0; r < Math.Min(validH, image.Height); r++) + { + for (var x = 0; x < w; x++) + { + var src = (r * image.Width + x) * image.Components; + var dst = ((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane; + for (var c = 0; c < comps; c++) ints[dst + c] = image.Pixels8 is { } p8 ? p8[src + c] : image.Pixels16![src + c]; + } + } + if (image.Warnings.Count > 0) warning = "TIFF: " + image.Warnings[0]; + return new ChunkResult(warning, image.BitDepth); + } + + // Lossless: the JPEG frame may be shaped differently from the tile (DNG writes e.g. 2 components × width/2), + // but the sample stream order is the same, so samples map back linearly. + var samples = raw.Samples; + var perRow = g.ChunkWidth * g.ChunkSpp; + var tileSamples = (long)perRow * g.ChunkHeight; + if (samples.Length != tileSamples) warning = $"TIFF: lossless JPEG holds {samples.Length} samples, tile needs {tileSamples}"; + var n = (int)Math.Min(samples.Length, tileSamples); + for (var k = 0; k < n; k++) + { + var r = k / perRow; + var rem = k - r * perRow; + var x = rem / g.ChunkSpp; + if (r >= validH) break; + if (x >= validW) continue; + ints[((long)(y0 + r) * g.Width + x0 + x) * g.Spp + plane + rem % g.ChunkSpp] = samples[k]; + } + return new ChunkResult(warning, raw.Precision); + } +} diff --git a/src/Titano.Core/Codecs/Tiff/TiffWriter.cs b/src/Titano.Core/Codecs/Tiff/TiffWriter.cs new file mode 100644 index 00000000..9e8c6051 --- /dev/null +++ b/src/Titano.Core/Codecs/Tiff/TiffWriter.cs @@ -0,0 +1,222 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Codecs.Tiff; + +/// Compression written by . +public enum TiffCompression +{ + None = 1, + Deflate = 8, +} + +/// Options for . +public sealed record TiffWriteOptions +{ + public static TiffWriteOptions Default { get; } = new(); + + /// 8 or 16. + public int BitsPerSample { get; init; } = 16; + + public TiffCompression Compression { get; init; } = TiffCompression.Deflate; + + /// Horizontal differencing (Predictor = 2) before Deflate; ignored when uncompressed. + public bool Predictor { get; init; } = true; + + /// Encoding of input: sRGB (display-ready) or linear light. + public TransferFunction Transfer { get; init; } = TransferFunction.Srgb; + + public CompressionLevel Level { get; init; } = CompressionLevel.Optimal; + + /// TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded. + public byte[]? Exif { get; init; } + + /// Worker limit for strip encoding (-1 = all cores). + public int MaxDegreeOfParallelism { get; init; } = -1; +} + +/// +/// Little-endian baseline TIFF writer: 8/16-bit gray, RGB or RGBA (unassociated alpha), uncompressed or Deflate with +/// optional horizontal predictor, optional embedded Exif. Strips are encoded in parallel and written in order. +/// +public static class TiffWriter +{ + private const int TargetStripBytes = 256 * 1024; + + public static byte[] Write(ImageBuffer image, TiffWriteOptions? options = null) + { + using var ms = new MemoryStream(); + Write(ms, image, options); + return ms.ToArray(); + } + + /// Writes a linear-light buffer (1 channel → gray, 3 → RGB, 4 → RGBA). + public static void Write(Stream output, ImageBuffer image, TiffWriteOptions? options = null) + { + var o = options ?? TiffWriteOptions.Default; + var channels = image.Channels; + Write(output, image.Width, image.Height, channels, o, (y, row) => + { + if (o.BitsPerSample == 16) + { + PixelConvert.EncodeRow16(image, y, row, channels, o.Transfer); + return; + } + var buffer = ArrayPool.Shared.Rent(row.Length); + PixelConvert.EncodeRow8(image, y, buffer.AsSpan(0, row.Length), channels, o.Transfer, dither: false); + for (var i = 0; i < row.Length; i++) row[i] = buffer[i]; + ArrayPool.Shared.Return(buffer); + }); + } + + /// Writes interleaved, already-encoded samples (values below 2^). + public static unsafe void Write(Stream output, ReadOnlySpan samples, int width, int height, int channels, TiffWriteOptions? options = null) + { + if (samples.Length < (long)width * height * channels) throw new ArgumentException("Sample buffer too small", nameof(samples)); + fixed (ushort* p = samples) + { + var ptr = (nint)p; + Write(output, width, height, channels, options ?? TiffWriteOptions.Default, + (y, row) => new ReadOnlySpan((ushort*)ptr + (long)y * width * channels, width * channels).CopyTo(row)); + } + } + + private delegate void RowSource(int y, Span row); + + private static void Write(Stream output, int width, int height, int channels, TiffWriteOptions o, RowSource source) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (channels is < 1 or > 4 or 2) throw new ArgumentOutOfRangeException(nameof(channels), "1, 3 or 4 channels"); + if (o.BitsPerSample is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(o), "8 or 16 bits per sample"); + if (!output.CanSeek) + { + using var buffer = new MemoryStream(); + Write(buffer, width, height, channels, o, source); + buffer.Position = 0; + buffer.CopyTo(output); + return; + } + + var start = output.Position; + output.Write("II*\0\0\0\0\0"u8); + var bytesPerSample = o.BitsPerSample / 8; + var rowBytes = (long)width * channels * bytesPerSample; + var rowsPerStrip = (int)Math.Clamp(TargetStripBytes / rowBytes, 1, height); + var strips = (height + rowsPerStrip - 1) / rowsPerStrip; + var deflate = o.Compression == TiffCompression.Deflate; + var predictor = deflate && o.Predictor; + var offsets = new uint[strips]; + var counts = new uint[strips]; + var batch = Math.Max(1, Environment.ProcessorCount * 2); + var encoded = new byte[batch][]; + var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism }; + for (var first = 0; first < strips; first += batch) + { + var n = Math.Min(batch, strips - first); + Parallel.For(0, n, parallel, k => + { + var s = first + k; + var y0 = s * rowsPerStrip; + var rows = Math.Min(rowsPerStrip, height - y0); + var raw = new byte[rowBytes * rows]; + var row = new ushort[width * channels]; + for (var r = 0; r < rows; r++) + { + source(y0 + r, row); + if (predictor) + { + var mask = (1 << o.BitsPerSample) - 1; + for (var i = row.Length - 1; i >= channels; i--) row[i] = (ushort)((row[i] - row[i - channels]) & mask); + } + var dst = raw.AsSpan((int)(r * rowBytes), (int)rowBytes); + if (bytesPerSample == 2) + { + for (var i = 0; i < row.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(dst[(2 * i)..], row[i]); + } + else + { + for (var i = 0; i < row.Length; i++) dst[i] = (byte)row[i]; + } + } + encoded[k] = deflate ? Deflate(raw, o.Level) : raw; + }); + for (var k = 0; k < n; k++) + { + if (output.Position - start > uint.MaxValue - (long)encoded[k].Length) throw new InvalidOperationException("TIFF exceeds 4 GB"); + offsets[first + k] = (uint)(output.Position - start); + counts[first + k] = (uint)encoded[k].Length; + output.Write(encoded[k]); + } + } + + var ifd = new TiffDirectory(); + ifd.Long(TiffTags.NewSubfileType, 0); + ifd.Long(TiffTags.ImageWidth, (uint)width); + ifd.Long(TiffTags.ImageLength, (uint)height); + ifd.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)o.BitsPerSample, channels).ToArray()); + ifd.Short(TiffTags.Compression, (ushort)o.Compression); + ifd.Short(TiffTags.PhotometricInterpretation, channels == 1 ? (ushort)1 : (ushort)2); + ifd.Long(TiffTags.StripOffsets, offsets); + ifd.Short(TiffTags.SamplesPerPixel, (ushort)channels); + ifd.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip); + ifd.Long(TiffTags.StripByteCounts, counts); + ifd.Rational(TiffTags.XResolution, (72u, 1u)); + ifd.Rational(TiffTags.YResolution, (72u, 1u)); + ifd.Short(TiffTags.PlanarConfiguration, 1); + ifd.Short(TiffTags.ResolutionUnit, 2); + ifd.Ascii(TiffTags.Software, "Titano"); + if (predictor) ifd.Short(TiffTags.Predictor, 2); + if (channels == 4) ifd.Short(TiffTags.ExtraSamples, 2); + if (o.Exif is { } exif) ifd.AttachExif(exif); + WriteDirectory(output, start, ifd); + } + + /// Appends (and its children) and points the header at it. + internal static void WriteDirectory(Stream output, long start, TiffDirectory ifd) + { + var at = output.Position - start; + ifd.Layout(at); + var origin = new OffsetStream(output, start); + ifd.Write(origin); + var end = output.Position; + output.Position = start + 4; + Span pointer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(pointer, (uint)((at + 1) & ~1L)); + output.Write(pointer); + output.Position = end; + } + + internal static byte[] Deflate(byte[] raw, CompressionLevel level) + { + using var ms = new MemoryStream(raw.Length / 2 + 64); + using (var z = new ZLibStream(ms, level, leaveOpen: true)) z.Write(raw); + return ms.ToArray(); + } + + /// View of a stream whose Position is relative to the TIFF header (files may start mid-stream). + private sealed class OffsetStream(Stream inner, long origin) : Stream + { + public override bool CanRead => false; + public override bool CanSeek => true; + public override bool CanWrite => true; + public override long Length => inner.Length - origin; + + public override long Position + { + get => inner.Position - origin; + set => inner.Position = value + origin; + } + + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + public override void Write(ReadOnlySpan buffer) => inner.Write(buffer); + public override void WriteByte(byte value) => inner.WriteByte(value); + public override void Flush() => inner.Flush(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin seekOrigin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } +} diff --git a/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs b/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs new file mode 100644 index 00000000..d49c57c1 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/TiffTestEncoders.cs @@ -0,0 +1,127 @@ +using Titano.Core.Codecs.Tiff; +using Titano.Core.Metadata.Tiff; + +namespace Titano.Core.Tests.Codecs; + +/// Test-side encoders for TIFF compressions the product never writes (LZW, PackBits) and a raw TIFF builder. +internal static class TiffTestEncoders +{ + /// TIFF LZW; writes LSB-first codes switching width one code late (pre-6.0 libtiff). + public static byte[] Lzw(ReadOnlySpan data, bool oldStyle = false) + { + var output = new List(); + uint acc = 0; + var bits = 0; + var width = 9; + void Put(int code) + { + if (oldStyle) + { + acc |= (uint)code << bits; + bits += width; + while (bits >= 8) + { + output.Add((byte)acc); + acc >>= 8; + bits -= 8; + } + } + else + { + acc = acc << width | (uint)code; + bits += width; + while (bits >= 8) + { + output.Add((byte)(acc >> (bits - 8))); + bits -= 8; + } + } + } + var table = new Dictionary<(int, byte), int>(); + var next = 258; + Put(256); + if (data.Length == 0) + { + Put(257); + } + else + { + int current = data[0]; + for (var i = 1; i < data.Length; i++) + { + var c = data[i]; + if (table.TryGetValue((current, c), out var code)) + { + current = code; + continue; + } + Put(current); + table[(current, c)] = next++; + current = c; + if (next == 4094) + { + Put(256); + table.Clear(); + next = 258; + width = 9; + } + else if (next >= (1 << width) + (oldStyle ? 1 : 0)) + { + width++; + } + } + Put(current); + // libtiff's LZWPostEncode counts the final code too, so EOI uses the decoder's width. + if (++next >= (1 << width) + (oldStyle ? 1 : 0) && width < 12) width++; + Put(257); + } + if (bits > 0) output.Add(oldStyle ? (byte)acc : (byte)(acc << (8 - bits))); + return [.. output]; + } + + /// PackBits with both literal and replicate runs. + public static byte[] PackBits(ReadOnlySpan data) + { + var output = new List(); + var i = 0; + while (i < data.Length) + { + var run = 1; + while (i + run < data.Length && run < 128 && data[i + run] == data[i]) run++; + if (run >= 3) + { + output.Add((byte)(sbyte)(1 - run)); + output.Add(data[i]); + i += run; + continue; + } + var start = i; + while (i < data.Length && i - start < 128 && !(i + 2 < data.Length && data[i] == data[i + 1] && data[i] == data[i + 2])) i++; + output.Add((byte)(i - start - 1)); + for (var k = start; k < i; k++) output.Add(data[k]); + } + return [.. output]; + } + + /// Builds a little-endian TIFF from pre-encoded strips or tiles plus layout tags. + public static byte[] Build(Action tags, IReadOnlyList chunks, bool tiled) + { + using var ms = new MemoryStream(); + ms.Write("II*\0\0\0\0\0"u8); + var offsets = new uint[chunks.Count]; + var counts = new uint[chunks.Count]; + for (var i = 0; i < chunks.Count; i++) + { + offsets[i] = (uint)ms.Position; + counts[i] = (uint)chunks[i].Length; + ms.Write(chunks[i]); + if ((ms.Position & 1) != 0) ms.WriteByte(0); + } + var ifd = new TiffDirectory(); + tags(ifd); + ifd.Long(tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets, offsets); + ifd.Long(tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts, counts); + TiffWriter.WriteDirectory(ms, 0, ifd); + return ms.ToArray(); + } +} diff --git a/tests/Titano.Core.Tests/Codecs/TiffTests.cs b/tests/Titano.Core.Tests/Codecs/TiffTests.cs new file mode 100644 index 00000000..92777536 --- /dev/null +++ b/tests/Titano.Core.Tests/Codecs/TiffTests.cs @@ -0,0 +1,315 @@ +using System.Buffers.Binary; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Codecs.Tiff; +using Titano.Core.Imaging; +using Titano.Core.Metadata.Tiff; +using Titano.Testing; +using static Titano.Core.Tests.Codecs.CodecTestData; + +namespace Titano.Core.Tests.Codecs; + +public sealed class TiffTests(TestContext context) +{ + private static TiffRaster Raster(byte[] tiff, TiffDecodeOptions? options = null) + { + var reader = TiffReader.Open(new MemoryStream(tiff)) ?? throw new InvalidDataException("not a TIFF"); + return TiffImageReader.ReadRaster(reader, reader.ReadChain()[0], options); + } + + [Theory] + [Case("tiff/lzw-pred.tif")] + [Case("tiff/packbits.tif")] + [Case("tiff/none-strips.tif")] + [Case("tiff/lzw-tiled.tif")] + [Case("tiff/planar-zip.tif")] + public void EightBitLayoutsMatchSource(string name) + { + var raster = Raster(Fixture(name)); + Assert.Empty(raster.Warnings); + Assert.Equal(3, raster.SamplesPerPixel); + Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Words, raster.Samples!); + } + + [Test] + public void SixteenBitDeflatePredictorMatchesSource() + { + var raster = Raster(Fixture("tiff/deflate16-pred.tif")); + Assert.Equal(16, raster.BitsPerSample); + Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, raster.Samples!); + } + + [Test] + public void FloatingPointPredictorMatchesSource() + { + var raster = Raster(Fixture("tiff/float32-pred3.tif")); + Assert.Equal(TiffSampleFormat.Float, raster.SampleFormat); + var source = ReadPnm(Fixture("src16.ppm")).Samples; + for (var i = 0; i < source.Length; i++) Assert.Approximately(source[i] / 65535.0, raster.FloatSamples![i], 1e-6); + using var image = TiffImageReader.Decode(Fixture("tiff/float32-pred3.tif")); + Assert.Approximately(source[3 * 100 + 1] / 65535.0, image[1, 100 % 61, 100 / 61], 1e-6); + } + + [Theory] + [Case("tiff/jpeg-ycbcr")] + [Case("tiff/jpeg-rgb")] + public void JpegCompressedStripsMatchLibtiff(string name) + { + var raster = Raster(Fixture(name + ".tif")); + Assert.Equal(2, raster.Photometric); + Assert.Empty(raster.Warnings); + var diff = MaxAbsDiff(raster.Samples!.Select(s => (byte)s).ToArray(), ReadPnm(Fixture(name + ".ppm")).Samples); + context.Log($"{name}: max |diff| vs libtiff {diff}"); + Assert.LessOrEqual(diff, 2); + } + + [Test] + public void MinIsWhiteIsInverted() + { + // The raster keeps stored values; the image inverts them (0 = white), as libtiff readers do. + var file = Fixture("tiff/gray-miniswhite.tif"); + var raster = Raster(file); + Assert.Equal(0, raster.Photometric); + using var image = TiffImageReader.Decode(file); + Assert.Equal(1, image.Channels); + for (var i = 0; i < image.PlaneLength; i++) Assert.Equal(ColorSpace.Linear8((byte)(255 - raster.Samples![i])), image.Plane(0)[i]); + } + + [Theory] + [Case(false)] + [Case(true)] + public void LzwBothBitOrdersAndTableResets(bool oldStyle) + { + const int w = 70, h = 64; + var pixels = new byte[w * h * 3]; + new Random(3).NextBytes(pixels.AsSpan(0, pixels.Length / 2)); + for (var i = pixels.Length / 2; i < pixels.Length; i++) pixels[i] = (byte)(i / 50); + var strips = new List(); + for (var y = 0; y < h; y += 32) strips.Add(TiffTestEncoders.Lzw(pixels.AsSpan(y * w * 3, Math.Min(32, h - y) * w * 3), oldStyle)); + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 3, 8, compression: 5, rowsPerStrip: 32), strips, tiled: false); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.SequenceEqual(pixels.Select(b => (ushort)b), raster.Samples!); + } + + [Test] + public void PackBitsSixteenBitPlanarTiles() + { + const int w = 40, h = 24, tile = 16; + var samples = new ushort[w * h * 3]; + for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 7 == 0 ? 60000 : i * 13); + var chunks = new List(); + for (var plane = 0; plane < 3; plane++) + { + for (var ty = 0; ty < h; ty += tile) + { + for (var tx = 0; tx < w; tx += tile) + { + var raw = new byte[tile * tile * 2]; + for (var y = 0; y < tile; y++) + { + for (var x = 0; x < tile; x++) + { + var v = ty + y < h && tx + x < w ? samples[((ty + y) * w + tx + x) * 3 + plane] : (ushort)0; + BinaryPrimitives.WriteUInt16LittleEndian(raw.AsSpan((y * tile + x) * 2), v); + } + } + chunks.Add(TiffTestEncoders.PackBits(raw)); + } + } + } + var tiff = TiffTestEncoders.Build(d => + { + Layout(d, w, h, 3, 16, compression: 32773); + d.Short(TiffTags.PlanarConfiguration, 2); + d.Long(TiffTags.TileWidth, tile); + d.Long(TiffTags.TileLength, tile); + }, chunks, tiled: true); + Assert.SequenceEqual(samples, Raster(tiff).Samples!); + } + + [Test] + public void PackedTwelveBitSamplesUnpack() + { + const int w = 5, h = 3; + var values = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 273 % 4096)).ToArray(); + var stride = (w * 12 + 7) / 8; + var raw = new byte[stride * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + for (var b = 0; b < 12; b++) + { + if ((values[y * w + x] >> (11 - b) & 1) != 0) raw[y * stride + (x * 12 + b) / 8] |= (byte)(0x80 >> ((x * 12 + b) % 8)); + } + } + } + var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 12, compression: 1), [raw], tiled: false); + var raster = Raster(tiff); + Assert.Equal(12, raster.BitsPerSample); + Assert.SequenceEqual(values, raster.Samples!); + } + + [Test] + public void DngStyleLosslessTilesMapBackFromReshapedFrames() + { + // A CFA-like 1-sample tile of 32×8 stored as a 2-component, 16-wide lossless JPEG frame (as DNG writers do). + const int w = 48, h = 8, tile = 32; + var samples = Enumerable.Range(0, w * h).Select(i => (ushort)(i * 977 % 16384)).ToArray(); + var chunks = new List(); + for (var tx = 0; tx < w; tx += tile) + { + var t = new ushort[tile * h]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < tile; x++) t[y * tile + x] = tx + x < w ? samples[y * w + tx + x] : (ushort)0; + } + chunks.Add(JpegLosslessEncoder.Encode(t, tile / 2, h, 2, 14, predictor: 1)); + } + var tiff = TiffTestEncoders.Build(d => + { + Layout(d, w, h, 1, 16, compression: 7); + d.Short(TiffTags.PhotometricInterpretation, 32803); + d.Long(TiffTags.TileWidth, tile); + d.Long(TiffTags.TileLength, h); + }, chunks, tiled: true); + var raster = Raster(tiff); + Assert.Empty(raster.Warnings); + Assert.Equal(14, raster.BitsPerSample); + Assert.SequenceEqual(samples, raster.Samples!); + Assert.Throws(() => TiffImageReader.ToImageBuffer(raster)); + } + + [Theory] + [Case(8, 1, TiffCompression.None, false)] + [Case(8, 3, TiffCompression.Deflate, true)] + [Case(16, 3, TiffCompression.Deflate, true)] + [Case(16, 3, TiffCompression.Deflate, false)] + [Case(16, 4, TiffCompression.None, false)] + [Case(16, 1, TiffCompression.Deflate, true)] + public void WriterRoundTrips(int bits, int channels, TiffCompression compression, bool predictor) + { + const int w = 123, h = 77; + var samples = new ushort[w * h * channels]; + var rng = new Random(bits + channels); + for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i % 3 == 0 ? rng.Next(1 << bits) : (i / channels * 31) & ((1 << bits) - 1)); + var options = new TiffWriteOptions { BitsPerSample = bits, Compression = compression, Predictor = predictor }; + using var ms = new MemoryStream(); + TiffWriter.Write(ms, samples, w, h, channels, options); + var raster = Raster(ms.ToArray()); + Assert.Equal(channels, raster.SamplesPerPixel); + Assert.Equal(bits, raster.BitsPerSample); + Assert.SequenceEqual(samples, raster.Samples!); + } + + [Test] + public void ImageBufferRoundTripAndExifEmbedding() + { + using var image = new ImageBuffer(300, 1100); + for (var c = 0; c < 3; c++) + { + var plane = image.Plane(c); + for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 2) % 1000) / 999f; + } + var tiff = TiffWriter.Write(image, new TiffWriteOptions { Exif = ExifBlock() }); + using var back = TiffImageReader.Decode(tiff); + for (var i = 0; i < image.Data.Length; i += 101) Assert.Approximately(image.Data[i], back.Data[i], 2e-4); + AssertExif(tiff); + Assert.True(Raster(tiff).Warnings.Count == 0); + } + + [Theory] + [Case("tiff/lzw-pred.tif")] + [Case("tiff/lzw-tiled.tif")] + [Case("tiff/planar-zip.tif")] + [Case("tiff/jpeg-ycbcr.tif")] + [Case("tiff/float32-pred3.tif")] + public void FuzzedInputOnlyThrowsInvalidData(string name) + { + int ok = 0, rejected = 0; + var options = new TiffDecodeOptions { MaxSamples = 1 << 22 }; + foreach (var input in Corruptions(Fixture(name), 120, seed: name.Length * 31)) + { + try + { + using var image = TiffImageReader.Decode(input, options); + ok++; + } + catch (InvalidDataException) + { + rejected++; + } + } + context.Log($"{name}: {ok} decoded, {rejected} rejected"); + } + + internal static void Layout(TiffDirectory d, int w, int h, int spp, int bits, int compression, int rowsPerStrip = 0) + { + d.Long(TiffTags.ImageWidth, (uint)w); + d.Long(TiffTags.ImageLength, (uint)h); + d.Short(TiffTags.BitsPerSample, Enumerable.Repeat((ushort)bits, spp).ToArray()); + d.Short(TiffTags.Compression, (ushort)compression); + d.Short(TiffTags.PhotometricInterpretation, spp >= 3 ? (ushort)2 : (ushort)1); + d.Short(TiffTags.SamplesPerPixel, (ushort)spp); + if (rowsPerStrip > 0) d.Long(TiffTags.RowsPerStrip, (uint)rowsPerStrip); + } + + /// A big-endian Exif APP1 payload: IFD0 Make/Model/Orientation, Exif IFD (exposure, ISO, Interop), GPS IFD. + internal static byte[] ExifBlock() + { + var ms = new MemoryStream(); + var w = new BinaryWriter(ms); + void U16(int v) => w.Write(BinaryPrimitives.ReverseEndianness((ushort)v)); + void U32(uint v) => w.Write(BinaryPrimitives.ReverseEndianness(v)); + void Entry(int tag, int type, uint count, uint value) + { + U16(tag); + U16(type); + U32(count); + U32(value); + } + w.Write("Exif\0\0MM\0*"u8); + U32(8); + // IFD0 at 8: 5 entries → 2 + 60 + 4 = 66 bytes → data area at 74. + U16(5); + Entry(0x010F, 2, 6, 74); // Make "Canon\0" at 74 + Entry(0x0110, 2, 4, 0x45_4F_53_00); // Model "EOS\0" inline + Entry(0x0112, 3, 1, 6u << 16); // Orientation (not copied) + Entry(0x8769, 4, 1, 80); // Exif IFD at 80 + Entry(0x8825, 4, 1, 148); // GPS IFD at 148 + U32(0); + w.Write("Canon\0"u8); + // Exif IFD at 80: 3 entries → 2 + 36 + 4 = 42 → rational at 122. + U16(3); + Entry(0x829A, 5, 1, 122); // ExposureTime 1/250 + Entry(0x8827, 3, 1, 400u << 16); // ISO 400 + Entry(0xA005, 4, 1, 130); // Interop IFD at 130 + U32(0); + U32(1); + U32(250); + // Interop IFD at 130: 2 + 12 + 4 = 18 bytes → GPS IFD at 148. + U16(1); + Entry(0x0001, 2, 4, 0x52_39_38_00); // InteroperabilityIndex "R98" + U32(0); + U16(1); + Entry(0x0001, 2, 2, 0x4E_00_00_00); // GPSLatitudeRef "N" + U32(0); + return ms.ToArray(); + } + + internal static void AssertExif(byte[] file) + { + var reader = TiffReader.Open(new MemoryStream(file))!; + var ifd0 = reader.ReadChain()[0]; + Assert.Equal("Canon", reader.GetString(ifd0, TiffTags.Make)); + Assert.Equal("EOS", reader.GetString(ifd0, TiffTags.Model)); + Assert.False(ifd0.Has(TiffTags.Orientation) && reader.GetUInt(ifd0, TiffTags.Orientation) == 6, "orientation must not be copied"); + var exif = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.ExifIfd)!.Value)!; + Assert.Approximately(1 / 250.0, reader.GetDouble(exif, TiffTags.ExposureTime)!.Value, 1e-9); + Assert.Equal(400u, reader.GetUInt(exif, TiffTags.IsoSpeedRatings)); + var interop = reader.ReadIfd(reader.GetUInt(exif, TiffTags.InteropIfd)!.Value)!; + Assert.Equal("R98", reader.GetString(interop, 0x0001)); + var gps = reader.ReadIfd(reader.GetUInt(ifd0, TiffTags.GpsIfd)!.Value)!; + Assert.Equal("N", reader.GetString(gps, TiffTags.GpsLatitudeRef)); + } +} diff --git a/tests/fixtures/codecs/make-fixtures.sh b/tests/fixtures/codecs/make-fixtures.sh index a2aea85c..f499e9f5 100755 --- a/tests/fixtures/codecs/make-fixtures.sh +++ b/tests/fixtures/codecs/make-fixtures.sh @@ -70,6 +70,7 @@ convert src16.ppm -depth 16 -compress Zip -define tiff:predictor=2 tiff/deflate1 convert src.ppm -compress LZW -define tiff:tile-geometry=16x16 tiff/lzw-tiled.tif tiffcp -p separate -c zip src.ppm.tmp.tif tiff/planar-zip.tif 2>/dev/null || { convert src.ppm -compress None tiff/_tmp.tif; tiffcp -p separate -c zip tiff/_tmp.tif tiff/planar-zip.tif; rm tiff/_tmp.tif; } convert src.ppm -compress None tiff/_tmp.tif && tiffcp -c jpeg:90 -r 16 tiff/_tmp.tif tiff/jpeg-ycbcr.tif && tiffcp -c jpeg:r:90 -r 16 tiff/_tmp.tif tiff/jpeg-rgb.tif && rm tiff/_tmp.tif +convert tiff/jpeg-ycbcr.tif tiff/jpeg-ycbcr.ppm && convert tiff/jpeg-rgb.tif tiff/jpeg-rgb.ppm convert src16.ppm -define quantum:format=floating-point -depth 32 -compress Zip -define tiff:predictor=3 tiff/float32-pred3.tif convert src.ppm -colorspace Gray -define tiff:photometric=min-is-white -compress None tiff/gray-miniswhite.tif ls -l jpeg png tiff diff --git a/tests/fixtures/codecs/tiff/jpeg-rgb.ppm b/tests/fixtures/codecs/tiff/jpeg-rgb.ppm new file mode 100644 index 0000000000000000000000000000000000000000..78d88fd00bfdf91f839f049ac658ee8642675c61 GIT binary patch literal 8248 zcmeHpi&qp^w*IN^20?{LK|kuz4;l&-RDuLc1r-&Qw4kD*p%qkOP%*7h5{Y7B=Z2X$ z8L~zpOeBdW*a=BAq65*+gcuSr_M@sFDBKBYQTkQY-Owmzf{r-Utz>>{{c_j3_Yb&h z&FQnw+I_0_sqcK}JA3c7b0^QuR6UhFc}{lrWB_p@XgnGki-GRPK_g-)ghGA=YAb=xl|rrMP)h}Lx)N%xf|~Y0$E%_G z8t7OpRHuiI)&Ol|YQ0ZByqzx+WfC`OJK_`^o1?63X za?B7(Ls?EJqYp~!hf)S0wHs0}5E6pKBT(EZ6f*`zjYGl-2m&xCg2$ubu^9M%96Tb1 zLn!Q5z#cU`kOKFo!@U`>GYh6k*qjS@=fPe1aAyH*EP~sM;kFX^Tq)dI4!2amrz_#+ zD!6GMe7qX2uYr%%!gYH1XdQgy7+g~iSD%3QHo;ZRaOEku;tX8Y3YVUROWNS#4!F<= z7j(k;U2xttIL8c=G@RvxGy34PemG?SR=Z&Z10x|=JOam!!ZBlT)Hp1hfFVF|B4Rw6 z7>gn9#}Ol9B7_ot1>sQ>11Us*I?nBnM2(_C~Fa#1J#3Mx9C=oM8M2!=| z2?7EnCnCqA$*~ynejGU>CPOIcSCAexIgmp3r<1)Iq%(`8Nz$B4cIS~@`DAASX)Ge! zi^;YU@?0s|T28i9kf$rj<|?vjA9=i*tgj)D)sl63@@O4-O`)=HM1B}>}K;tsOVNEURG`CVk*H8RIc@?Xkwk{NwuT0faGK&suOf+3L*DIOu? zM#-2lGHRR@PLL4La3alkv}PpaIbEq~uF^E^(;TnX)YoW^)oSYWnxl1^BgZr~ z^_uDvn!Q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N}dZkNsC%Rn*nym!*<1)@zl=$j`^{{;o7v#9_8 literal 0 HcmV?d00001 diff --git a/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm b/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm new file mode 100644 index 0000000000000000000000000000000000000000..16a511195d4d3bfb7855f3f6748ef6a028815e37 GIT binary patch literal 8248 zcmXY!byQS~|Fw?-CKAKsnPh@)n4mjm=u%(+K~b(!Vjzg5q)4M;p;9IWC}3T$O(=>= z*VLJ!&FhUX?{I(bT6@i!KcBPb`RubMfU${TPO_qJvY^v90V>}Cm2ZkDsVr?$o>Ns4 z!HXdQBV9c)?|CQ??HD{Wa& z+VE9L`G*qlrxLJ6^DkxCul2A$H^aWEYc3%)=Ri#<0VW`8PU^sh4K+WS!Uilgdsv#U z?KECFX+Cq-dgKQ09=~fjJ=e5)S1#1&t~$Sa&>nizIs<6!p|qRf)Yk3P z#vQbVU9=0kX=nE8oJ`TFJg8H8M5iD}CpTXwqgXffglazxJgtKh(XdhqI8VWRAtS$& z)qhde|4Uu7LIc*(e{Q7z*v$B*PG3S;EuiT#0v*z3@Tv3(UB-wJW5|s8!HV9`V)WQD zUOO_MxiOx2GP=DP_x+i7gIR4`Sy#hZm!qsN#9E)-ZGCDlvo?iUafnrNgjtZyJeJQq zTEse7#!9Yc{dStU>%3Kbqt(t9I`J1w_8!yq9x?R(Y{GeO$$87<^gD1~daxgQdv*A*+x0~V2Q8Iiqq zkuN+Wy8XgC{KDJ)xwiu&Z-hj*Zrgq-GWyKU=(;^ol_}g4hqxu_+~Tb8!kmbr{P1H% z5!t2O^h$1O9d~bi_}&ZQyBot}S|cK^b3@v=zU^Gk2VCc85!SE6S$$jW2e#UN2(ujI z8h++dMqJ)nUi-Iu?LQ>429wN(k_|`p(I)nhcqv3EnIKKVFC<}> zl3+iQH~hH|_$L)mKDx3#Yh`oxzv@{(w6d4b*>m`8iFS^VnmwbNJz< z@^bTXvrDp%mgl5Z=j}b2A6K8Z{X%Z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