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 00000000..78d88fd0
Binary files /dev/null and b/tests/fixtures/codecs/tiff/jpeg-rgb.ppm differ
diff --git a/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm b/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm
new file mode 100644
index 00000000..16a51119
Binary files /dev/null and b/tests/fixtures/codecs/tiff/jpeg-ycbcr.ppm differ