diff --git a/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs b/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs
new file mode 100644
index 00000000..8e112346
--- /dev/null
+++ b/src/Titano.Core/Codecs/Dng/LinearDngWriter.cs
@@ -0,0 +1,155 @@
+using System.Buffers.Binary;
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Codecs.Tiff;
+using Titano.Core.Imaging;
+using Titano.Core.Metadata.Tiff;
+
+namespace Titano.Core.Codecs.Dng;
+
+/// Tile compression of a linear DNG.
+public enum DngCompression
+{
+ Uncompressed = 1,
+
+ /// Lossless JPEG (SOF3, predictor 1) per tile, DNG Compression = 7.
+ LosslessJpeg = 7,
+}
+
+/// Options for .
+public sealed record LinearDngOptions
+{
+ public static LinearDngOptions Default { get; } = new();
+
+ public DngCompression Compression { get; init; } = DngCompression.LosslessJpeg;
+
+ /// UniqueCameraModel (and Model): raw editors key their profiles on it.
+ public string UniqueCameraModel { get; init; } = "Titano";
+
+ /// TIFF-structured Exif block (JPEG APP1 payload) whose capture metadata is embedded.
+ public byte[]? Exif { get; init; }
+
+ /// Tile edge in pixels (multiple of 16).
+ public int TileSize { get; init; } = 256;
+
+ /// Worker limit for tile encoding (-1 = all cores).
+ public int MaxDegreeOfParallelism { get; init; } = -1;
+}
+
+///
+/// Writes linear Rec.709/sRGB-primaries RGB as a 16-bit LinearRaw DNG 1.4 that raw editors render with correct
+/// colours: ColorMatrix1 = XYZ(D65) → linear sRGB, ForwardMatrix1 = linear sRGB → XYZ(D50), illuminant D65,
+/// AsShotNeutral 1/1/1, WhiteLevel 65535, BaselineExposure 0. Values above 1.0 are clipped.
+///
+public static class LinearDngWriter
+{
+ /// XYZ (D65) → linear sRGB, i.e. the inverse of the sRGB → XYZ matrix (IEC 61966-2-1).
+ internal static readonly double[] XyzToLinearSrgb =
+ [
+ 3.2404542, -1.5371385, -0.4985314,
+ -0.9692660, 1.8760108, 0.0415560,
+ 0.0556434, -0.2040259, 1.0572252,
+ ];
+
+ /// Linear sRGB → XYZ (D50), Bradford-adapted: neutral (1,1,1) maps to the D50 white point.
+ internal static readonly double[] LinearSrgbToXyzD50 =
+ [
+ 0.4360747, 0.3850649, 0.1430804,
+ 0.2225045, 0.7168786, 0.0606169,
+ 0.0139322, 0.0971045, 0.7141733,
+ ];
+
+ public static byte[] Write(ImageBuffer image, LinearDngOptions? options = null)
+ {
+ using var ms = new MemoryStream();
+ Write(ms, image, options);
+ return ms.ToArray();
+ }
+
+ /// Writes a linear-light buffer (gray is stored as neutral RGB; alpha is dropped).
+ public static void Write(Stream output, ImageBuffer image, LinearDngOptions? options = null)
+ {
+ var o = options ?? LinearDngOptions.Default;
+ if (o.TileSize is < 16 or > 4096 || o.TileSize % 16 != 0) throw new ArgumentOutOfRangeException(nameof(options), "Tile size must be a multiple of 16 in 16..4096");
+ if (!output.CanSeek)
+ {
+ using var buffer = new MemoryStream();
+ Write(buffer, image, o);
+ buffer.Position = 0;
+ buffer.CopyTo(output);
+ return;
+ }
+ int w = image.Width, h = image.Height, t = o.TileSize;
+ int across = (w + t - 1) / t, down = (h + t - 1) / t;
+ var offsets = new uint[across * down];
+ var counts = new uint[across * down];
+ var start = output.Position;
+ output.Write("II*\0\0\0\0\0"u8);
+ var parallel = new ParallelOptions { MaxDegreeOfParallelism = o.MaxDegreeOfParallelism };
+ var band = new ushort[w * t * 3];
+ var tiles = new byte[across][];
+ for (var ty = 0; ty < down; ty++)
+ {
+ var y0 = ty * t;
+ var rows = Math.Min(t, h - y0);
+ Parallel.For(0, rows, parallel, r => PixelConvert.EncodeRow16(image, y0 + r, band.AsSpan(r * w * 3, w * 3), 3, TransferFunction.Linear));
+ Parallel.For(0, across, parallel, tx => tiles[tx] = EncodeTile(band, w, rows, tx * t, t, o.Compression));
+ for (var tx = 0; tx < across; tx++)
+ {
+ if (output.Position - start > uint.MaxValue - (long)tiles[tx].Length) throw new InvalidOperationException("DNG exceeds 4 GB");
+ offsets[ty * across + tx] = (uint)(output.Position - start);
+ counts[ty * across + tx] = (uint)tiles[tx].Length;
+ output.Write(tiles[tx]);
+ }
+ }
+
+ var ifd = new TiffDirectory();
+ // Capture metadata first, so the source camera's Make/Model win; UniqueCameraModel still keys the profile.
+ if (o.Exif is { } exif) ifd.AttachExif(exif);
+ if (!ifd.Has(TiffTags.Make)) ifd.Ascii(TiffTags.Make, "Titano");
+ if (!ifd.Has(TiffTags.Model)) ifd.Ascii(TiffTags.Model, o.UniqueCameraModel);
+ ifd.Long(TiffTags.NewSubfileType, 0);
+ ifd.Long(TiffTags.ImageWidth, (uint)w);
+ ifd.Long(TiffTags.ImageLength, (uint)h);
+ ifd.Short(TiffTags.BitsPerSample, 16, 16, 16);
+ ifd.Short(TiffTags.Compression, (ushort)o.Compression);
+ ifd.Short(TiffTags.PhotometricInterpretation, 34892);
+ ifd.Short(TiffTags.Orientation, 1);
+ ifd.Short(TiffTags.SamplesPerPixel, 3);
+ ifd.Short(TiffTags.PlanarConfiguration, 1);
+ ifd.Ascii(TiffTags.Software, "Titano");
+ ifd.Long(TiffTags.TileWidth, (uint)t);
+ ifd.Long(TiffTags.TileLength, (uint)t);
+ ifd.Long(TiffTags.TileOffsets, offsets);
+ ifd.Long(TiffTags.TileByteCounts, counts);
+ ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0);
+ ifd.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0);
+ ifd.Ascii(TiffTags.UniqueCameraModel, o.UniqueCameraModel);
+ ifd.SRational(TiffTags.ColorMatrix1, Rationals(XyzToLinearSrgb));
+ ifd.SRational(TiffTags.ForwardMatrix1, Rationals(LinearSrgbToXyzD50));
+ ifd.Short(TiffTags.CalibrationIlluminant1, 21); // D65
+ ifd.Rational(TiffTags.AsShotNeutral, (1u, 1u), (1u, 1u), (1u, 1u));
+ ifd.SRational(TiffTags.BaselineExposure, (0, 1));
+ ifd.Long(TiffTags.WhiteLevel, 65535, 65535, 65535);
+ TiffWriter.WriteDirectory(output, start, ifd);
+ }
+
+ /// One t×t tile from a band of rows; pixels beyond the image repeat the edge (better compression).
+ private static byte[] EncodeTile(ushort[] band, int width, int rows, int x0, int t, DngCompression compression)
+ {
+ var tile = new ushort[t * t * 3];
+ for (var y = 0; y < t; y++)
+ {
+ var src = band.AsSpan(Math.Min(y, rows - 1) * width * 3, width * 3);
+ var dst = tile.AsSpan(y * t * 3, t * 3);
+ var valid = Math.Min(t, width - x0);
+ src.Slice(x0 * 3, valid * 3).CopyTo(dst);
+ for (var x = valid; x < t; x++) src.Slice((width - 1) * 3, 3).CopyTo(dst[(x * 3)..]);
+ }
+ if (compression == DngCompression.LosslessJpeg) return JpegLosslessEncoder.Encode(tile, t, t, 3, 16);
+ var bytes = new byte[tile.Length * 2];
+ for (var i = 0; i < tile.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), tile[i]);
+ return bytes;
+ }
+
+ private static (int, int)[] Rationals(double[] matrix) => matrix.Select(v => ((int)Math.Round(v * 10000), 10000)).ToArray();
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs
new file mode 100644
index 00000000..63afe5c9
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegDecoder.cs
@@ -0,0 +1,83 @@
+using Titano.Core.Imaging;
+
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Managed JPEG decoder: baseline, extended (12-bit), progressive and lossless Huffman streams; 1, 3 or 4 components
+/// (CMYK/YCCK via Adobe APP14); any integral sampling factors; restart intervals with resynchronisation on corrupt
+/// data; DCT-domain scaling for thumbnails. Exif orientation is not applied. Malformed headers throw
+/// ; damaged entropy-coded data yields a partial image plus warnings.
+///
+public static class JpegDecoder
+{
+ private static readonly float[]?[] LinearLuts = new float[17][];
+
+ /// Reads the frame header only (no pixel decoding).
+ public static JpegInfo ReadInfo(ReadOnlySpan data)
+ {
+ var parser = new JpegParser(JpegDecodeOptions.Default);
+ parser.Parse(data, headerOnly: true);
+ return parser.Info();
+ }
+
+ /// Decodes to interleaved gray or RGB samples (8-bit, or 16-bit containers for higher precisions).
+ public static JpegImage Decode(ReadOnlySpan data, JpegDecodeOptions? options = null)
+ {
+ var parser = Parse(data, options);
+ if (parser.Frame!.Process == JpegProcess.Lossless) return LosslessToImage(parser);
+ return new JpegRenderer(parser).RenderInterleaved(parser.Info());
+ }
+
+ /// Decodes into a linear-light (samples are taken as sRGB-encoded).
+ /// Return gray images as three identical channels instead of one.
+ public static ImageBuffer DecodeToLinear(ReadOnlySpan data, JpegDecodeOptions? options = null, bool expandGray = false)
+ {
+ var parser = Parse(data, options);
+ if (parser.Frame!.Process == JpegProcess.Lossless)
+ {
+ var image = LosslessToImage(parser);
+ var channels = image.Components == 1 && expandGray ? 3 : image.Components;
+ return image.Pixels8 is { } p8
+ ? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Components, outputChannels: channels)
+ : PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Components, maxValue: (1 << image.BitDepth) - 1, outputChannels: channels);
+ }
+ 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);
+ parser.Parse(data);
+ return parser;
+ }
+
+ private static JpegImage LosslessToImage(JpegParser parser)
+ {
+ var raw = JpegLosslessDecoder.Finish(parser);
+ if (raw.Components is not (1 or 3)) throw new InvalidDataException($"JPEG: {raw.Components}-component lossless images have no colour interpretation");
+ if (raw.Precision > 8)
+ return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, raw.Precision, null, raw.Samples, [.. parser.Warnings]);
+ var bytes = new byte[raw.Samples.Length];
+ for (var i = 0; i < bytes.Length; i++) bytes[i] = (byte)raw.Samples[i];
+ return new JpegImage(parser.Info(), raw.Width, raw.Height, raw.Components, 8, bytes, null, [.. parser.Warnings]);
+ }
+
+ /// sRGB-decoding table for codes 0..2^precision−1.
+ internal static float[] LinearLut(int precision)
+ {
+ if (LinearLuts[precision] is { } cached) return cached;
+ var size = 1 << precision;
+ var lut = new float[size];
+ for (var i = 0; i < size; i++) lut[i] = (float)ColorSpace.SrgbToLinear(i / (double)(size - 1));
+ return LinearLuts[precision] = lut;
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs
new file mode 100644
index 00000000..e65fb43a
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegEncoder.cs
@@ -0,0 +1,477 @@
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
+using Titano.Core.Imaging;
+
+namespace Titano.Core.Codecs.Jpeg;
+
+/// Chroma subsampling written by .
+public enum JpegSubsampling
+{
+ Yuv444,
+ Yuv422,
+ Yuv420,
+}
+
+/// Options for .
+public sealed record JpegEncodeOptions
+{
+ public static JpegEncodeOptions Default { get; } = new();
+
+ /// IJG quality 1–100 (scales the Annex K tables).
+ public int Quality { get; init; } = 90;
+
+ public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Yuv420;
+
+ /// Two-pass encoding with Huffman tables built from the image's statistics (smaller files).
+ public bool OptimizeHuffman { get; init; }
+
+ /// Restart interval in MCUs (0 = none).
+ public int RestartInterval { get; init; }
+
+ /// APP1 payloads written after SOI, each including its identifier (e.g. "Exif\0\0" + TIFF, or the XMP
+ /// namespace + packet); at most 65533 bytes each. When present the JFIF APP0 segment is omitted (Exif layout).
+ public IReadOnlyList? App1Segments { get; init; }
+
+ /// Ordered dither when quantising linear float input to 8-bit sRGB.
+ public bool Dither { get; init; }
+
+ /// Worker limit for colour conversion and forward DCT (-1 = all cores).
+ public int MaxDegreeOfParallelism { get; init; } = -1;
+}
+
+///
+/// Baseline JPEG encoder (8-bit, Huffman, 1 or 3 components). Colour conversion and float forward DCT run in
+/// parallel per MCU row; entropy coding is sequential.
+///
+public static class JpegEncoder
+{
+ private static readonly float[] BasisT = Transpose(JpegTables.Basis);
+
+ /// Encodes a linear-light buffer (1 channel → gray JPEG, 3/4 → YCbCr; alpha is dropped).
+ public static byte[] Encode(ImageBuffer image, JpegEncodeOptions? options = null)
+ {
+ using var ms = new MemoryStream();
+ Encode(ms, image, options);
+ return ms.ToArray();
+ }
+
+ public static void Encode(Stream output, ImageBuffer image, JpegEncodeOptions? options = null)
+ {
+ var o = options ?? JpegEncodeOptions.Default;
+ var channels = image.Channels == 1 ? 1 : 3;
+ EncodeCore(output, image.Width, image.Height, channels, (y, row) => PixelConvert.EncodeRow8(image, y, row, channels, TransferFunction.Srgb, o.Dither), o);
+ }
+
+ /// Encodes interleaved 8-bit sRGB pixels: 1 = gray, 3 = RGB, 4 = RGBA (alpha ignored).
+ public static byte[] Encode(ReadOnlySpan pixels, int width, int height, int channels, JpegEncodeOptions? options = null)
+ {
+ using var ms = new MemoryStream();
+ Encode(ms, pixels, width, height, channels, options);
+ return ms.ToArray();
+ }
+
+ public static unsafe void Encode(Stream output, ReadOnlySpan pixels, int width, int height, int channels, JpegEncodeOptions? options = null)
+ {
+ if (channels is not (1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(channels));
+ if (pixels.Length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small", nameof(pixels));
+ var outChannels = channels == 1 ? 1 : 3;
+ fixed (byte* p = pixels)
+ {
+ var ptr = (nint)p;
+ EncodeCore(output, width, height, outChannels, (y, row) =>
+ {
+ var src = new ReadOnlySpan((byte*)ptr + (long)y * width * channels, width * channels);
+ if (channels == outChannels)
+ {
+ src.CopyTo(row);
+ return;
+ }
+ for (var x = 0; x < width; x++)
+ {
+ row[3 * x] = src[4 * x];
+ row[3 * x + 1] = src[4 * x + 1];
+ row[3 * x + 2] = src[4 * x + 2];
+ }
+ }, options ?? JpegEncodeOptions.Default);
+ }
+ }
+
+ /// IJG quality scaling of a base table (jcparam.c), clamped to baseline 1..255.
+ internal static int[] ScaleTable(ReadOnlySpan table, int quality)
+ {
+ quality = Math.Clamp(quality, 1, 100);
+ var scale = quality < 50 ? 5000 / quality : 200 - quality * 2;
+ var result = new int[64];
+ for (var i = 0; i < 64; i++) result[i] = Math.Clamp((table[i] * scale + 50) / 100, 1, 255);
+ return result;
+ }
+
+ private delegate void RowReader(int y, Span row);
+
+ private sealed class Plan
+ {
+ public required int Width, Height, Components, HY, VY, McusX, McusY;
+ public required int[][] Quant;
+ public required short[][] Coefficients;
+
+ public int BlocksPerLine(int c) => c == 0 ? McusX * HY : McusX;
+ }
+
+ private static void EncodeCore(Stream output, int width, int height, int components, RowReader read, JpegEncodeOptions o)
+ {
+ if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width), "JPEG dimensions are 1..65535");
+ if (o.RestartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(o), "Restart interval is 0..65535");
+ var (hy, vy) = components == 1 ? (1, 1) : o.Subsampling switch
+ {
+ JpegSubsampling.Yuv444 => (1, 1),
+ JpegSubsampling.Yuv422 => (2, 1),
+ _ => (2, 2),
+ };
+ var mcusX = JpegParser.DivUp(width, 8 * hy);
+ var mcusY = JpegParser.DivUp(height, 8 * vy);
+ var plan = new Plan
+ {
+ Width = width, Height = height, Components = components, HY = hy, VY = vy, McusX = mcusX, McusY = mcusY,
+ Quant = [ScaleTable(JpegTables.LumaQuant, o.Quality), ScaleTable(JpegTables.ChromaQuant, o.Quality)],
+ Coefficients = new short[components][],
+ };
+ plan.Coefficients[0] = new short[checked(mcusX * hy * mcusY * vy * 64)];
+ for (var c = 1; c < components; c++) plan.Coefficients[c] = new short[checked(mcusX * mcusY * 64)];
+
+ Transform(plan, read, o.MaxDegreeOfParallelism);
+
+ JpegHuffmanCode dcY, acY, dcC, acC;
+ if (o.OptimizeHuffman)
+ {
+ var freq = new long[4][];
+ for (var i = 0; i < 4; i++) freq[i] = new long[256];
+ Entropy(plan, o.RestartInterval, null, freq, null);
+ dcY = JpegHuffmanCode.Optimal(freq[0]);
+ acY = JpegHuffmanCode.Optimal(freq[1]);
+ dcC = components > 1 ? JpegHuffmanCode.Optimal(freq[2]) : dcY;
+ acC = components > 1 ? JpegHuffmanCode.Optimal(freq[3]) : acY;
+ }
+ else
+ {
+ dcY = new JpegHuffmanCode(JpegTables.DcLumaBits, JpegTables.DcLumaValues);
+ acY = new JpegHuffmanCode(JpegTables.AcLumaBits, JpegTables.AcLumaValues);
+ dcC = new JpegHuffmanCode(JpegTables.DcChromaBits, JpegTables.DcChromaValues);
+ acC = new JpegHuffmanCode(JpegTables.AcChromaBits, JpegTables.AcChromaValues);
+ }
+
+ var writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components / 4));
+ Entropy(plan, o.RestartInterval, writer, null, [dcY, acY, dcC, acC]);
+ WriteHeaders(output, plan, o, dcY, acY, dcC, acC);
+ output.Write(writer.Written);
+ output.Write([0xFF, JpegTables.Eoi]);
+ }
+
+ /// Colour conversion, chroma downsampling (box average), forward DCT and quantisation per MCU row.
+ private static void Transform(Plan p, RowReader read, int parallelism)
+ {
+ int hy = p.HY, vy = p.VY, mcuH = 8 * vy, paddedW = p.McusX * 8 * hy, nc = p.Components;
+ var recip = new float[2][];
+ for (var t = 0; t < 2; t++)
+ {
+ recip[t] = new float[64];
+ for (var i = 0; i < 64; i++) recip[t][i] = 1f / p.Quant[t][i];
+ }
+ Parallel.For(0, p.McusY, new ParallelOptions { MaxDegreeOfParallelism = parallelism }, my =>
+ {
+ var rgb = new byte[p.Width * nc];
+ var planes = new float[nc][];
+ for (var c = 0; c < nc; c++) planes[c] = new float[paddedW * mcuH];
+ for (var r = 0; r < mcuH; r++)
+ {
+ var y = Math.Min(my * mcuH + r, p.Height - 1);
+ read(y, rgb);
+ var row = r * paddedW;
+ if (nc == 1)
+ {
+ var g = planes[0];
+ for (var x = 0; x < p.Width; x++) g[row + x] = rgb[x] - 128f;
+ }
+ else
+ {
+ float[] yp = planes[0], cb = planes[1], cr = planes[2];
+ for (var x = 0; x < p.Width; x++)
+ {
+ float rr = rgb[3 * x], gg = rgb[3 * x + 1], bb = rgb[3 * x + 2];
+ yp[row + x] = 0.299f * rr + 0.587f * gg + 0.114f * bb - 128f;
+ cb[row + x] = -0.168736f * rr - 0.331264f * gg + 0.5f * bb;
+ cr[row + x] = 0.5f * rr - 0.418688f * gg - 0.081312f * bb;
+ }
+ }
+ for (var c = 0; c < nc; c++)
+ {
+ var plane = planes[c];
+ plane.AsSpan(row + p.Width, paddedW - p.Width).Fill(plane[row + p.Width - 1]);
+ }
+ }
+
+ Span block = stackalloc float[64];
+ Span coef = stackalloc float[64];
+ var bpl = p.BlocksPerLine(0);
+ for (var by = 0; by < vy; by++)
+ {
+ for (var bx = 0; bx < bpl; bx++)
+ {
+ for (var r = 0; r < 8; r++) planes[0].AsSpan((by * 8 + r) * paddedW + bx * 8, 8).CopyTo(block.Slice(r * 8, 8));
+ ForwardDct(block, coef);
+ Quantize(coef, recip[0], p.Coefficients[0].AsSpan(((my * vy + by) * bpl + bx) * 64, 64));
+ }
+ }
+ var area = 1f / (hy * vy);
+ for (var c = 1; c < nc; c++)
+ {
+ var plane = planes[c];
+ for (var bx = 0; bx < p.McusX; bx++)
+ {
+ for (var r = 0; r < 8; r++)
+ {
+ for (var i = 0; i < 8; i++)
+ {
+ var sum = 0f;
+ var x0 = (bx * 8 + i) * hy;
+ for (var dy = 0; dy < vy; dy++)
+ {
+ var at = (r * vy + dy) * paddedW + x0;
+ for (var dx = 0; dx < hy; dx++) sum += plane[at + dx];
+ }
+ block[r * 8 + i] = sum * area;
+ }
+ }
+ ForwardDct(block, coef);
+ Quantize(coef, recip[1], p.Coefficients[c].AsSpan((my * p.McusX + bx) * 64, 64));
+ }
+ }
+ });
+ }
+
+ /// F = B·f·Bᵀ with the orthonormal basis (DC = 8 × mean), Vector256 rows when available.
+ private static void ForwardDct(ReadOnlySpan f, Span output)
+ {
+ var basis = JpegTables.Basis;
+ if (Vector256.IsHardwareAccelerated)
+ {
+ ref var bt = ref MemoryMarshal.GetArrayDataReference(BasisT);
+ Span> t = stackalloc Vector256[8];
+ for (var y = 0; y < 8; y++)
+ {
+ var acc = Vector256.Zero;
+ for (var x = 0; x < 8; x++) acc += Vector256.Create(f[y * 8 + x]) * Vector256.LoadUnsafe(ref bt, (nuint)(x * 8));
+ t[y] = acc;
+ }
+ for (var v = 0; v < 8; v++)
+ {
+ var acc = Vector256.Zero;
+ for (var y = 0; y < 8; y++) acc += Vector256.Create(basis[v * 8 + y]) * t[y];
+ acc.CopyTo(output.Slice(v * 8, 8));
+ }
+ return;
+ }
+ Span tmp = stackalloc float[64];
+ for (var y = 0; y < 8; y++)
+ {
+ for (var u = 0; u < 8; u++)
+ {
+ var s = 0f;
+ for (var x = 0; x < 8; x++) s += f[y * 8 + x] * basis[u * 8 + x];
+ tmp[y * 8 + u] = s;
+ }
+ }
+ for (var v = 0; v < 8; v++)
+ {
+ for (var u = 0; u < 8; u++)
+ {
+ var s = 0f;
+ for (var y = 0; y < 8; y++) s += basis[v * 8 + y] * tmp[y * 8 + u];
+ output[v * 8 + u] = s;
+ }
+ }
+ }
+
+ private static void Quantize(ReadOnlySpan coef, float[] recip, Span destination)
+ {
+ destination[0] = (short)Math.Clamp(MathF.Round(coef[0] * recip[0]), -1024f, 1023f);
+ for (var i = 1; i < 64; i++) destination[i] = (short)Math.Clamp(MathF.Round(coef[i] * recip[i]), -1023f, 1023f);
+ }
+
+ /// Walks every MCU in order: counts symbol frequencies () or emits codes.
+ private static void Entropy(Plan p, int restartInterval, JpegBitWriter? writer, long[][]? freq, JpegHuffmanCode[]? codes)
+ {
+ var preds = new int[p.Components];
+ var total = p.McusX * p.McusY;
+ var rst = 0;
+ for (var mcu = 0; mcu < total; mcu++)
+ {
+ if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0)
+ {
+ Array.Clear(preds);
+ if (writer is not null)
+ {
+ writer.Flush();
+ writer.WriteMarker((byte)(JpegTables.Rst0 + rst));
+ }
+ rst = (rst + 1) & 7;
+ }
+ writer?.Reserve(4096);
+ int mx = mcu % p.McusX, my = mcu / p.McusX;
+ for (var c = 0; c < p.Components; c++)
+ {
+ int h = c == 0 ? p.HY : 1, v = c == 0 ? p.VY : 1, bpl = p.BlocksPerLine(c), table = c == 0 ? 0 : 2;
+ for (var by = 0; by < v; by++)
+ {
+ for (var bx = 0; bx < h; bx++)
+ {
+ var block = p.Coefficients[c].AsSpan(((my * v + by) * bpl + mx * h + bx) * 64, 64);
+ if (writer is null) CountBlock(block, ref preds[c], freq![table], freq[table + 1]);
+ else EncodeBlock(writer, block, ref preds[c], codes![table], codes[table + 1]);
+ }
+ }
+ }
+ }
+ writer?.Flush();
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static int Category(int v) => v == 0 ? 0 : 32 - BitOperations.LeadingZeroCount((uint)Math.Abs(v));
+
+ private static void CountBlock(ReadOnlySpan block, ref int pred, long[] dc, long[] ac)
+ {
+ dc[Category(block[0] - pred)]++;
+ pred = block[0];
+ var run = 0;
+ var order = JpegTables.NaturalOrder;
+ for (var k = 1; k < 64; k++)
+ {
+ int v = block[order[k]];
+ if (v == 0)
+ {
+ run++;
+ continue;
+ }
+ for (; run >= 16; run -= 16) ac[0xF0]++;
+ ac[run << 4 | Category(v)]++;
+ run = 0;
+ }
+ if (run > 0) ac[0]++;
+ }
+
+ private static void EncodeBlock(JpegBitWriter w, ReadOnlySpan block, ref int pred, JpegHuffmanCode dc, JpegHuffmanCode ac)
+ {
+ var diff = block[0] - pred;
+ pred = block[0];
+ var s = Category(diff);
+ w.Write((uint)(dc.Code[s] << s | ((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1))), dc.Length[s] + s);
+ var run = 0;
+ var order = JpegTables.NaturalOrder;
+ for (var k = 1; k < 64; k++)
+ {
+ int v = block[order[k]];
+ if (v == 0)
+ {
+ run++;
+ continue;
+ }
+ for (; run >= 16; run -= 16) w.Write(ac.Code[0xF0], ac.Length[0xF0]);
+ s = Category(v);
+ var symbol = run << 4 | s;
+ w.Write((uint)(ac.Code[symbol] << s | ((v < 0 ? v - 1 : v) & ((1 << s) - 1))), ac.Length[symbol] + s);
+ run = 0;
+ }
+ if (run > 0) w.Write(ac.Code[0], ac.Length[0]);
+ }
+
+ private static void WriteHeaders(Stream output, Plan p, JpegEncodeOptions o, JpegHuffmanCode dcY, JpegHuffmanCode acY, JpegHuffmanCode dcC, JpegHuffmanCode acC)
+ {
+ var h = new MemoryStream();
+ h.Write([0xFF, JpegTables.Soi]);
+ if (o.App1Segments is { Count: > 0 } apps)
+ {
+ foreach (var app in apps)
+ {
+ if (app.Length > 65533) throw new ArgumentException("APP1 payload exceeds 65533 bytes", nameof(o));
+ Segment(h, JpegTables.App1, app);
+ }
+ }
+ else
+ {
+ Segment(h, JpegTables.App0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
+ }
+ var tables = p.Components == 1 ? 1 : 2;
+ var dqt = new byte[65 * tables];
+ for (var t = 0; t < tables; t++)
+ {
+ dqt[65 * t] = (byte)t;
+ for (var k = 0; k < 64; k++) dqt[65 * t + 1 + k] = (byte)p.Quant[t][JpegTables.NaturalOrder[k]];
+ }
+ Segment(h, JpegTables.Dqt, dqt);
+
+ var sof = new byte[6 + 3 * p.Components];
+ sof[0] = 8;
+ sof[1] = (byte)(p.Height >> 8);
+ sof[2] = (byte)p.Height;
+ sof[3] = (byte)(p.Width >> 8);
+ sof[4] = (byte)p.Width;
+ sof[5] = (byte)p.Components;
+ for (var c = 0; c < p.Components; c++)
+ {
+ sof[6 + 3 * c] = (byte)(c + 1);
+ sof[7 + 3 * c] = c == 0 ? (byte)(p.HY << 4 | p.VY) : (byte)0x11;
+ sof[8 + 3 * c] = (byte)(c == 0 ? 0 : 1);
+ }
+ Segment(h, JpegTables.Sof0, sof);
+
+ var dht = new MemoryStream();
+ Huffman(dht, 0x00, dcY);
+ Huffman(dht, 0x10, acY);
+ if (p.Components > 1)
+ {
+ Huffman(dht, 0x01, dcC);
+ Huffman(dht, 0x11, acC);
+ }
+ Segment(h, JpegTables.Dht, dht.ToArray());
+ if (o.RestartInterval > 0) Segment(h, JpegTables.Dri, [(byte)(o.RestartInterval >> 8), (byte)o.RestartInterval]);
+
+ var sos = new byte[4 + 2 * p.Components];
+ sos[0] = (byte)p.Components;
+ for (var c = 0; c < p.Components; c++)
+ {
+ sos[1 + 2 * c] = (byte)(c + 1);
+ sos[2 + 2 * c] = c == 0 ? (byte)0x00 : (byte)0x11;
+ }
+ sos[^3] = 0;
+ sos[^2] = 63;
+ sos[^1] = 0;
+ Segment(h, JpegTables.Sos, sos);
+ h.Position = 0;
+ h.CopyTo(output);
+ }
+
+ private static void Huffman(Stream s, byte classAndId, JpegHuffmanCode code)
+ {
+ s.WriteByte(classAndId);
+ s.Write(code.Bits);
+ s.Write(code.Values);
+ }
+
+ internal static void Segment(Stream s, byte marker, ReadOnlySpan payload)
+ {
+ var length = payload.Length + 2;
+ s.Write([0xFF, marker, (byte)(length >> 8), (byte)length]);
+ s.Write(payload);
+ }
+
+ private static float[] Transpose(float[] m)
+ {
+ var t = new float[64];
+ for (var i = 0; i < 8; i++)
+ {
+ for (var j = 0; j < 8; j++) t[j * 8 + i] = m[i * 8 + j];
+ }
+ return t;
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs
new file mode 100644
index 00000000..9a125079
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegHuffman.cs
@@ -0,0 +1,272 @@
+using System.Runtime.CompilerServices;
+
+namespace Titano.Core.Codecs.Jpeg;
+
+/// Canonical Huffman decoding table with a 9-bit lookahead (and a combined run/value table for AC).
+internal sealed class JpegHuffmanTable
+{
+ public const int FastBits = 9;
+
+ /// (length << 8) | symbol for codes of ≤ bits; 0 = longer code.
+ public readonly ushort[] Fast = new ushort[1 << FastBits];
+
+ /// Exclusive upper bound of each code length's codes, left-aligned to 16 bits.
+ public readonly int[] MaxCode = new int[18];
+
+ /// Symbol index = (code >> (16 − length)) + Delta[length].
+ public readonly int[] Delta = new int[17];
+
+ public readonly byte[] Values = new byte[256];
+
+ /// For AC tables: (value << 16) | (run << 8) | totalBits when code and magnitude fit in the lookahead.
+ public readonly int[] FastAc = new int[1 << FastBits];
+
+ /// Builds a table from the 16 code-length counts and the symbols (DHT layout).
+ /// The lengths oversubscribe the code space.
+ public JpegHuffmanTable(ReadOnlySpan counts, ReadOnlySpan values)
+ {
+ int code = 0, k = 0;
+ for (var len = 1; len <= 16; len++)
+ {
+ Delta[len] = k - code;
+ for (var i = 0; i < counts[len - 1]; i++, code++, k++)
+ {
+ if (code >= 1 << len) throw new InvalidDataException("JPEG: Huffman table oversubscribed");
+ if (len > FastBits) continue;
+ var first = code << (FastBits - len);
+ Fast.AsSpan(first, 1 << (FastBits - len)).Fill((ushort)(len << 8 | values[k]));
+ }
+ MaxCode[len] = code << (16 - len);
+ code <<= 1;
+ }
+ MaxCode[17] = int.MaxValue;
+ values[..k].CopyTo(Values);
+ BuildFastAc();
+ }
+
+ private void BuildFastAc()
+ {
+ for (var i = 0; i < Fast.Length; i++)
+ {
+ int e = Fast[i];
+ if (e == 0) continue;
+ var len = e >> 8;
+ var rs = e & 0xFF;
+ int run = rs >> 4, s = rs & 15;
+ if (s == 0 || len + s > FastBits) continue;
+ var m = (i >> (FastBits - len - s)) & ((1 << s) - 1);
+ var v = m < 1 << (s - 1) ? m - (1 << s) + 1 : m;
+ FastAc[i] = v << 16 | run << 8 | (len + s);
+ }
+ }
+}
+
+/// Thrown inside a scan when entropy-coded data is corrupt; the scan decoder resynchronises.
+internal sealed class JpegEntropyException(string message) : Exception(message);
+
+///
+/// MSB-first bit reader over entropy-coded JPEG data: removes 0xFF00 stuffing, stops at markers and then
+/// feeds zero bits, counting them so that consumption past the real data is detectable ().
+///
+internal ref struct JpegBitReader
+{
+ private readonly ReadOnlySpan _data;
+ private int _pos;
+ private ulong _bits;
+ private int _count;
+ private int _padBits;
+ private int _marker;
+ private int _markerPos;
+
+ public JpegBitReader(ReadOnlySpan data, int start)
+ {
+ _data = data;
+ _pos = start;
+ }
+
+ /// Marker code that stopped the reader (0 = none, -1 = end of data).
+ public readonly int Marker => _marker;
+
+ /// True once bits beyond the entropy-coded segment have been consumed.
+ public readonly bool Overrun => _padBits > _count;
+
+ /// Where marker parsing continues after the scan.
+ public readonly int Position => _marker > 0 ? _markerPos : _pos;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Ensure(int n)
+ {
+ if (_count < n) Fill();
+ }
+
+ /// Next bits (1..32) without consuming; call first.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public readonly int Peek(int n) => (int)(_bits >> (64 - n));
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Consume(int n)
+ {
+ _bits <<= n;
+ _count -= n;
+ }
+
+ /// Reads 1..16 bits.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadBits(int n)
+ {
+ if (_count < n) Fill();
+ var v = (int)(_bits >> (64 - n));
+ _bits <<= n;
+ _count -= n;
+ return v;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadBit()
+ {
+ if (_count < 1) Fill();
+ var v = (int)(_bits >> 63);
+ _bits <<= 1;
+ _count--;
+ return v;
+ }
+
+ /// Reads an -bit magnitude (1..16) and sign-extends it (T.81 F.2.2.1 EXTEND).
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int Receive(int s)
+ {
+ var v = ReadBits(s);
+ return v + ((((v >> (s - 1)) & 1) - 1) & (1 - (1 << s)));
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int Decode(JpegHuffmanTable t)
+ {
+ if (_count < 16) Fill();
+ int e = t.Fast[(int)(_bits >> (64 - JpegHuffmanTable.FastBits))];
+ if (e != 0)
+ {
+ var len = e >> 8;
+ _bits <<= len;
+ _count -= len;
+ return e & 0xFF;
+ }
+ return DecodeSlow(t);
+ }
+
+ private int DecodeSlow(JpegHuffmanTable t)
+ {
+ var code = (int)(_bits >> 48);
+ for (var len = JpegHuffmanTable.FastBits + 1; len <= 16; len++)
+ {
+ if (code < t.MaxCode[len])
+ {
+ Consume(len);
+ return t.Values[(code >> (16 - len)) + t.Delta[len]];
+ }
+ }
+ throw new JpegEntropyException("JPEG: invalid Huffman code");
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ public void Fill()
+ {
+ while (_count <= 56)
+ {
+ if (_marker != 0 || _pos >= _data.Length)
+ {
+ if (_marker == 0) _marker = -1;
+ _padBits += 8;
+ _count += 8;
+ continue;
+ }
+ int b = _data[_pos];
+ if (b == 0xFF)
+ {
+ var p = _pos + 1;
+ while (p < _data.Length && _data[p] == 0xFF) p++;
+ if (p >= _data.Length)
+ {
+ _pos = p;
+ continue;
+ }
+ if (_data[p] != 0)
+ {
+ _marker = _data[p];
+ _markerPos = p - 1;
+ continue;
+ }
+ _pos = p + 1;
+ }
+ else
+ {
+ _pos++;
+ }
+ _bits |= (ulong)(uint)b << (56 - _count);
+ _count += 8;
+ }
+ }
+
+ /// Discards buffered bits and locates the next marker (for restart processing). Returns its code
+ /// (-1 when the data ends) without consuming it; steps over it.
+ public int FindMarker()
+ {
+ _bits = 0;
+ _count = 0;
+ _padBits = 0;
+ if (_marker > 0) return _marker;
+ var p = _pos;
+ while (p + 1 < _data.Length)
+ {
+ if (_data[p] == 0xFF && _data[p + 1] is not (0x00 or 0xFF))
+ {
+ _marker = _data[p + 1];
+ _markerPos = p;
+ return _marker;
+ }
+ p++;
+ }
+ _pos = _data.Length;
+ _marker = -1;
+ return -1;
+ }
+
+ /// Consumes the marker found by and resumes reading after it.
+ public void AcceptMarker()
+ {
+ if (_marker <= 0) return;
+ _pos = _markerPos + 2;
+ _marker = 0;
+ }
+
+ ///
+ /// Restart processing with libjpeg's resync_to_restart rules: skips invalid markers and stale RSTs, accepts the
+ /// expected RSTn, and reports how many whole intervals were lost when RSTn+1/RSTn+2 shows up instead.
+ /// Returns false when a non-restart marker (or the end of data) ends the scan.
+ ///
+ public bool NextRestart(ref int expected, out int lostIntervals)
+ {
+ lostIntervals = 0;
+ while (true)
+ {
+ var marker = FindMarker();
+ if (marker < 0) return false;
+ if (marker < 0xC0)
+ {
+ AcceptMarker(); // corrupt data that happened to look like a marker
+ continue;
+ }
+ if (marker is < JpegTables.Rst0 or > JpegTables.Rst0 + 7) return false;
+ var delta = (marker - JpegTables.Rst0 - expected) & 7;
+ if (delta is 6 or 7)
+ {
+ AcceptMarker(); // a restart we already passed
+ continue;
+ }
+ if (delta is 1 or 2) lostIntervals = delta;
+ AcceptMarker();
+ expected = (marker - JpegTables.Rst0 + 1) & 7;
+ return true;
+ }
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs b/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs
new file mode 100644
index 00000000..071d76d1
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegHuffmanEncoding.cs
@@ -0,0 +1,151 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+/// Huffman code table for encoding (code and length per symbol) plus its DHT representation.
+internal sealed class JpegHuffmanCode
+{
+ public readonly byte[] Bits;
+ public readonly byte[] Values;
+ public readonly ushort[] Code = new ushort[256];
+ public readonly byte[] Length = new byte[256];
+
+ public JpegHuffmanCode(ReadOnlySpan bits, ReadOnlySpan values)
+ {
+ Bits = bits.ToArray();
+ Values = values.ToArray();
+ int code = 0, k = 0;
+ for (var len = 1; len <= 16; len++)
+ {
+ for (var i = 0; i < bits[len - 1]; i++, k++, code++)
+ {
+ Code[values[k]] = (ushort)code;
+ Length[values[k]] = (byte)len;
+ }
+ code <<= 1;
+ }
+ }
+
+ /// Optimal length-limited (16-bit) table for symbol frequencies (T.81 Annex K.2, as libjpeg).
+ public static JpegHuffmanCode Optimal(ReadOnlySpan frequencies)
+ {
+ var freq = new long[257];
+ frequencies.CopyTo(freq);
+ freq[256] = 1; // reserved code point guarantees no all-ones code
+ var codeSize = new int[257];
+ var others = new int[257];
+ Array.Fill(others, -1);
+ while (true)
+ {
+ int c1 = -1, c2 = -1;
+ long v1 = long.MaxValue, v2 = long.MaxValue;
+ for (var i = 0; i <= 256; i++)
+ {
+ if (freq[i] != 0 && freq[i] <= v1)
+ {
+ v1 = freq[i];
+ c1 = i;
+ }
+ }
+ for (var i = 0; i <= 256; i++)
+ {
+ if (freq[i] != 0 && freq[i] <= v2 && i != c1)
+ {
+ v2 = freq[i];
+ c2 = i;
+ }
+ }
+ if (c2 < 0) break;
+ freq[c1] += freq[c2];
+ freq[c2] = 0;
+ codeSize[c1]++;
+ while (others[c1] >= 0)
+ {
+ c1 = others[c1];
+ codeSize[c1]++;
+ }
+ others[c1] = c2;
+ codeSize[c2]++;
+ while (others[c2] >= 0)
+ {
+ c2 = others[c2];
+ codeSize[c2]++;
+ }
+ }
+ var bits = new int[33];
+ for (var i = 0; i <= 256; i++)
+ {
+ if (codeSize[i] > 0) bits[codeSize[i]]++;
+ }
+ for (var i = 32; i > 16; i--)
+ {
+ while (bits[i] > 0)
+ {
+ var j = i - 2;
+ while (bits[j] == 0) j--;
+ bits[i] -= 2;
+ bits[i - 1]++;
+ bits[j + 1] += 2;
+ bits[j]--;
+ }
+ }
+ var top = 16;
+ while (bits[top] == 0) top--;
+ bits[top]--; // drop the reserved symbol
+ var counts = new byte[16];
+ for (var i = 1; i <= 16; i++) counts[i - 1] = (byte)bits[i];
+ var values = new List();
+ for (var len = 1; len <= 32; len++)
+ {
+ for (var s = 0; s < 256; s++)
+ {
+ if (codeSize[s] == len) values.Add((byte)s);
+ }
+ }
+ return new JpegHuffmanCode(counts, values.ToArray());
+ }
+}
+
+/// MSB-first bit writer with 0xFF byte stuffing into a growable buffer.
+internal sealed class JpegBitWriter(int initialCapacity)
+{
+ private byte[] _buffer = new byte[Math.Max(1024, initialCapacity)];
+ private int _length;
+ private ulong _acc;
+ private int _bits;
+
+ public ReadOnlySpan Written => _buffer.AsSpan(0, _length);
+
+ /// Guarantees room for more output bytes (stuffing included).
+ public void Reserve(int bytes)
+ {
+ if (_length + bytes <= _buffer.Length) return;
+ Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + bytes));
+ }
+
+ /// Appends the low bits of (size ≤ 32).
+ public void Write(uint value, int size)
+ {
+ _acc = (_acc << size) | (value & (uint)((1UL << size) - 1));
+ _bits += size;
+ while (_bits >= 8)
+ {
+ _bits -= 8;
+ var b = (byte)(_acc >> _bits);
+ _buffer[_length++] = b;
+ if (b == 0xFF) _buffer[_length++] = 0;
+ }
+ }
+
+ /// Pads the last byte with 1-bits (T.81 F.1.2.3).
+ public void Flush()
+ {
+ if (_bits > 0) Write((1u << (8 - _bits)) - 1, 8 - _bits);
+ _acc = 0;
+ }
+
+ public void WriteMarker(byte marker)
+ {
+ Reserve(2);
+ _buffer[_length++] = 0xFF;
+ _buffer[_length++] = marker;
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs b/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs
new file mode 100644
index 00000000..41c8c826
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegIdct.cs
@@ -0,0 +1,169 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Inverse DCT. Full-size blocks use libjpeg's accurate integer algorithm (jidctint ISLOW: Loeffler–Ligtenberg–
+/// Moschytz with 13-bit constants), so output is bit-identical to libjpeg/djpeg. Reduced sizes (4, 2, 1) evaluate
+/// the low-frequency n×n coefficients on an n-point grid in float (DCT-domain scaling for thumbnails).
+///
+internal static class JpegIdct
+{
+ private const int ConstBits = 13;
+ private const int Fix0298631336 = 2446, Fix0390180644 = 3196, Fix0541196100 = 4433, Fix0765366865 = 6270;
+ private const int Fix0899976223 = 7373, Fix1175875602 = 9633, Fix1501321110 = 12299, Fix1847759065 = 15137;
+ private const int Fix1961570560 = 16069, Fix2053119869 = 16819, Fix2562915447 = 20995, Fix3072711026 = 25172;
+
+ private static readonly float[] Basis4 = JpegTables.BuildBasis(4);
+ private static readonly float[] Basis2 = JpegTables.BuildBasis(2);
+
+ /// Transforms one block into n·n samples, level-shifted and clamped to 0..2^precision−1.
+ /// 64 quantised coefficients, natural order.
+ /// 64 dequantisation factors, natural order.
+ /// Output block size: 8, 4, 2 or 1.
+ /// Sample precision (8 or 12).
+ public static void Transform(ReadOnlySpan coefficients, ReadOnlySpan quant, int size, int precision, Span output)
+ {
+ var max = (1 << precision) - 1;
+ var center = 1 << (precision - 1);
+ if (size == 8)
+ {
+ Islow(coefficients, quant, precision == 8 ? 2 : 1, center, max, output);
+ return;
+ }
+ if (size == 1)
+ {
+ output[0] = Math.Clamp((int)MathF.Round(coefficients[0] * quant[0] * 0.125f) + center, 0, max);
+ return;
+ }
+ Reduced(coefficients, quant, size, size == 4 ? Basis4 : Basis2, center, max, output);
+ }
+
+ /// Port of libjpeg-turbo jpeg_idct_islow (columns, then rows; PASS1_BITS 2 for 8-bit, 1 for 12-bit).
+ private static void Islow(ReadOnlySpan c, ReadOnlySpan q, int pass1Bits, int center, int max, Span output)
+ {
+ Span ws = stackalloc int[64];
+ _ = c[63];
+ _ = q[63];
+ for (var col = 0; col < 8; col++)
+ {
+ if (c[8 + col] == 0 && c[16 + col] == 0 && c[24 + col] == 0 && c[32 + col] == 0 &&
+ c[40 + col] == 0 && c[48 + col] == 0 && c[56 + col] == 0)
+ {
+ var dc = c[col] * q[col] << pass1Bits;
+ for (var r = 0; r < 8; r++) ws[r * 8 + col] = dc;
+ continue;
+ }
+ var shift = ConstBits - pass1Bits;
+ Butterfly(
+ c[col] * q[col], c[8 + col] * q[8 + col], c[16 + col] * q[16 + col], c[24 + col] * q[24 + col],
+ c[32 + col] * q[32 + col], c[40 + col] * q[40 + col], c[48 + col] * q[48 + col], c[56 + col] * q[56 + col],
+ out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7);
+ var round = 1 << (shift - 1);
+ ws[col] = (o0 + round) >> shift;
+ ws[8 + col] = (o1 + round) >> shift;
+ ws[16 + col] = (o2 + round) >> shift;
+ ws[24 + col] = (o3 + round) >> shift;
+ ws[32 + col] = (o4 + round) >> shift;
+ ws[40 + col] = (o5 + round) >> shift;
+ ws[48 + col] = (o6 + round) >> shift;
+ ws[56 + col] = (o7 + round) >> shift;
+ }
+ for (var row = 0; row < 8; row++)
+ {
+ var w = ws.Slice(row * 8, 8);
+ var o = output.Slice(row * 8, 8);
+ if (w[1] == 0 && w[2] == 0 && w[3] == 0 && w[4] == 0 && w[5] == 0 && w[6] == 0 && w[7] == 0)
+ {
+ var dcShift = pass1Bits + 3;
+ o.Fill(Math.Clamp(((w[0] + (1 << (dcShift - 1))) >> dcShift) + center, 0, max));
+ continue;
+ }
+ var shift = ConstBits + pass1Bits + 3;
+ var round = 1 << (shift - 1);
+ Butterfly(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7],
+ out var o0, out var o1, out var o2, out var o3, out var o4, out var o5, out var o6, out var o7);
+ o[0] = Math.Clamp(((o0 + round) >> shift) + center, 0, max);
+ o[1] = Math.Clamp(((o1 + round) >> shift) + center, 0, max);
+ o[2] = Math.Clamp(((o2 + round) >> shift) + center, 0, max);
+ o[3] = Math.Clamp(((o3 + round) >> shift) + center, 0, max);
+ o[4] = Math.Clamp(((o4 + round) >> shift) + center, 0, max);
+ o[5] = Math.Clamp(((o5 + round) >> shift) + center, 0, max);
+ o[6] = Math.Clamp(((o6 + round) >> shift) + center, 0, max);
+ o[7] = Math.Clamp(((o7 + round) >> shift) + center, 0, max);
+ }
+ }
+
+ /// One 8-point ISLOW pass; outputs are scaled by 2^13 (CONST_BITS) before descaling.
+ private static void Butterfly(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7,
+ out int o0, out int o1, out int o2, out int o3, out int o4, out int o5, out int o6, out int o7)
+ {
+ // Even part: the rotator is sqrt(2)·c(−6).
+ var z1 = (i2 + i6) * Fix0541196100;
+ var tmp2 = z1 - i6 * Fix1847759065;
+ var tmp3 = z1 + i2 * Fix0765366865;
+ var tmp0 = (i0 + i4) << ConstBits;
+ var tmp1 = (i0 - i4) << ConstBits;
+ int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
+
+ // Odd part (figure 8 of the LL&M paper).
+ tmp0 = i7;
+ tmp1 = i5;
+ tmp2 = i3;
+ tmp3 = i1;
+ z1 = tmp0 + tmp3;
+ var z2 = tmp1 + tmp2;
+ var z3 = tmp0 + tmp2;
+ var z4 = tmp1 + tmp3;
+ var z5 = (z3 + z4) * Fix1175875602;
+ tmp0 *= Fix0298631336;
+ tmp1 *= Fix2053119869;
+ tmp2 *= Fix3072711026;
+ tmp3 *= Fix1501321110;
+ z1 *= -Fix0899976223;
+ z2 *= -Fix2562915447;
+ z3 = z3 * -Fix1961570560 + z5;
+ z4 = z4 * -Fix0390180644 + z5;
+ tmp0 += z1 + z3;
+ tmp1 += z2 + z4;
+ tmp2 += z2 + z3;
+ tmp3 += z1 + z4;
+
+ o0 = tmp10 + tmp3;
+ o7 = tmp10 - tmp3;
+ o1 = tmp11 + tmp2;
+ o6 = tmp11 - tmp2;
+ o2 = tmp12 + tmp1;
+ o5 = tmp12 - tmp1;
+ o3 = tmp13 + tmp0;
+ o4 = tmp13 - tmp0;
+ }
+
+ /// n-point IDCT of the low-frequency n×n coefficients, evaluated at the centres of n output samples.
+ private static void Reduced(ReadOnlySpan coefficients, ReadOnlySpan quant, int n, float[] basis, int center, int max, Span output)
+ {
+ Span g = stackalloc float[n * n];
+ Span f = stackalloc float[n];
+ g.Clear();
+ for (var v = 0; v < n; v++)
+ {
+ var row = g.Slice(v * n, n);
+ for (var u = 0; u < n; u++)
+ {
+ int coef = coefficients[v * 8 + u];
+ if (coef == 0) continue;
+ var value = (float)(coef * quant[v * 8 + u]);
+ for (var x = 0; x < n; x++) row[x] += value * basis[u * n + x];
+ }
+ }
+ for (var y = 0; y < n; y++)
+ {
+ f.Clear();
+ for (var v = 0; v < n; v++)
+ {
+ var w = basis[v * n + y];
+ var row = g.Slice(v * n, n);
+ for (var x = 0; x < n; x++) f[x] += w * row[x];
+ }
+ for (var x = 0; x < n; x++) output[y * n + x] = Math.Clamp((int)MathF.Round(f[x]) + center, 0, max);
+ }
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs
new file mode 100644
index 00000000..fce195ae
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessDecoder.cs
@@ -0,0 +1,132 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Lossless JPEG (SOF3, ITU T.81 Annex H) as used by DNG raw tiles and CR2: predictors 1–7, point transform,
+/// 2–16 bit precision, one or more components (interleaved or in separate scans), restart intervals.
+///
+public static class JpegLosslessDecoder
+{
+ /// Decodes a lossless stream to interleaved samples with the frame's own width and component count
+ /// (DNG tiles often encode e.g. two components at half the tile width; callers re-map the sample order).
+ /// The stream is malformed or not lossless.
+ public static JpegLosslessImage Decode(ReadOnlySpan data)
+ {
+ var parser = new JpegParser(JpegDecodeOptions.Default);
+ parser.Parse(data);
+ if (parser.Frame!.Process != JpegProcess.Lossless) throw new InvalidDataException("JPEG: not a lossless (SOF3) stream");
+ return Finish(parser);
+ }
+
+ /// Applies each component's point transform and packages the samples.
+ internal static JpegLosslessImage Finish(JpegParser parser)
+ {
+ var f = parser.Frame!;
+ var n = f.Components.Length;
+ var samples = parser.LosslessSamples ?? new ushort[checked(f.Width * f.Height * n)];
+ foreach (var c in f.Components)
+ {
+ if (c.PointTransform == 0) continue;
+ for (var i = c.Index; i < samples.Length; i += n) samples[i] = (ushort)(samples[i] << c.PointTransform);
+ c.PointTransform = 0;
+ }
+ parser.LosslessSamples = samples;
+ return new JpegLosslessImage(samples, f.Width, f.Height, n, f.Precision);
+ }
+
+ internal static int DecodeScan(JpegParser parser, ReadOnlySpan data, int pos, JpegScan scan)
+ {
+ var f = parser.Frame!;
+ int width = f.Width, nf = f.Components.Length, stride = width * nf;
+ var samples = parser.LosslessSamples ??= new ushort[checked(stride * f.Height)];
+ var comps = scan.Components;
+ var tables = scan.DcTables;
+ var ns = comps.Length;
+ var index = new int[ns];
+ for (var i = 0; i < ns; i++)
+ {
+ index[i] = comps[i].Index;
+ comps[i].PointTransform = scan.Al;
+ }
+ var predictor = scan.Ss;
+ var initial = 1 << (f.Precision - scan.Al - 1);
+ var interval = parser.RestartInterval;
+ var total = (long)width * f.Height;
+ var reader = new JpegBitReader(data, pos);
+
+ long mcu = 0;
+ int x = 0, y = 0, restartRow = 0, expectedRst = 0;
+ var first = true;
+ while (mcu < total)
+ {
+ var end = interval > 0 ? Math.Min(total, mcu + interval) : total;
+ try
+ {
+ for (; mcu < end; mcu++)
+ {
+ var at = y * stride + x * nf;
+ for (var i = 0; i < ns; i++)
+ {
+ var s = reader.Decode(tables[i]!);
+ var diff = s switch
+ {
+ 0 => 0,
+ 16 => 32768,
+ > 16 => throw new JpegEntropyException("JPEG: bad lossless difference magnitude"),
+ _ => reader.Receive(s),
+ };
+ var idx = at + index[i];
+ int pred;
+ if (first) pred = initial;
+ else if (y == restartRow) pred = samples[idx - nf];
+ else if (x == 0) pred = samples[idx - stride];
+ else pred = Predict(predictor, samples[idx - nf], samples[idx - stride], samples[idx - stride - nf]);
+ samples[idx] = (ushort)(pred + diff);
+ }
+ first = false;
+ if (++x == width)
+ {
+ x = 0;
+ y++;
+ if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
+ }
+ }
+ if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
+ }
+ catch (JpegEntropyException ex)
+ {
+ parser.Warn(ex.Message);
+ if (interval == 0) break;
+ mcu = end;
+ }
+ if (mcu >= total || interval == 0) break;
+
+ if (!reader.NextRestart(ref expectedRst, out var lost))
+ {
+ parser.Warn("JPEG: restart marker missing; scan truncated");
+ break;
+ }
+ if (lost > 0)
+ {
+ // Intervals between the expected and the found marker were lost: leave their samples untouched.
+ parser.Warn($"JPEG: {lost} restart interval(s) lost");
+ mcu += (long)lost * interval;
+ }
+ x = (int)(mcu % width);
+ y = (int)(mcu / width);
+ restartRow = y;
+ first = true;
+ }
+ return reader.Position;
+ }
+
+ private static int Predict(int predictor, int ra, int rb, int rc) => predictor switch
+ {
+ 1 => ra,
+ 2 => rb,
+ 3 => rc,
+ 4 => ra + rb - rc,
+ 5 => ra + ((rb - rc) >> 1),
+ 6 => rb + ((ra - rc) >> 1),
+ _ => (ra + rb) >> 1,
+ };
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs
new file mode 100644
index 00000000..6db474d6
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegLosslessEncoder.cs
@@ -0,0 +1,169 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Lossless JPEG (SOF3) encoder: one interleaved scan, optimal Huffman table per component, predictors 1–7,
+/// point transform and restart intervals. Used for DNG tiles (DNG Compression = 7).
+///
+public static class JpegLosslessEncoder
+{
+ /// Encodes interleaved samples (each < 2^).
+ /// Restart interval in samples per component (0 = none).
+ public static byte[] Encode(ReadOnlySpan samples, int width, int height, int components, int precision,
+ int predictor = 1, int pointTransform = 0, int restartInterval = 0)
+ {
+ if (width is < 1 or > 65535 || height is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(width));
+ if (components is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(components));
+ if (precision is < 2 or > 16) throw new ArgumentOutOfRangeException(nameof(precision));
+ if (predictor is < 1 or > 7) throw new ArgumentOutOfRangeException(nameof(predictor));
+ if (pointTransform < 0 || pointTransform >= precision) throw new ArgumentOutOfRangeException(nameof(pointTransform));
+ if (restartInterval is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(restartInterval));
+ if (samples.Length < (long)width * height * components) throw new ArgumentException("Sample buffer too small", nameof(samples));
+ var limit = 1 << precision;
+ foreach (var s in samples[..(width * height * components)])
+ {
+ if (s >= limit) throw new ArgumentException($"Sample {s} exceeds {precision}-bit precision", nameof(samples));
+ }
+
+ var layout = new Layout(width, height, components, predictor, pointTransform, restartInterval, precision);
+ var counter = new Counter { Frequencies = new long[components][] };
+ for (var c = 0; c < components; c++) counter.Frequencies[c] = new long[256];
+ Walk(samples, layout, ref counter);
+ var codes = new JpegHuffmanCode[components];
+ for (var c = 0; c < components; c++) codes[c] = JpegHuffmanCode.Optimal(counter.Frequencies[c]);
+
+ var emitter = new Emitter { Writer = new JpegBitWriter((int)Math.Min(1 << 30, (long)width * height * components)), Codes = codes };
+ Walk(samples, layout, ref emitter);
+ emitter.Writer.Flush();
+
+ using var output = new MemoryStream();
+ output.Write([0xFF, JpegTables.Soi]);
+ var sof = new byte[6 + 3 * components];
+ sof[0] = (byte)precision;
+ sof[1] = (byte)(height >> 8);
+ sof[2] = (byte)height;
+ sof[3] = (byte)(width >> 8);
+ sof[4] = (byte)width;
+ sof[5] = (byte)components;
+ for (var c = 0; c < components; c++)
+ {
+ sof[6 + 3 * c] = (byte)(c + 1);
+ sof[7 + 3 * c] = 0x11;
+ }
+ JpegEncoder.Segment(output, JpegTables.Sof3, sof);
+ var dht = new MemoryStream();
+ for (var c = 0; c < components; c++)
+ {
+ dht.WriteByte((byte)c);
+ dht.Write(codes[c].Bits);
+ dht.Write(codes[c].Values);
+ }
+ JpegEncoder.Segment(output, JpegTables.Dht, dht.ToArray());
+ if (restartInterval > 0) JpegEncoder.Segment(output, JpegTables.Dri, [(byte)(restartInterval >> 8), (byte)restartInterval]);
+ var sos = new byte[4 + 2 * components];
+ sos[0] = (byte)components;
+ for (var c = 0; c < components; c++)
+ {
+ sos[1 + 2 * c] = (byte)(c + 1);
+ sos[2 + 2 * c] = (byte)(c << 4);
+ }
+ sos[^3] = (byte)predictor;
+ sos[^2] = 0;
+ sos[^1] = (byte)pointTransform;
+ JpegEncoder.Segment(output, JpegTables.Sos, sos);
+ output.Write(emitter.Writer.Written);
+ output.Write([0xFF, JpegTables.Eoi]);
+ return output.ToArray();
+ }
+
+ private readonly record struct Layout(int Width, int Height, int Components, int Predictor, int PointTransform, int RestartInterval, int Precision);
+
+ private interface ISink
+ {
+ void Difference(int component, int diff);
+ void Restart(int index);
+ }
+
+ /// Visits every residual in stream order with the decoder's prediction rules (T.81 H.1.2).
+ private static void Walk(ReadOnlySpan samples, Layout l, ref TSink sink) where TSink : struct, ISink
+ {
+ int w = l.Width, nc = l.Components, stride = w * nc, pt = l.PointTransform;
+ var initial = 1 << (l.Precision - pt - 1);
+ var total = (long)w * l.Height;
+ int restartRow = 0, x = 0, y = 0, rst = 0;
+ var first = true;
+ for (long mcu = 0; mcu < total; mcu++)
+ {
+ if (l.RestartInterval > 0 && mcu > 0 && mcu % l.RestartInterval == 0)
+ {
+ sink.Restart(rst);
+ rst = (rst + 1) & 7;
+ first = true;
+ restartRow = y;
+ }
+ var at = y * stride + x * nc;
+ for (var c = 0; c < nc; c++)
+ {
+ var idx = at + c;
+ int pred;
+ if (first) pred = initial;
+ else if (y == restartRow) pred = samples[idx - nc] >> pt;
+ else if (x == 0) pred = samples[idx - stride] >> pt;
+ else
+ {
+ int ra = samples[idx - nc] >> pt, rb = samples[idx - stride] >> pt, rc = samples[idx - stride - nc] >> pt;
+ pred = l.Predictor switch
+ {
+ 1 => ra,
+ 2 => rb,
+ 3 => rc,
+ 4 => ra + rb - rc,
+ 5 => ra + ((rb - rc) >> 1),
+ 6 => rb + ((ra - rc) >> 1),
+ _ => (ra + rb) >> 1,
+ };
+ }
+ sink.Difference(c, (short)((samples[idx] >> pt) - pred));
+ }
+ first = false;
+ if (++x == w)
+ {
+ x = 0;
+ y++;
+ }
+ }
+ }
+
+ private static int Category(int diff) => diff == -32768 ? 16 : diff == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(diff));
+
+ private struct Counter : ISink
+ {
+ public long[][] Frequencies;
+
+ public readonly void Difference(int component, int diff) => Frequencies[component][Category(diff)]++;
+
+ public readonly void Restart(int index)
+ {
+ }
+ }
+
+ private struct Emitter : ISink
+ {
+ public JpegBitWriter Writer;
+ public JpegHuffmanCode[] Codes;
+
+ public readonly void Difference(int component, int diff)
+ {
+ var code = Codes[component];
+ var s = Category(diff);
+ Writer.Reserve(16);
+ Writer.Write(code.Code[s], code.Length[s]);
+ if (s is > 0 and < 16) Writer.Write((uint)((diff < 0 ? diff - 1 : diff) & ((1 << s) - 1)), s);
+ }
+
+ public readonly void Restart(int index)
+ {
+ Writer.Flush();
+ Writer.WriteMarker((byte)(JpegTables.Rst0 + index));
+ }
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegParser.cs b/src/Titano.Core/Codecs/Jpeg/JpegParser.cs
new file mode 100644
index 00000000..ec660afd
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegParser.cs
@@ -0,0 +1,400 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+/// One frame component and its coefficient (DCT) storage.
+internal sealed class JpegComponent
+{
+ public int Id, Index, H, V, QuantTable;
+
+ /// Component size in samples: ceil(X·H/Hmax) × ceil(Y·V/Vmax).
+ public int Width, Height;
+
+ /// Blocks covering the component (non-interleaved scan extent).
+ public int WidthInBlocks, HeightInBlocks;
+
+ /// Allocated block grid, padded to whole MCUs.
+ public int BlocksPerLine, BlocksPerColumn;
+
+ /// Quantised coefficients, 64 per block in natural order, blocks row-major.
+ public short[]? Coefficients;
+
+ /// Quantisation table latched when the component's first scan starts (natural order).
+ public ushort[]? Quant;
+
+ /// Point transform of the lossless scan that carried this component.
+ public int PointTransform;
+
+ public int DcPred;
+}
+
+/// Frame header (SOFn) with derived MCU geometry.
+internal sealed class JpegFrame
+{
+ public required JpegProcess Process { get; init; }
+ public required int Precision { get; init; }
+ public required int Width { get; init; }
+ public required int Height { get; init; }
+ public required JpegComponent[] Components { get; init; }
+ public int HMax { get; init; }
+ public int VMax { get; init; }
+ public int McusX { get; init; }
+ public int McusY { get; init; }
+}
+
+/// Scan header (SOS) resolved against the frame.
+internal sealed class JpegScan
+{
+ public required JpegComponent[] Components { get; init; }
+ public required JpegHuffmanTable?[] DcTables { get; init; }
+ public required JpegHuffmanTable?[] AcTables { get; init; }
+ public int Ss { get; init; }
+ public int Se { get; init; }
+ public int Ah { get; init; }
+ public int Al { get; init; }
+}
+
+///
+/// Marker-level JPEG parser: tables, frame and scan headers; dispatches entropy-coded segments to the DCT or
+/// lossless scan decoders. Structural errors throw ; once a scan has been
+/// decoded, later errors only end parsing with a warning so that partial images survive.
+///
+internal sealed class JpegParser(JpegDecodeOptions options)
+{
+ private readonly ushort[]?[] _quant = new ushort[4][];
+ private readonly JpegHuffmanTable?[] _dc = new JpegHuffmanTable[4];
+ private readonly JpegHuffmanTable?[] _ac = new JpegHuffmanTable[4];
+ private readonly List _warnings = [];
+ private static JpegHuffmanTable? _stdDcLuma, _stdDcChroma, _stdAcLuma, _stdAcChroma;
+
+ public JpegDecodeOptions Options { get; } = options;
+ public JpegFrame? Frame { get; private set; }
+ public int RestartInterval { get; private set; }
+ public int AdobeTransform { get; private set; } = -1;
+ public bool Jfif { get; private set; }
+ public int ScansDecoded { get; private set; }
+ public IReadOnlyList Warnings => _warnings;
+
+ /// Interleaved samples of a lossless frame (point transform not yet applied).
+ public ushort[]? LosslessSamples { get; set; }
+
+ public void Warn(string message)
+ {
+ if (_warnings.Count < 64) _warnings.Add(message);
+ }
+
+ /// Parses a full stream. With it stops at the first scan header.
+ public void Parse(ReadOnlySpan data, bool headerOnly = false)
+ {
+ if (Options.Tables is { Length: > 0 } tables) ParseCore(tables, tablesOnly: true, headerOnly: false);
+ try
+ {
+ ParseCore(data, tablesOnly: false, headerOnly);
+ }
+ catch (InvalidDataException ex) when (ScansDecoded > 0)
+ {
+ Warn(ex.Message);
+ }
+ if (Frame is null) throw new InvalidDataException("JPEG: no frame header");
+ if (!headerOnly && ScansDecoded == 0) throw new InvalidDataException("JPEG: no scan data");
+ }
+
+ public JpegInfo Info()
+ {
+ var f = Frame ?? throw new InvalidDataException("JPEG: no frame header");
+ return new JpegInfo(
+ f.Width, f.Height, f.Components.Length, f.Precision, f.Process, ColorSpace(),
+ f.Components.Select(c => (c.H, c.V)).ToArray(), RestartInterval);
+ }
+
+ /// Colour space after applying the option override and libjpeg's marker/component-id heuristics.
+ public JpegColorSpace ColorSpace()
+ {
+ var f = Frame!;
+ var n = f.Components.Length;
+ if (n == 1) return JpegColorSpace.Gray;
+ if (f.Process == JpegProcess.Lossless && Options.ColorTransform == JpegColorTransform.Auto)
+ return n switch { 3 => JpegColorSpace.Rgb, 4 => JpegColorSpace.Cmyk, _ => JpegColorSpace.Other };
+ var transformed = Options.ColorTransform switch
+ {
+ JpegColorTransform.None => false,
+ JpegColorTransform.YCbCr => true,
+ _ => n == 3
+ ? Jfif || (AdobeTransform < 0 ? !(f.Components[0].Id == 'R' && f.Components[1].Id == 'G' && f.Components[2].Id == 'B') : AdobeTransform != 0)
+ : AdobeTransform == 2,
+ };
+ return n switch
+ {
+ 3 => transformed ? JpegColorSpace.YCbCr : JpegColorSpace.Rgb,
+ 4 => transformed ? JpegColorSpace.Ycck : JpegColorSpace.Cmyk,
+ _ => JpegColorSpace.Other,
+ };
+ }
+
+ private void ParseCore(ReadOnlySpan data, bool tablesOnly, bool headerOnly)
+ {
+ if (data.Length < 4 || data[0] != 0xFF || data[1] != JpegTables.Soi) throw new InvalidDataException("JPEG: missing SOI marker");
+ var pos = 2;
+ while (true)
+ {
+ var marker = NextMarker(data, ref pos);
+ if (marker < 0)
+ {
+ if (!tablesOnly) Warn("JPEG: missing EOI marker");
+ return;
+ }
+ if (marker == JpegTables.Eoi) return;
+ if (marker is JpegTables.Soi or (>= JpegTables.Rst0 and <= JpegTables.Rst0 + 7) or 0x01) continue;
+ if (pos + 2 > data.Length) throw new InvalidDataException("JPEG: truncated marker segment");
+ var length = data[pos] << 8 | data[pos + 1];
+ if (length < 2 || pos + length > data.Length) throw new InvalidDataException($"JPEG: bad length for marker 0x{marker:X2}");
+ var segment = data.Slice(pos + 2, length - 2);
+ pos += length;
+ switch (marker)
+ {
+ case JpegTables.Dqt:
+ ParseDqt(segment);
+ break;
+ case JpegTables.Dht:
+ ParseDht(segment);
+ break;
+ case JpegTables.Dri:
+ if (segment.Length < 2) throw new InvalidDataException("JPEG: bad DRI");
+ RestartInterval = segment[0] << 8 | segment[1];
+ break;
+ case JpegTables.App0:
+ if (segment.StartsWith("JFIF\0"u8)) Jfif = true;
+ break;
+ case JpegTables.App14:
+ if (segment.Length >= 12 && segment.StartsWith("Adobe"u8)) AdobeTransform = segment[11];
+ break;
+ case >= JpegTables.Sof0 and <= JpegTables.Sof3:
+ if (tablesOnly) throw new InvalidDataException("JPEG: frame header in a tables-only stream");
+ if (Frame is not null) throw new InvalidDataException("JPEG: more than one frame");
+ ParseSof(marker, segment);
+ break;
+ case JpegTables.Sos:
+ if (tablesOnly || Frame is null) throw new InvalidDataException("JPEG: scan without frame header");
+ if (headerOnly) return;
+ pos = DecodeScan(data, segment, pos);
+ ScansDecoded++;
+ break;
+ case JpegTables.Dac:
+ throw new InvalidDataException("JPEG: arithmetic coding is not supported");
+ case >= 0xC5 and <= 0xCF:
+ throw new InvalidDataException($"JPEG: unsupported coding process (SOF 0x{marker:X2})");
+ }
+ }
+ }
+
+ /// Finds the next marker at or after , skipping garbage; returns its code or -1.
+ private int NextMarker(ReadOnlySpan data, ref int pos)
+ {
+ var start = pos;
+ while (pos + 1 < data.Length)
+ {
+ if (data[pos] != 0xFF)
+ {
+ pos++;
+ continue;
+ }
+ int m = data[pos + 1];
+ if (m == 0xFF)
+ {
+ pos++;
+ continue;
+ }
+ if (m == 0)
+ {
+ pos += 2;
+ continue;
+ }
+ if (pos != start) Warn($"JPEG: {pos - start} extraneous bytes before marker 0x{m:X2}");
+ pos += 2;
+ return m;
+ }
+ pos = data.Length;
+ return -1;
+ }
+
+ private void ParseDqt(ReadOnlySpan s)
+ {
+ while (s.Length > 0)
+ {
+ int pq = s[0] >> 4, tq = s[0] & 15;
+ var size = pq == 0 ? 64 : 128;
+ if (pq > 1 || tq > 3 || s.Length < 1 + size) throw new InvalidDataException("JPEG: bad DQT");
+ var table = new ushort[64];
+ for (var k = 0; k < 64; k++)
+ {
+ table[JpegTables.NaturalOrder[k]] = pq == 0 ? s[1 + k] : (ushort)(s[1 + 2 * k] << 8 | s[2 + 2 * k]);
+ }
+ _quant[tq] = table;
+ s = s[(1 + size)..];
+ }
+ }
+
+ private void ParseDht(ReadOnlySpan s)
+ {
+ while (s.Length > 0)
+ {
+ if (s.Length < 17) throw new InvalidDataException("JPEG: bad DHT");
+ int tc = s[0] >> 4, th = s[0] & 15;
+ if (tc > 1 || th > 3) throw new InvalidDataException("JPEG: bad DHT class/id");
+ var counts = s.Slice(1, 16);
+ var total = 0;
+ foreach (var c in counts) total += c;
+ if (total > 256 || s.Length < 17 + total) throw new InvalidDataException("JPEG: bad DHT counts");
+ var table = new JpegHuffmanTable(counts, s.Slice(17, total));
+ (tc == 0 ? _dc : _ac)[th] = table;
+ s = s[(17 + total)..];
+ }
+ }
+
+ private void ParseSof(int marker, ReadOnlySpan s)
+ {
+ if (s.Length < 6) throw new InvalidDataException("JPEG: bad SOF");
+ var process = marker switch
+ {
+ JpegTables.Sof0 => JpegProcess.Baseline,
+ JpegTables.Sof1 => JpegProcess.ExtendedSequential,
+ JpegTables.Sof2 => JpegProcess.Progressive,
+ _ => JpegProcess.Lossless,
+ };
+ int precision = s[0], height = s[1] << 8 | s[2], width = s[3] << 8 | s[4], n = s[5];
+ if (process == JpegProcess.Lossless ? precision is < 2 or > 16 : precision is not (8 or 12))
+ throw new InvalidDataException($"JPEG: unsupported precision {precision}");
+ if (width == 0 || height == 0) throw new InvalidDataException("JPEG: zero image size (DNL is not supported)");
+ if ((long)width * height > Options.MaxPixels) throw new InvalidDataException($"JPEG: {width}x{height} exceeds the pixel limit");
+ if (n is < 1 or > 4 || s.Length < 6 + 3 * n) throw new InvalidDataException("JPEG: bad component count");
+ var components = new JpegComponent[n];
+ int hMax = 1, vMax = 1;
+ for (var i = 0; i < n; i++)
+ {
+ var c = s.Slice(6 + 3 * i, 3);
+ int h = c[1] >> 4, v = c[1] & 15;
+ if (h is < 1 or > 4 || v is < 1 or > 4 || c[2] > 3) throw new InvalidDataException("JPEG: bad sampling factors");
+ components[i] = new JpegComponent { Id = c[0], Index = i, H = h, V = v, QuantTable = c[2] };
+ hMax = Math.Max(hMax, h);
+ vMax = Math.Max(vMax, v);
+ }
+ if (n == 1)
+ {
+ // A single component is always coded non-interleaved: its own factors are irrelevant.
+ components[0].H = components[0].V = hMax = vMax = 1;
+ }
+ foreach (var c in components)
+ {
+ if (hMax % c.H != 0 || vMax % c.V != 0) throw new InvalidDataException("JPEG: fractional sampling ratios are not supported");
+ if (process == JpegProcess.Lossless && (c.H != 1 || c.V != 1))
+ throw new InvalidDataException("JPEG: subsampled lossless streams are not supported");
+ }
+ var unit = process == JpegProcess.Lossless ? 1 : 8;
+ var mcusX = DivUp(width, unit * hMax);
+ var mcusY = DivUp(height, unit * vMax);
+ foreach (var c in components)
+ {
+ c.Width = DivUp(width * c.H, hMax);
+ c.Height = DivUp(height * c.V, vMax);
+ c.WidthInBlocks = DivUp(c.Width, 8);
+ c.HeightInBlocks = DivUp(c.Height, 8);
+ c.BlocksPerLine = mcusX * c.H;
+ c.BlocksPerColumn = mcusY * c.V;
+ }
+ Frame = new JpegFrame
+ {
+ Process = process, Precision = precision, Width = width, Height = height, Components = components,
+ HMax = hMax, VMax = vMax, McusX = mcusX, McusY = mcusY,
+ };
+ }
+
+ private int DecodeScan(ReadOnlySpan data, ReadOnlySpan s, int pos)
+ {
+ var frame = Frame!;
+ if (s.Length < 1) throw new InvalidDataException("JPEG: bad SOS");
+ int n = s[0];
+ if (n is < 1 or > 4 || s.Length < 4 + 2 * n) throw new InvalidDataException("JPEG: bad SOS component count");
+ var comps = new JpegComponent[n];
+ var dc = new JpegHuffmanTable?[n];
+ var ac = new JpegHuffmanTable?[n];
+ var tdTa = new int[n];
+ for (var i = 0; i < n; i++)
+ {
+ int id = s[1 + 2 * i];
+ JpegComponent? match = null;
+ foreach (var c in frame.Components)
+ {
+ if (c.Id == id && Array.IndexOf(comps, c) < 0)
+ {
+ match = c;
+ break;
+ }
+ }
+ comps[i] = match ?? throw new InvalidDataException($"JPEG: scan references unknown component {id}");
+ tdTa[i] = s[2 + 2 * i];
+ }
+ var p = 1 + 2 * n;
+ int ss = s[p], se = s[p + 1], ah = s[p + 2] >> 4, al = s[p + 2] & 15;
+
+ if (frame.Process == JpegProcess.Lossless)
+ {
+ if (ss is < 1 or > 7) throw new InvalidDataException($"JPEG: bad lossless predictor {ss}");
+ if (al >= frame.Precision) throw new InvalidDataException("JPEG: bad point transform");
+ for (var i = 0; i < n; i++) dc[i] = _dc[tdTa[i] >> 4 & 3] ?? throw new InvalidDataException("JPEG: missing Huffman table");
+ var losslessScan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Al = al };
+ return JpegLosslessDecoder.DecodeScan(this, data, pos, losslessScan);
+ }
+
+ var progressive = frame.Process == JpegProcess.Progressive;
+ if (progressive)
+ {
+ if (ss > se || se > 63 || (ss == 0 && se != 0) || (ss > 0 && n != 1) || al > 13 || ah > 13)
+ throw new InvalidDataException("JPEG: bad progressive scan parameters");
+ }
+ else
+ {
+ ss = 0;
+ se = 63;
+ ah = al = 0;
+ }
+ if (n > 1)
+ {
+ var blocks = 0;
+ foreach (var c in comps) blocks += c.H * c.V;
+ if (blocks > 10) throw new InvalidDataException("JPEG: too many blocks per MCU");
+ }
+ var needDc = ss == 0 && ah == 0;
+ var needAc = se > 0;
+ for (var i = 0; i < n; i++)
+ {
+ int td = tdTa[i] >> 4, ta = tdTa[i] & 15;
+ if (td > 3 || ta > 3) throw new InvalidDataException("JPEG: bad Huffman table selector");
+ if (needDc) dc[i] = _dc[td] ?? StandardTable(dc: true, td);
+ if (needAc) ac[i] = _ac[ta] ?? StandardTable(dc: false, ta);
+ var c = comps[i];
+ if (c.Quant is null)
+ {
+ c.Quant = _quant[c.QuantTable] is { } q ? (ushort[])q.Clone() : throw new InvalidDataException("JPEG: missing quantisation table");
+ }
+ c.Coefficients ??= new short[checked(c.BlocksPerLine * c.BlocksPerColumn * 64)];
+ }
+ var scan = new JpegScan { Components = comps, DcTables = dc, AcTables = ac, Ss = ss, Se = se, Ah = ah, Al = al };
+ return JpegScanDecoder.Decode(this, data, pos, scan);
+ }
+
+ /// Quantisation table for a component that never appeared in a scan (rendered flat).
+ public ushort[] QuantFor(JpegComponent c) => c.Quant ?? _quant[c.QuantTable] ?? new ushort[64];
+
+ /// Annex K tables for streams that omit DHT (Motion-JPEG), as libjpeg does.
+ private static JpegHuffmanTable StandardTable(bool dc, int id)
+ {
+ if (id > 1) throw new InvalidDataException("JPEG: missing Huffman table");
+ return (dc, id) switch
+ {
+ (true, 0) => _stdDcLuma ??= new JpegHuffmanTable(JpegTables.DcLumaBits, JpegTables.DcLumaValues),
+ (true, _) => _stdDcChroma ??= new JpegHuffmanTable(JpegTables.DcChromaBits, JpegTables.DcChromaValues),
+ (false, 0) => _stdAcLuma ??= new JpegHuffmanTable(JpegTables.AcLumaBits, JpegTables.AcLumaValues),
+ _ => _stdAcChroma ??= new JpegHuffmanTable(JpegTables.AcChromaBits, JpegTables.AcChromaValues),
+ };
+ }
+
+ internal static int DivUp(int a, int b) => (int)(((long)a + b - 1) / b);
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs
new file mode 100644
index 00000000..2bbe45cf
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegRenderer.cs
@@ -0,0 +1,378 @@
+using System.Buffers;
+using System.Numerics;
+using Titano.Core.Imaging;
+
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Turns decoded coefficients into pixels: (A) parallel IDCT of every block into per-component sample planes,
+/// (B) parallel bands of rows doing chroma upsampling (libjpeg "fancy" triangle filters for 2× factors,
+/// replication otherwise) and colour conversion (libjpeg's fixed-point YCbCr tables, CMYK/YCCK → RGB).
+///
+internal sealed class JpegRenderer
+{
+ private const int BandRows = 16;
+
+ private readonly JpegParser _parser;
+ private readonly JpegFrame _frame;
+ private readonly int _n;
+ private readonly bool _fancy;
+ private readonly int _max;
+ private readonly JpegColorSpace _colorSpace;
+ private readonly bool _invertedCmyk;
+ private readonly ParallelOptions _parallel;
+ private readonly byte[]?[] _planes8;
+ private readonly ushort[]?[] _planes16;
+ private readonly int[] _stride, _validW, _validH, _hf, _vf;
+
+ public JpegRenderer(JpegParser parser)
+ {
+ _parser = parser;
+ _frame = parser.Frame!;
+ var options = parser.Options;
+ _n = BlockSize(_frame, options.MaxLongEdge);
+ _fancy = options.FancyUpsampling;
+ _max = (1 << _frame.Precision) - 1;
+ _colorSpace = parser.ColorSpace();
+ _invertedCmyk = parser.AdobeTransform >= 0 || _colorSpace == JpegColorSpace.Ycck;
+ _parallel = new ParallelOptions { MaxDegreeOfParallelism = options.MaxDegreeOfParallelism };
+ Width = JpegParser.DivUp(_frame.Width * _n, 8);
+ Height = JpegParser.DivUp(_frame.Height * _n, 8);
+ Channels = _colorSpace == JpegColorSpace.Gray ? 1 : 3;
+ if (_colorSpace == JpegColorSpace.Other) throw new InvalidDataException("JPEG: component count has no colour interpretation");
+
+ var count = _frame.Components.Length;
+ _planes8 = new byte[count][];
+ _planes16 = new ushort[count][];
+ _stride = new int[count];
+ _validW = new int[count];
+ _validH = new int[count];
+ _hf = new int[count];
+ _vf = new int[count];
+ for (var i = 0; i < count; i++)
+ {
+ var c = _frame.Components[i];
+ _hf[i] = _frame.HMax / c.H;
+ _vf[i] = _frame.VMax / c.V;
+ _validW[i] = JpegParser.DivUp(_frame.Width * c.H * _n, _frame.HMax * 8);
+ _validH[i] = JpegParser.DivUp(_frame.Height * c.V * _n, _frame.VMax * 8);
+ }
+ }
+
+ public int Width { get; }
+ public int Height { get; }
+
+ /// Output channels: 1 for gray, 3 otherwise.
+ public int Channels { get; }
+
+ /// IDCT output size per block (8 = full size, 4/2/1 = DCT-domain scaling) for a requested long edge.
+ public static int BlockSize(JpegFrame frame, int maxLongEdge)
+ {
+ if (maxLongEdge <= 0) return 8;
+ var longEdge = Math.Max(frame.Width, frame.Height);
+ foreach (var n in (ReadOnlySpan)[1, 2, 4])
+ {
+ if (JpegParser.DivUp(longEdge * n, 8) >= maxLongEdge) return n;
+ }
+ return 8;
+ }
+
+ public JpegImage RenderInterleaved(JpegInfo info)
+ {
+ RunIdct();
+ var length = checked(Width * Height * Channels);
+ if (_frame.Precision <= 8)
+ {
+ var pixels = new byte[length];
+ Render((y, rows) =>
+ {
+ var dst = pixels.AsSpan(y * Width * Channels, Width * Channels);
+ for (var c = 0; c < Channels; c++)
+ {
+ var src = rows[c];
+ for (var x = 0; x < Width; x++) dst[x * Channels + c] = (byte)src[x];
+ }
+ });
+ return new JpegImage(info, Width, Height, Channels, 8, pixels, null, [.. _parser.Warnings]);
+ }
+ var pixels16 = new ushort[length];
+ Render((y, rows) =>
+ {
+ var dst = pixels16.AsSpan(y * Width * Channels, Width * Channels);
+ for (var c = 0; c < Channels; c++)
+ {
+ var src = rows[c];
+ for (var x = 0; x < Width; x++) dst[x * Channels + c] = (ushort)src[x];
+ }
+ });
+ return new JpegImage(info, Width, Height, Channels, _frame.Precision, null, pixels16, [.. _parser.Warnings]);
+ }
+
+ /// Renders straight into linear-light float planes (sRGB transfer removed by table lookup).
+ public ImageBuffer RenderLinear(bool expandGray)
+ {
+ RunIdct();
+ var lut = _frame.Precision == 8 ? null : JpegDecoder.LinearLut(_frame.Precision);
+ var outChannels = Channels == 1 && !expandGray ? 1 : 3;
+ var image = new ImageBuffer(Width, Height, outChannels, clear: false);
+ var storage = image.Storage;
+ var plane = image.PlaneLength;
+ Render((y, rows) =>
+ {
+ for (var c = 0; c < outChannels; c++)
+ {
+ var src = rows[Channels == 1 ? 0 : c];
+ var dst = storage.AsSpan(c * plane + y * Width, Width);
+ if (lut is null)
+ {
+ for (var x = 0; x < dst.Length; x++) dst[x] = ColorSpace.Linear8((byte)src[x]);
+ }
+ else
+ {
+ for (var x = 0; x < dst.Length; x++) dst[x] = lut[src[x]];
+ }
+ }
+ });
+ return image;
+ }
+
+ private void RunIdct()
+ {
+ var comps = _frame.Components;
+ var center = 1 << (_frame.Precision - 1);
+ var jobs = new List<(int Component, int BlockRow)>();
+ for (var i = 0; i < comps.Length; i++)
+ {
+ var c = comps[i];
+ _stride[i] = c.BlocksPerLine * _n;
+ var length = checked(_stride[i] * c.BlocksPerColumn * _n);
+ if (_frame.Precision <= 8) _planes8[i] = new byte[length];
+ else _planes16[i] = new ushort[length];
+ var blockRows = JpegParser.DivUp(_validH[i], _n);
+ for (var by = 0; by < blockRows; by++) jobs.Add((i, by));
+ }
+ var quant = new int[comps.Length][];
+ for (var i = 0; i < comps.Length; i++) quant[i] = Array.ConvertAll(_parser.QuantFor(comps[i]), q => (int)q);
+
+ Parallel.For(0, jobs.Count, _parallel, () => new int[64], (j, _, block) =>
+ {
+ var (i, by) = jobs[j];
+ var c = comps[i];
+ var stride = _stride[i];
+ var rowOffset = by * _n * stride;
+ if (c.Coefficients is not { } coefficients)
+ {
+ // Component never scanned: flat mid-grey, like zero coefficients.
+ if (_planes8[i] is { } flat8) flat8.AsSpan(rowOffset, _n * stride).Fill((byte)center);
+ else _planes16[i].AsSpan(rowOffset, _n * stride).Fill((ushort)center);
+ return block;
+ }
+ var blocks = JpegParser.DivUp(_validW[i], _n);
+ for (var bx = 0; bx < blocks; bx++)
+ {
+ JpegIdct.Transform(coefficients.AsSpan((by * c.BlocksPerLine + bx) * 64, 64), quant[i], _n, _frame.Precision, block);
+ var at = rowOffset + bx * _n;
+ for (var y = 0; y < _n; y++, at += stride)
+ {
+ var src = block.AsSpan(y * _n, _n);
+ if (_planes8[i] is { } p8)
+ {
+ var dst = p8.AsSpan(at, _n);
+ for (var x = 0; x < _n; x++) dst[x] = (byte)src[x];
+ }
+ else
+ {
+ var dst = _planes16[i].AsSpan(at, _n);
+ for (var x = 0; x < _n; x++) dst[x] = (ushort)src[x];
+ }
+ }
+ }
+ return block;
+ }, _ => { });
+ foreach (var c in comps) c.Coefficients = null;
+ }
+
+ private delegate void RowSink(int y, int[][] rows);
+
+ private void Render(RowSink sink)
+ {
+ var bands = JpegParser.DivUp(Height, BandRows);
+ var count = _frame.Components.Length;
+ var ycc = _colorSpace is JpegColorSpace.YCbCr or JpegColorSpace.Ycck ? YccTables.For(_frame.Precision) : null;
+ Parallel.For(0, bands, _parallel, band =>
+ {
+ var rows = new int[count][];
+ for (var c = 0; c < count; c++) rows[c] = ArrayPool.Shared.Rent(Width + 1);
+ try
+ {
+ var end = Math.Min(Height, (band + 1) * BandRows);
+ for (var y = band * BandRows; y < end; y++)
+ {
+ for (var c = 0; c < count; c++)
+ {
+ if (_planes8[c] is { } p8) Upsample(p8, c, y, rows[c]);
+ else Upsample(_planes16[c]!, c, y, rows[c]);
+ }
+ ConvertColor(rows, ycc);
+ sink(y, rows);
+ }
+ }
+ finally
+ {
+ foreach (var r in rows) ArrayPool.Shared.Return(r);
+ }
+ });
+ }
+
+ /// Writes one output row of component at full output width.
+ /// holds at least Width + 1 values, enough for the 2·w samples a 2× upsampler produces.
+ private void Upsample(T[] plane, int c, int y, int[] dst) where T : unmanaged, IBinaryInteger
+ {
+ int hf = _hf[c], vf = _vf[c], stride = _stride[c], w = _validW[c], h = _validH[c];
+ var cy = Math.Min(y / vf, h - 1);
+ var near = plane.AsSpan(cy * stride, w);
+ var width = Width;
+ if (hf == 1 && vf == 1)
+ {
+ for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x]);
+ return;
+ }
+ if (_fancy && vf == 2 && hf <= 2)
+ {
+ var upper = (y & 1) == 0;
+ var far = plane.AsSpan(Math.Clamp(upper ? cy - 1 : cy + 1, 0, h - 1) * stride, w);
+ if (hf == 1)
+ {
+ var bias = upper ? 1 : 2;
+ for (var x = 0; x < width; x++) dst[x] = (3 * int.CreateTruncating(near[x]) + int.CreateTruncating(far[x]) + bias) >> 2;
+ return;
+ }
+ if (w > 2)
+ {
+ H2V2(near, far, w, dst);
+ return;
+ }
+ }
+ if (_fancy && hf == 2 && vf == 1 && w > 2)
+ {
+ H2V1(near, w, dst);
+ return;
+ }
+ for (var x = 0; x < width; x++) dst[x] = int.CreateTruncating(near[x / hf]);
+ }
+
+ /// libjpeg h2v1_fancy_upsample: 3/4·nearer + 1/4·further, alternating rounding bias.
+ private static void H2V1(ReadOnlySpan s, int w, Span o) where T : unmanaged, IBinaryInteger
+ {
+ var first = int.CreateTruncating(s[0]);
+ o[0] = first;
+ o[1] = (3 * first + int.CreateTruncating(s[1]) + 2) >> 2;
+ for (var i = 1; i < w - 1; i++)
+ {
+ var v = 3 * int.CreateTruncating(s[i]);
+ o[2 * i] = (v + int.CreateTruncating(s[i - 1]) + 1) >> 2;
+ o[2 * i + 1] = (v + int.CreateTruncating(s[i + 1]) + 2) >> 2;
+ }
+ var last = int.CreateTruncating(s[w - 1]);
+ o[2 * w - 2] = (3 * last + int.CreateTruncating(s[w - 2]) + 1) >> 2;
+ o[2 * w - 1] = last;
+ }
+
+ /// libjpeg h2v2_fancy_upsample: triangle filter in both directions (9/3/3/1 weights).
+ private static void H2V2(ReadOnlySpan near, ReadOnlySpan far, int w, Span o) where T : unmanaged, IBinaryInteger
+ {
+ var thisSum = 3 * int.CreateTruncating(near[0]) + int.CreateTruncating(far[0]);
+ var nextSum = 3 * int.CreateTruncating(near[1]) + int.CreateTruncating(far[1]);
+ o[0] = (thisSum * 4 + 8) >> 4;
+ o[1] = (thisSum * 3 + nextSum + 7) >> 4;
+ var lastSum = thisSum;
+ thisSum = nextSum;
+ for (var i = 1; i < w - 1; i++)
+ {
+ nextSum = 3 * int.CreateTruncating(near[i + 1]) + int.CreateTruncating(far[i + 1]);
+ o[2 * i] = (thisSum * 3 + lastSum + 8) >> 4;
+ o[2 * i + 1] = (thisSum * 3 + nextSum + 7) >> 4;
+ lastSum = thisSum;
+ thisSum = nextSum;
+ }
+ o[2 * w - 2] = (thisSum * 3 + lastSum + 8) >> 4;
+ o[2 * w - 1] = (thisSum * 4 + 7) >> 4;
+ }
+
+ private void ConvertColor(int[][] rows, YccTables? ycc)
+ {
+ var w = Width;
+ var max = _max;
+ switch (_colorSpace)
+ {
+ case JpegColorSpace.YCbCr:
+ YccToRgb(rows, ycc!, w, max);
+ break;
+ case JpegColorSpace.Cmyk or JpegColorSpace.Ycck:
+ {
+ if (_colorSpace == JpegColorSpace.Ycck)
+ {
+ YccToRgb(rows, ycc!, w, max);
+ for (var c = 0; c < 3; c++)
+ {
+ var r = rows[c];
+ for (var x = 0; x < w; x++) r[x] = max - r[x];
+ }
+ }
+ var k = rows[3];
+ var half = max / 2;
+ for (var c = 0; c < 3; c++)
+ {
+ var r = rows[c];
+ for (var x = 0; x < w; x++)
+ {
+ r[x] = _invertedCmyk ? (r[x] * k[x] + half) / max : ((max - r[x]) * (max - k[x]) + half) / max;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ private static void YccToRgb(int[][] rows, YccTables t, int w, int max)
+ {
+ int[] y = rows[0], cb = rows[1], cr = rows[2];
+ for (var x = 0; x < w; x++)
+ {
+ int yy = y[x], b = cb[x], r = cr[x];
+ y[x] = Math.Clamp(yy + t.CrR[r], 0, max);
+ cb[x] = Math.Clamp(yy + ((t.CbG[b] + t.CrG[r]) >> 16), 0, max);
+ cr[x] = Math.Clamp(yy + t.CbB[b], 0, max);
+ }
+ }
+
+ /// libjpeg's fixed-point (16 fractional bits) YCbCr → RGB tables for a sample precision.
+ private sealed class YccTables
+ {
+ private static readonly YccTables?[] Cache = new YccTables?[17];
+ public readonly int[] CrR, CbB, CrG, CbG;
+
+ private YccTables(int precision)
+ {
+ var size = 1 << precision;
+ var center = size / 2;
+ CrR = new int[size];
+ CbB = new int[size];
+ CrG = new int[size];
+ CbG = new int[size];
+ const int half = 1 << 15;
+ for (var i = 0; i < size; i++)
+ {
+ var x = i - center;
+ CrR[i] = (Fix(1.40200) * x + half) >> 16;
+ CbB[i] = (Fix(1.77200) * x + half) >> 16;
+ CrG[i] = -Fix(0.71414) * x;
+ CbG[i] = -Fix(0.34414) * x + half;
+ }
+ }
+
+ public static YccTables For(int precision) => Cache[precision] ??= new YccTables(precision);
+
+ private static int Fix(double v) => (int)(v * 65536 + 0.5);
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs
new file mode 100644
index 00000000..3bd8b679
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegScanDecoder.cs
@@ -0,0 +1,255 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+///
+/// Entropy decoding of DCT scans into the components' coefficient arrays: sequential (baseline/extended) and the
+/// four progressive scan kinds (DC first/refine, AC first/refine). Corrupt intervals are skipped by resynchronising
+/// on the next RSTn marker; without restart markers the rest of the scan is abandoned with a warning.
+///
+internal static class JpegScanDecoder
+{
+ private enum Kind
+ {
+ Sequential,
+ DcFirst,
+ DcRefine,
+ AcFirst,
+ AcRefine,
+ }
+
+ public static int Decode(JpegParser parser, ReadOnlySpan data, int pos, JpegScan scan)
+ {
+ var frame = parser.Frame!;
+ var comps = scan.Components;
+ var kind = frame.Process != JpegProcess.Progressive ? Kind.Sequential
+ : scan.Ss == 0 ? (scan.Ah == 0 ? Kind.DcFirst : Kind.DcRefine)
+ : (scan.Ah == 0 ? Kind.AcFirst : Kind.AcRefine);
+
+ var single = comps.Length == 1;
+ var mcusX = single ? comps[0].WidthInBlocks : frame.McusX;
+ var mcusY = single ? comps[0].HeightInBlocks : frame.McusY;
+ var total = (long)mcusX * mcusY;
+ var interval = parser.RestartInterval;
+ var reader = new JpegBitReader(data, pos);
+ var state = new ScanState(scan);
+ var expectedRst = 0;
+ foreach (var c in comps) c.DcPred = 0;
+
+ long mcu = 0;
+ while (mcu < total)
+ {
+ var end = interval > 0 ? Math.Min(total, mcu + interval) : total;
+ try
+ {
+ for (; mcu < end; mcu++)
+ {
+ if (single)
+ {
+ var c = comps[0];
+ var bx = (int)(mcu % mcusX);
+ var by = (int)(mcu / mcusX);
+ DecodeBlock(ref reader, kind, c, (by * c.BlocksPerLine + bx) * 64, 0, ref state);
+ }
+ else
+ {
+ var mx = (int)(mcu % mcusX);
+ var my = (int)(mcu / mcusX);
+ for (var i = 0; i < comps.Length; i++)
+ {
+ var c = comps[i];
+ for (var v = 0; v < c.V; v++)
+ {
+ var row = (my * c.V + v) * c.BlocksPerLine + mx * c.H;
+ for (var h = 0; h < c.H; h++) DecodeBlock(ref reader, kind, c, (row + h) * 64, i, ref state);
+ }
+ }
+ }
+ if (reader.Overrun) throw new JpegEntropyException("JPEG: premature end of entropy-coded data");
+ }
+ }
+ catch (JpegEntropyException ex)
+ {
+ parser.Warn(ex.Message);
+ if (interval == 0) break;
+ mcu = end;
+ }
+ if (mcu >= total || interval == 0) break;
+
+ if (!reader.NextRestart(ref expectedRst, out var lost))
+ {
+ parser.Warn("JPEG: restart marker missing; scan truncated");
+ break;
+ }
+ if (lost > 0)
+ {
+ // Intervals between the expected and the found marker were lost: leave their samples untouched.
+ parser.Warn($"JPEG: {lost} restart interval(s) lost");
+ mcu += (long)lost * interval;
+ }
+ state.EobRun = 0;
+ foreach (var c in comps) c.DcPred = 0;
+ }
+ return reader.Position;
+ }
+
+ private struct ScanState(JpegScan scan)
+ {
+ public readonly JpegScan Scan = scan;
+ public int EobRun;
+ }
+
+ private static void DecodeBlock(ref JpegBitReader r, Kind kind, JpegComponent c, int offset, int index, ref ScanState state)
+ {
+ var block = c.Coefficients.AsSpan(offset, 64);
+ var scan = state.Scan;
+ switch (kind)
+ {
+ case Kind.Sequential:
+ DecodeSequential(ref r, block, scan.DcTables[index]!, scan.AcTables[index]!, ref c.DcPred);
+ break;
+ case Kind.DcFirst:
+ {
+ var t = r.Decode(scan.DcTables[index]!);
+ if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude");
+ c.DcPred += t == 0 ? 0 : r.Receive(t);
+ block[0] = (short)(c.DcPred * (1 << scan.Al));
+ break;
+ }
+ case Kind.DcRefine:
+ if (r.ReadBit() != 0) block[0] |= (short)(1 << scan.Al);
+ break;
+ case Kind.AcFirst:
+ DecodeAcFirst(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun);
+ break;
+ default:
+ DecodeAcRefine(ref r, block, scan.AcTables[index]!, scan.Ss, scan.Se, scan.Al, ref state.EobRun);
+ break;
+ }
+ }
+
+ private static void DecodeSequential(ref JpegBitReader r, Span block, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int pred)
+ {
+ var t = r.Decode(dc);
+ if (t > 16) throw new JpegEntropyException("JPEG: bad DC magnitude");
+ pred += t == 0 ? 0 : r.Receive(t);
+ block[0] = (short)pred;
+ var order = JpegTables.NaturalOrder;
+ var fastAc = ac.FastAc;
+ var k = 1;
+ while (k < 64)
+ {
+ r.Ensure(16);
+ var fast = fastAc[r.Peek(JpegHuffmanTable.FastBits)];
+ if (fast != 0)
+ {
+ k += (fast >> 8) & 15;
+ r.Consume(fast & 0xFF);
+ if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
+ block[order[k++]] = (short)(fast >> 16);
+ continue;
+ }
+ var rs = r.Decode(ac);
+ int run = rs >> 4, s = rs & 15;
+ if (s == 0)
+ {
+ if (run != 15) break;
+ k += 16;
+ continue;
+ }
+ k += run;
+ if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
+ block[order[k++]] = (short)r.Receive(s);
+ }
+ }
+
+ private static void DecodeAcFirst(ref JpegBitReader r, Span block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun)
+ {
+ if (eobRun > 0)
+ {
+ eobRun--;
+ return;
+ }
+ var order = JpegTables.NaturalOrder;
+ for (var k = ss; k <= se;)
+ {
+ var rs = r.Decode(ac);
+ int run = rs >> 4, s = rs & 15;
+ if (s == 0)
+ {
+ if (run < 15)
+ {
+ eobRun = (1 << run) - 1;
+ if (run > 0) eobRun += r.ReadBits(run);
+ return;
+ }
+ k += 16;
+ continue;
+ }
+ k += run;
+ if (k > 63) throw new JpegEntropyException("JPEG: coefficient index out of range");
+ block[order[k++]] = (short)(r.Receive(s) * (1 << al));
+ }
+ }
+
+ /// AC successive-approximation refinement (T.81 G.1.2.3), following libjpeg's decode_mcu_AC_refine.
+ private static void DecodeAcRefine(ref JpegBitReader r, Span block, JpegHuffmanTable ac, int ss, int se, int al, ref int eobRun)
+ {
+ var order = JpegTables.NaturalOrder;
+ var p1 = (short)(1 << al);
+ var m1 = (short)(-1 << al);
+ var k = ss;
+ if (eobRun == 0)
+ {
+ for (; k <= se; k++)
+ {
+ var rs = r.Decode(ac);
+ int run = rs >> 4, s = rs & 15;
+ short value = 0;
+ if (s != 0)
+ {
+ if (s != 1) throw new JpegEntropyException("JPEG: bad refinement magnitude");
+ value = r.ReadBit() != 0 ? p1 : m1;
+ }
+ else if (run != 15)
+ {
+ eobRun = 1 << run;
+ if (run > 0) eobRun += r.ReadBits(run);
+ break;
+ }
+ // Skip `run` still-zero coefficients, refining the non-zero ones passed on the way.
+ for (; k <= se; k++)
+ {
+ ref var coef = ref block[order[k]];
+ if (coef != 0)
+ {
+ RefineBit(ref r, ref coef, p1, m1);
+ }
+ else
+ {
+ if (run == 0) break;
+ run--;
+ }
+ }
+ if (value != 0)
+ {
+ if (k > se) throw new JpegEntropyException("JPEG: refinement beyond spectral band");
+ block[order[k]] = value;
+ }
+ }
+ }
+ if (eobRun > 0)
+ {
+ for (; k <= se; k++)
+ {
+ ref var coef = ref block[order[k]];
+ if (coef != 0) RefineBit(ref r, ref coef, p1, m1);
+ }
+ eobRun--;
+ }
+ }
+
+ private static void RefineBit(ref JpegBitReader r, ref short coef, short p1, short m1)
+ {
+ if (r.ReadBit() == 0 || (coef & p1) != 0) return;
+ coef += coef >= 0 ? p1 : m1;
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegTables.cs b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs
new file mode 100644
index 00000000..78224a03
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegTables.cs
@@ -0,0 +1,96 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+/// Constants shared by the JPEG encoder and decoders (ITU T.81 Annex K).
+internal static class JpegTables
+{
+ public const byte Soi = 0xD8, Eoi = 0xD9, Sos = 0xDA, Dqt = 0xDB, Dri = 0xDD, Dht = 0xC4, Dac = 0xCC;
+ public const byte Sof0 = 0xC0, Sof1 = 0xC1, Sof2 = 0xC2, Sof3 = 0xC3, Rst0 = 0xD0, App0 = 0xE0, App1 = 0xE1, App14 = 0xEE;
+
+ /// Natural (row-major) index of the coefficient at each zig-zag position.
+ public static ReadOnlySpan NaturalOrder =>
+ [
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
+ ];
+
+ /// Annex K.1 luminance quantisation table, natural order.
+ public static ReadOnlySpan LumaQuant =>
+ [
+ 16, 11, 10, 16, 24, 40, 51, 61,
+ 12, 12, 14, 19, 26, 58, 60, 55,
+ 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62,
+ 18, 22, 37, 56, 68, 109, 103, 77,
+ 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101,
+ 72, 92, 95, 98, 112, 100, 103, 99,
+ ];
+
+ /// Annex K.1 chrominance quantisation table, natural order.
+ public static ReadOnlySpan ChromaQuant =>
+ [
+ 17, 18, 24, 47, 99, 99, 99, 99,
+ 18, 21, 26, 66, 99, 99, 99, 99,
+ 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ ];
+
+ public static ReadOnlySpan DcLumaBits => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
+ public static ReadOnlySpan DcLumaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+ public static ReadOnlySpan DcChromaBits => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
+ public static ReadOnlySpan DcChromaValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+ public static ReadOnlySpan AcLumaBits => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
+
+ public static ReadOnlySpan AcLumaValues =>
+ [
+ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
+ 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
+ 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
+ 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+ 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
+ 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
+ 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa,
+ ];
+
+ public static ReadOnlySpan AcChromaBits => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
+
+ public static ReadOnlySpan AcChromaValues =>
+ [
+ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
+ 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
+ 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
+ 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
+ 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
+ 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
+ 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+ 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa,
+ ];
+
+ /// Orthonormal 8-point DCT basis: Basis[u * 8 + x] = c(u)/2 · cos((2x+1)uπ/16).
+ public static readonly float[] Basis = BuildBasis(8);
+
+ /// DCT basis of an n-point reduced IDCT evaluated with 8-point normalisation (DCT-domain scaling).
+ public static float[] BuildBasis(int n)
+ {
+ var b = new float[n * n];
+ for (var u = 0; u < n; u++)
+ {
+ var cu = u == 0 ? Math.Sqrt(0.5) : 1.0;
+ for (var x = 0; x < n; x++) b[u * n + x] = (float)(cu / 2 * Math.Cos((2 * x + 1) * u * Math.PI / (2 * n)));
+ }
+ return b;
+ }
+}
diff --git a/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs b/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs
new file mode 100644
index 00000000..a8514b3b
--- /dev/null
+++ b/src/Titano.Core/Codecs/Jpeg/JpegTypes.cs
@@ -0,0 +1,153 @@
+namespace Titano.Core.Codecs.Jpeg;
+
+/// JPEG coding process declared by the SOF marker.
+public enum JpegProcess
+{
+ /// SOF0: baseline sequential DCT, 8-bit, at most two Huffman tables per class.
+ Baseline,
+
+ /// SOF1: extended sequential DCT (8 or 12-bit).
+ ExtendedSequential,
+
+ /// SOF2: progressive DCT (spectral selection and successive approximation).
+ Progressive,
+
+ /// SOF3: lossless predictive coding (2–16 bit).
+ Lossless,
+}
+
+/// Colour space of the encoded components.
+public enum JpegColorSpace
+{
+ Gray,
+ YCbCr,
+ Rgb,
+ Cmyk,
+ Ycck,
+
+ /// No defined colour interpretation (e.g. two-component lossless raw tiles).
+ Other,
+}
+
+/// Overrides the colour interpretation of a 3- or 4-component stream (TIFF knows it out of band).
+public enum JpegColorTransform
+{
+ /// JFIF/Adobe markers and component ids decide (libjpeg rules).
+ Auto,
+
+ /// Components are stored as-is (RGB or CMYK).
+ None,
+
+ /// Components are YCbCr (or YCCK for four components).
+ YCbCr,
+}
+
+/// Frame facts from the headers, available without decoding pixels.
+/// Full image width in pixels.
+/// Full image height in pixels.
+/// Number of encoded components (1–4).
+/// Sample precision in bits (8 or 12 for DCT, 2–16 for lossless).
+/// Coding process.
+/// Colour space the decoder will assume.
+/// Horizontal and vertical sampling factors per component.
+/// Restart interval in MCUs declared before the first scan (0 = none).
+public sealed record JpegInfo(
+ int Width,
+ int Height,
+ int Components,
+ int Precision,
+ JpegProcess Process,
+ JpegColorSpace ColorSpace,
+ IReadOnlyList<(int H, int V)> Sampling,
+ int RestartInterval)
+{
+ /// Chroma subsampling in J:a:b notation for three-component images ("4:2:0"), otherwise a factor list.
+ public string SamplingNotation
+ {
+ get
+ {
+ if (Sampling.Count == 3 && Sampling[1] == Sampling[2] && Sampling[1] == (1, 1))
+ {
+ return Sampling[0] switch
+ {
+ (1, 1) => "4:4:4",
+ (2, 1) => "4:2:2",
+ (2, 2) => "4:2:0",
+ (1, 2) => "4:4:0",
+ (4, 1) => "4:1:1",
+ (4, 2) => "4:1:0",
+ _ => Factors(),
+ };
+ }
+ return Factors();
+ }
+ }
+
+ private string Factors() => string.Join(",", Sampling.Select(s => $"{s.H}x{s.V}"));
+}
+
+/// Options for .
+public sealed record JpegDecodeOptions
+{
+ /// Default options: full size, fancy upsampling, automatic colour transform.
+ public static JpegDecodeOptions Default { get; } = new();
+
+ /// When > 0, decode with the smallest DCT-domain reduction (1/2, 1/4, 1/8) whose long edge is still
+ /// ≥ this value. 0 decodes at full size. Ignored for lossless streams.
+ public int MaxLongEdge { get; init; }
+
+ /// Triangle-filter chroma upsampling (libjpeg "fancy"); false replicates chroma samples.
+ public bool FancyUpsampling { get; init; } = true;
+
+ /// Colour interpretation override (TIFF photometric).
+ public JpegColorTransform ColorTransform { get; init; } = JpegColorTransform.Auto;
+
+ /// Abbreviated table-specification stream (TIFF JPEGTables) parsed before the image stream.
+ public byte[]? Tables { get; init; }
+
+ /// Upper bound on width × height; larger frames are rejected before any allocation.
+ public long MaxPixels { get; init; } = 1L << 28;
+
+ /// Worker limit for the IDCT and colour stages (-1 = all cores, 1 = single-threaded).
+ public int MaxDegreeOfParallelism { get; init; } = -1;
+}
+
+/// Decoded JPEG pixels, interleaved, top-down, Exif orientation not applied.
+public sealed class JpegImage
+{
+ internal JpegImage(JpegInfo info, int width, int height, int components, int bitDepth, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList warnings)
+ {
+ Info = info;
+ Width = width;
+ Height = height;
+ Components = components;
+ BitDepth = bitDepth;
+ Pixels8 = pixels8;
+ Pixels16 = pixels16;
+ Warnings = warnings;
+ }
+
+ /// Header facts of the source stream (full-size dimensions).
+ public JpegInfo Info { get; }
+
+ /// Output width (smaller than when DCT scaling was used).
+ public int Width { get; }
+
+ public int Height { get; }
+
+ /// Output channels: 1 (gray) or 3 (RGB; CMYK/YCCK are converted).
+ public int Components { get; }
+
+ /// Significant bits per sample: 8 → ; more → with values 0..2^BitDepth−1.
+ public int BitDepth { get; }
+
+ public byte[]? Pixels8 { get; }
+
+ public ushort[]? Pixels16 { get; }
+
+ /// Recoverable problems (corrupt entropy data, missing restart markers, truncation).
+ public IReadOnlyList Warnings { get; }
+}
+
+/// Raw samples of a lossless (SOF3) stream as encoded: interleaved, as in the frame header.
+public readonly record struct JpegLosslessImage(ushort[] Samples, int Width, int Height, int Components, int Precision);
diff --git a/src/Titano.Core/Codecs/Png/PngDecoder.cs b/src/Titano.Core/Codecs/Png/PngDecoder.cs
new file mode 100644
index 00000000..72d74a2e
--- /dev/null
+++ b/src/Titano.Core/Codecs/Png/PngDecoder.cs
@@ -0,0 +1,359 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Titano.Core.Hashing;
+using Titano.Core.Imaging;
+
+namespace Titano.Core.Codecs.Png;
+
+/// IHDR facts of a PNG stream.
+public sealed record PngInfo(int Width, int Height, int BitDepth, PngColorType ColorType, bool Interlaced);
+
+/// Decoded PNG pixels: interleaved, top-down, palette and tRNS expanded.
+public sealed class PngImage
+{
+ internal PngImage(PngInfo info, int channels, byte[]? pixels8, ushort[]? pixels16, IReadOnlyList warnings)
+ {
+ Info = info;
+ Channels = channels;
+ Pixels8 = pixels8;
+ Pixels16 = pixels16;
+ Warnings = warnings;
+ }
+
+ public PngInfo Info { get; }
+ public int Width => Info.Width;
+ public int Height => Info.Height;
+
+ /// 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA (palette → RGB/RGBA; tRNS adds alpha).
+ public int Channels { get; }
+
+ /// 8 (; 1/2/4-bit gray is scaled to 0..255) or 16 ().
+ public int BitDepth => Pixels16 is null ? 8 : 16;
+
+ public byte[]? Pixels8 { get; }
+ public ushort[]? Pixels16 { get; }
+
+ /// Recoverable problems (CRC mismatches, truncated or corrupt image data, unknown critical chunks).
+ public IReadOnlyList Warnings { get; }
+}
+
+///
+/// PNG decoder: every colour type and bit depth (1/2/4/8/16), PLTE + tRNS, Adam7, all five filters, zlib through
+/// . CRC mismatches are tolerated with a warning; damaged image data yields the rows decoded so
+/// far plus a warning. Ancillary colour chunks (gAMA, iCCP, cHRM) are ignored: samples are taken as sRGB.
+///
+public static class PngDecoder
+{
+ private static ReadOnlySpan Signature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
+
+ private static readonly (int X, int Y, int Dx, int Dy)[] Adam7 =
+ [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)];
+
+ public static PngInfo ReadInfo(ReadOnlySpan data)
+ {
+ if (data.Length < 33 || !data.StartsWith(Signature) || !data.Slice(12, 4).SequenceEqual("IHDR"u8))
+ throw new InvalidDataException("PNG: missing signature or IHDR");
+ return ParseHeader(data.Slice(16, 13));
+ }
+
+ /// Upper bound on width × height, checked before allocation.
+ public static PngImage Decode(ReadOnlySpan data, long maxPixels = 1L << 28)
+ {
+ var info = ReadInfo(data);
+ if ((long)info.Width * info.Height > maxPixels) throw new InvalidDataException($"PNG: {info.Width}x{info.Height} exceeds the pixel limit");
+ var warnings = new List();
+ byte[]? palette = null;
+ byte[]? trns = null;
+ using var idat = new MemoryStream();
+ var pos = 8;
+ var ended = false;
+ while (pos + 8 <= data.Length)
+ {
+ var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
+ var type = data.Slice(pos + 4, 4);
+ if (length > int.MaxValue || pos + 12 + (long)length > data.Length)
+ {
+ warnings.Add("PNG: truncated chunk");
+ break;
+ }
+ var body = data.Slice(pos + 8, (int)length);
+ var crc = BinaryPrimitives.ReadUInt32BigEndian(data[(pos + 8 + (int)length)..]);
+ if (Crc32.Compute(data.Slice(pos + 4, 4 + (int)length)) != crc) warnings.Add($"PNG: CRC mismatch in {Name(type)}");
+ pos += 12 + (int)length;
+ if (type.SequenceEqual("IDAT"u8))
+ {
+ idat.Write(body);
+ }
+ else if (type.SequenceEqual("PLTE"u8))
+ {
+ if (body.Length % 3 != 0 || body.Length > 768 || body.Length == 0) throw new InvalidDataException("PNG: bad PLTE");
+ palette = body.ToArray();
+ }
+ else if (type.SequenceEqual("tRNS"u8))
+ {
+ trns = body.ToArray();
+ }
+ else if (type.SequenceEqual("IEND"u8))
+ {
+ ended = true;
+ break;
+ }
+ else if (!type.SequenceEqual("IHDR"u8) && (type[0] & 0x20) == 0)
+ {
+ warnings.Add($"PNG: unknown critical chunk {Name(type)} ignored");
+ }
+ }
+ if (!ended) warnings.Add("PNG: missing IEND");
+ if (idat.Length == 0) throw new InvalidDataException("PNG: no image data");
+ if (info.ColorType == PngColorType.Palette && palette is null) throw new InvalidDataException("PNG: palette image without PLTE");
+
+ var layout = Layout.For(info, palette, trns);
+ idat.Position = 0;
+ using var z = new ZLibStream(idat, CompressionMode.Decompress);
+ return layout.Sixteen ? Decode16(info, layout, z, warnings) : Decode8(info, layout, z, warnings);
+ }
+
+ /// Decodes into a linear-light buffer (samples are sRGB-encoded; alpha stays linear).
+ /// Return gray as three identical channels.
+ /// Keep alpha as a fourth channel (gray is then expanded).
+ public static ImageBuffer DecodeToLinear(ReadOnlySpan data, bool expandGray = false, bool keepAlpha = false)
+ {
+ var image = Decode(data);
+ var gray = image.Channels <= 2;
+ var hasAlpha = image.Channels is 2 or 4;
+ var output = keepAlpha && hasAlpha ? 4 : gray && !expandGray ? 1 : 3;
+ return image.Pixels8 is { } p8
+ ? PixelConvert.FromInterleaved8(p8, image.Width, image.Height, image.Channels, outputChannels: output)
+ : PixelConvert.FromInterleaved16(image.Pixels16, image.Width, image.Height, image.Channels, outputChannels: output);
+ }
+
+ private static string Name(ReadOnlySpan type) => string.Create(4, type.ToArray(), (s, t) =>
+ {
+ for (var i = 0; i < 4; i++) s[i] = t[i] is >= 32 and < 127 ? (char)t[i] : '?';
+ });
+
+ private static PngInfo ParseHeader(ReadOnlySpan h)
+ {
+ var width = BinaryPrimitives.ReadUInt32BigEndian(h);
+ var height = BinaryPrimitives.ReadUInt32BigEndian(h[4..]);
+ int depth = h[8], type = h[9];
+ if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) throw new InvalidDataException("PNG: bad dimensions");
+ var valid = type switch
+ {
+ 0 => depth is 1 or 2 or 4 or 8 or 16,
+ 3 => depth is 1 or 2 or 4 or 8,
+ 2 or 4 or 6 => depth is 8 or 16,
+ _ => false,
+ };
+ if (!valid) throw new InvalidDataException($"PNG: invalid colour type {type} / bit depth {depth}");
+ if (h[10] != 0 || h[11] != 0 || h[12] > 1) throw new InvalidDataException("PNG: unsupported compression, filter or interlace method");
+ return new PngInfo((int)width, (int)height, depth, (PngColorType)type, h[12] == 1);
+ }
+
+ /// Sample geometry of the stored scanlines and of the expanded output.
+ private sealed class Layout
+ {
+ public int SourceChannels, BitsPerPixel, BytesPerPixel, OutChannels;
+ public bool Sixteen;
+ public byte[]? Palette;
+ public byte[]? PaletteAlpha;
+
+ /// tRNS colour key in source sample units (gray: 1 value, RGB: 3), or null.
+ public int[]? Key;
+
+ public static Layout For(PngInfo info, byte[]? palette, byte[]? trns)
+ {
+ var l = new Layout
+ {
+ SourceChannels = info.ColorType switch
+ {
+ PngColorType.Gray or PngColorType.Palette => 1,
+ PngColorType.GrayAlpha => 2,
+ PngColorType.Rgb => 3,
+ _ => 4,
+ },
+ Sixteen = info.BitDepth == 16,
+ };
+ l.BitsPerPixel = l.SourceChannels * info.BitDepth;
+ l.BytesPerPixel = Math.Max(1, l.BitsPerPixel / 8);
+ l.OutChannels = l.SourceChannels;
+ switch (info.ColorType)
+ {
+ case PngColorType.Palette:
+ l.Palette = palette;
+ l.OutChannels = 3;
+ if (trns is { Length: > 0 })
+ {
+ l.PaletteAlpha = new byte[256];
+ Array.Fill(l.PaletteAlpha, (byte)255);
+ trns.AsSpan(0, Math.Min(trns.Length, 256)).CopyTo(l.PaletteAlpha);
+ l.OutChannels = 4;
+ }
+ break;
+ case PngColorType.Gray when trns is { Length: >= 2 }:
+ l.Key = [trns[0] << 8 | trns[1]];
+ l.OutChannels = 2;
+ break;
+ case PngColorType.Rgb when trns is { Length: >= 6 }:
+ l.Key = [trns[0] << 8 | trns[1], trns[2] << 8 | trns[3], trns[4] << 8 | trns[5]];
+ l.OutChannels = 4;
+ break;
+ }
+ return l;
+ }
+ }
+
+ private static PngImage Decode8(PngInfo info, Layout l, Stream z, List warnings)
+ {
+ var pixels = new byte[checked((long)info.Width * info.Height * l.OutChannels)];
+ var row = new byte[info.Width * l.OutChannels];
+ Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
+ {
+ Expand8(raw, info.BitDepth, count, l, row);
+ for (int i = 0, x = x0; i < count; i++, x += dx)
+ {
+ row.AsSpan(i * l.OutChannels, l.OutChannels).CopyTo(pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels)));
+ }
+ });
+ return new PngImage(info, l.OutChannels, pixels, null, warnings);
+ }
+
+ private static PngImage Decode16(PngInfo info, Layout l, Stream z, List warnings)
+ {
+ var pixels = new ushort[checked((long)info.Width * info.Height * l.OutChannels)];
+ Inflate(info, l, z, warnings, (raw, y, x0, dx, count) =>
+ {
+ for (int i = 0, x = x0; i < count; i++, x += dx)
+ {
+ var dst = pixels.AsSpan((int)(((long)y * info.Width + x) * l.OutChannels), l.OutChannels);
+ var transparent = l.Key is not null;
+ for (var c = 0; c < l.SourceChannels; c++)
+ {
+ dst[c] = BinaryPrimitives.ReadUInt16BigEndian(raw[((i * l.SourceChannels + c) * 2)..]);
+ if (l.Key is not null && dst[c] != l.Key[c]) transparent = false;
+ }
+ if (l.Key is not null) dst[l.SourceChannels] = transparent ? (ushort)0 : ushort.MaxValue;
+ }
+ });
+ return new PngImage(info, l.OutChannels, null, pixels, warnings);
+ }
+
+ private delegate void RowHandler(ReadOnlySpan raw, int y, int x0, int dx, int count);
+
+ /// Streams every (pass,) row out of zlib, unfilters it and hands the raw samples to .
+ private static void Inflate(PngInfo info, Layout l, Stream z, List warnings, RowHandler handle)
+ {
+ var passes = info.Interlaced ? Adam7 : [(0, 0, 1, 1)];
+ var maxRow = (int)(((long)info.Width * l.BitsPerPixel + 7) / 8);
+ var line = new byte[maxRow + 1];
+ var prior = new byte[maxRow];
+ try
+ {
+ foreach (var (px, py, dx, dy) in passes)
+ {
+ if (px >= info.Width || py >= info.Height) continue;
+ var count = (info.Width - px + dx - 1) / dx;
+ var rowBytes = (int)(((long)count * l.BitsPerPixel + 7) / 8);
+ Array.Clear(prior);
+ for (var y = py; y < info.Height; y += dy)
+ {
+ var buffer = line.AsSpan(0, rowBytes + 1);
+ if (z.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) < buffer.Length)
+ {
+ warnings.Add("PNG: image data truncated");
+ return;
+ }
+ if (buffer[0] > 4)
+ {
+ warnings.Add($"PNG: invalid filter type {buffer[0]}");
+ return;
+ }
+ var row = buffer[1..];
+ Unfilter(buffer[0], row, prior.AsSpan(0, rowBytes), l.BytesPerPixel);
+ handle(row, y, px, dx, count);
+ row.CopyTo(prior);
+ }
+ }
+ }
+ catch (InvalidDataException ex)
+ {
+ warnings.Add("PNG: corrupt image data: " + ex.Message);
+ }
+ }
+
+ private static void Unfilter(int filter, Span row, ReadOnlySpan prior, int bpp)
+ {
+ switch (filter)
+ {
+ case 1:
+ for (var i = bpp; i < row.Length; i++) row[i] += row[i - bpp];
+ break;
+ case 2:
+ for (var i = 0; i < row.Length; i++) row[i] += prior[i];
+ break;
+ case 3:
+ for (var i = 0; i < bpp && i < row.Length; i++) row[i] += (byte)(prior[i] >> 1);
+ for (var i = bpp; i < row.Length; i++) row[i] += (byte)((row[i - bpp] + prior[i]) >> 1);
+ break;
+ case 4:
+ for (var i = 0; i < bpp && i < row.Length; i++) row[i] += prior[i];
+ for (var i = bpp; i < row.Length; i++) row[i] += (byte)PngEncoder.Paeth(row[i - bpp], prior[i], prior[i - bpp]);
+ break;
+ }
+ }
+
+ /// Expands one row of ≤ 8-bit samples (sub-byte gray, palette, tRNS key) to 8-bit output channels.
+ private static void Expand8(ReadOnlySpan raw, int depth, int count, Layout l, Span dst)
+ {
+ var oc = l.OutChannels;
+ if (depth == 8 && l.Palette is null && l.Key is null)
+ {
+ raw[..(count * oc)].CopyTo(dst);
+ return;
+ }
+ if (depth == 8 && l.Key is not null)
+ {
+ var sc = l.SourceChannels;
+ for (var i = 0; i < count; i++)
+ {
+ var opaque = false;
+ for (var c = 0; c < sc; c++)
+ {
+ var v = raw[i * sc + c];
+ dst[i * oc + c] = v;
+ if (v != l.Key[c]) opaque = true;
+ }
+ dst[i * oc + sc] = opaque ? (byte)255 : (byte)0;
+ }
+ return;
+ }
+ // Sub-byte or palette: one sample per pixel, MSB first.
+ var mask = (1 << depth) - 1;
+ var scale = l.Palette is null ? 255 / mask : 1;
+ for (var i = 0; i < count; i++)
+ {
+ var bit = i * depth;
+ var v = (raw[bit >> 3] >> (8 - depth - (bit & 7))) & mask;
+ if (l.Palette is { } pal)
+ {
+ var o = dst.Slice(i * oc, oc);
+ if (3 * v + 2 < pal.Length)
+ {
+ o[0] = pal[3 * v];
+ o[1] = pal[3 * v + 1];
+ o[2] = pal[3 * v + 2];
+ }
+ else
+ {
+ o[..3].Clear(); // out-of-range index: black, as libpng
+ }
+ if (oc == 4) o[3] = l.PaletteAlpha![v];
+ }
+ else
+ {
+ dst[i * oc] = (byte)(v * scale);
+ if (l.Key is not null) dst[i * oc + 1] = v == l.Key[0] ? (byte)0 : (byte)255;
+ }
+ }
+ }
+}
diff --git a/src/Titano.Core/Codecs/Png/PngEncoder.cs b/src/Titano.Core/Codecs/Png/PngEncoder.cs
index 6c9273fc..3fc68112 100644
--- a/src/Titano.Core/Codecs/Png/PngEncoder.cs
+++ b/src/Titano.Core/Codecs/Png/PngEncoder.cs
@@ -1,14 +1,16 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Hashing;
+using Titano.Core.Imaging;
namespace Titano.Core.Codecs.Png;
-/// PNG colour types written by .
+/// PNG colour types ( is decoded but never written by ).
public enum PngColorType : byte
{
Gray = 0,
Rgb = 2,
+ Palette = 3,
GrayAlpha = 4,
Rgba = 6,
}
@@ -29,6 +31,7 @@ public static class PngEncoder
public static void Encode(Stream output, ReadOnlySpan pixels, int width, int height, PngColorType colorType, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
{
if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
+ if (colorType == PngColorType.Palette) throw new ArgumentException("Palette images are not written", nameof(colorType));
var channels = colorType switch
{
PngColorType.Gray => 1,
@@ -60,6 +63,36 @@ public static class PngEncoder
WriteChunk(output, "IEND", []);
}
+ /// Encodes a linear-light buffer as sRGB-encoded PNG (1 channel → gray, 3 → RGB, 4 → RGBA with linear
+ /// alpha) and tags it with an sRGB chunk.
+ /// 8 or 16 bits per sample.
+ public static byte[] Encode(ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize)
+ {
+ using var ms = new MemoryStream();
+ Encode(ms, image, bitDepth, level);
+ return ms.ToArray();
+ }
+
+ public static void Encode(Stream output, ImageBuffer image, int bitDepth = 8, CompressionLevel level = CompressionLevel.SmallestSize, IEnumerable<(string Type, byte[] Data)>? extraChunks = null)
+ {
+ if (bitDepth is not (8 or 16)) throw new ArgumentOutOfRangeException(nameof(bitDepth));
+ var channels = image.Channels;
+ var colorType = channels switch { 1 => PngColorType.Gray, 3 => PngColorType.Rgb, _ => PngColorType.Rgba };
+ byte[] pixels;
+ if (bitDepth == 8)
+ {
+ pixels = PixelConvert.ToInterleaved8(image, channels);
+ }
+ else
+ {
+ var words = PixelConvert.ToInterleaved16(image, channels);
+ pixels = new byte[words.Length * 2];
+ for (var i = 0; i < words.Length; i++) BinaryPrimitives.WriteUInt16BigEndian(pixels.AsSpan(2 * i), words[i]);
+ }
+ IEnumerable<(string Type, byte[] Data)> chunks = [("sRGB", [0]), .. extraChunks ?? []];
+ Encode(output, pixels, image.Width, image.Height, colorType, bitDepth, level, chunks);
+ }
+
/// Filters every row (adaptive, minimum sum of absolute differences) and deflates the result.
public static byte[] Compress(ReadOnlySpan pixels, int height, int stride, int bpp, CompressionLevel level)
{
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..93cc5178
--- /dev/null
+++ b/src/Titano.Core/Codecs/Tiff/TiffImageReader.cs
@@ -0,0 +1,445 @@
+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;
+ private const int MaxChunks = 1 << 24;
+ private const long MaxChunkBytes = int.MaxValue / 2;
+
+ /// Decodes the first full-resolution image of a TIFF (or a DNG whose main image is not CFA).
+ public static ImageBuffer Decode(Stream stream, TiffDecodeOptions? options = null)
+ {
+ 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;
+ if (count > MaxChunks) throw new InvalidDataException($"TIFF: {count} strips/tiles");
+ var offsets = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileOffsets : TiffTags.StripOffsets) ?? throw new InvalidDataException("TIFF: missing strip/tile offsets");
+ var counts = reader.GetUInts(ifd, g.Tiled ? TiffTags.TileByteCounts : TiffTags.StripByteCounts);
+ if (counts is null && count == 1 && g.Compression == CompressionNone) counts = [(uint)Math.Min(int.MaxValue, g.RowBytes * (long)g.ChunkHeight)];
+ 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] = ReadChunk(reader, offsets[i], counts[i]);
+ if (chunks[i] is null) warnings.Add($"TIFF: strip/tile {i} lies outside the file");
+ }
+ var tables = g.Compression is CompressionJpeg or CompressionLossyJpeg && ifd.Entries.TryGetValue(TiffTags.JpegTables, out var t) ? reader.ReadBytes(t) : null;
+
+ 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 > MaxChunkBytes) 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 = g.Compression == CompressionNone && data.Length >= expected ? data : 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);
+ if (!ReferenceEquals(data, raw)) data.AsSpan(0, n).CopyTo(raw);
+ return n;
+ }
+
+ /// Reads one strip/tile; large uncompressed strips (single-strip files) exceed TiffReader's per-read cap
+ /// and are read in pieces.
+ private static byte[]? ReadChunk(TiffReader reader, uint offset, uint length)
+ {
+ if (length <= TiffReader.MaxValueBytes) return reader.ReadRelative(offset, (int)length);
+ if (length > MaxChunkBytes || offset + (long)length > reader.StreamLength - reader.Base) return null;
+ var result = new byte[length];
+ for (long done = 0; done < length;)
+ {
+ var piece = (int)Math.Min(TiffReader.MaxValueBytes, length - done);
+ if (reader.ReadRelative(offset + done, piece) is not { } part) return null;
+ part.CopyTo(result, done);
+ done += piece;
+ }
+ return result;
+ }
+
+ private static void Place(T[] row, T[] target, Geometry g, int x0, int y, int validW, int plane)
+ {
+ if (g.Planes == 1)
+ {
+ 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/src/Titano.Core/Imaging/PixelConvert.cs b/src/Titano.Core/Imaging/PixelConvert.cs
new file mode 100644
index 00000000..86505660
--- /dev/null
+++ b/src/Titano.Core/Imaging/PixelConvert.cs
@@ -0,0 +1,383 @@
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+
+namespace Titano.Core.Imaging;
+
+/// How integer samples relate to light: sRGB-encoded (display referred) or proportional to linear light.
+public enum TransferFunction
+{
+ Srgb,
+ Linear,
+}
+
+///
+/// Conversions between interleaved integer pixels and planar linear-light s, gray ↔ RGB,
+/// Exif orientation, and clamping. Interleaved layouts: 1 = gray, 2 = gray+alpha, 3 = RGB, 4 = RGBA. Alpha is
+/// never transfer-encoded. Row loops are parallel for large images.
+///
+public static class PixelConvert
+{
+ private const int ParallelThreshold = 1 << 16;
+
+ /// 8×8 Bayer thresholds in code units, centred on zero (ordered dither).
+ private static readonly float[] Bayer = BuildBayer();
+
+ /// Interleaved 8-bit samples → linear buffer.
+ /// 0 = natural (1/2 → 1, 3 → 3, 4 → 3); 3 expands gray; 4 keeps alpha.
+ public static ImageBuffer FromInterleaved8(ReadOnlySpan pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int outputChannels = 0)
+ {
+ var outCh = OutputChannels(channels, outputChannels);
+ CheckLength(pixels.Length, width, height, channels);
+ var lut = new float[256];
+ for (var i = 0; i < 256; i++) lut[i] = transfer == TransferFunction.Srgb ? ColorSpace.Linear8((byte)i) : i / 255f;
+ var image = new ImageBuffer(width, height, outCh, clear: false);
+ unsafe
+ {
+ fixed (byte* p = pixels)
+ {
+ var ptr = (nint)p;
+ ForRows(height, width, y =>
+ {
+ var row = new ReadOnlySpan((byte*)ptr + (long)y * width * channels, width * channels);
+ Scatter(row, image, y, channels, lut, 1f / 255f);
+ });
+ }
+ }
+ return image;
+ }
+
+ /// Interleaved 16-bit container samples (values 0..) → linear buffer.
+ public static ImageBuffer FromInterleaved16(ReadOnlySpan pixels, int width, int height, int channels, TransferFunction transfer = TransferFunction.Srgb, int maxValue = 65535, int outputChannels = 0)
+ {
+ if (maxValue is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(maxValue));
+ var outCh = OutputChannels(channels, outputChannels);
+ CheckLength(pixels.Length, width, height, channels);
+ var lut = new float[maxValue + 1];
+ for (var i = 0; i <= maxValue; i++)
+ {
+ lut[i] = transfer == TransferFunction.Linear ? i / (float)maxValue
+ : maxValue == 65535 ? ColorSpace.Linear16((ushort)i) : (float)ColorSpace.SrgbToLinear(i / (double)maxValue);
+ }
+ var alphaScale = 1f / maxValue;
+ var image = new ImageBuffer(width, height, outCh, clear: false);
+ unsafe
+ {
+ fixed (ushort* p = pixels)
+ {
+ var ptr = (nint)p;
+ ForRows(height, width, y =>
+ {
+ var row = new ReadOnlySpan((ushort*)ptr + (long)y * width * channels, width * channels);
+ Scatter(row, image, y, channels, lut, alphaScale);
+ });
+ }
+ }
+ return image;
+ }
+
+ /// Linear buffer → interleaved 8-bit samples with per pixel
+ /// (1 from RGB takes Rec.709 luminance; missing alpha is opaque).
+ /// Add 8×8 ordered dither before rounding (breaks banding in smooth gradients).
+ public static void ToInterleaved8(ImageBuffer image, Span destination, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false)
+ {
+ CheckLength(destination.Length, image.Width, image.Height, channels);
+ unsafe
+ {
+ fixed (byte* p = destination)
+ {
+ var ptr = (nint)p;
+ ForRows(image.Height, image.Width, y =>
+ {
+ var row = new Span((byte*)ptr + (long)y * image.Width * channels, image.Width * channels);
+ EncodeRow8(image, y, row, channels, transfer, dither);
+ });
+ }
+ }
+ }
+
+ /// Allocating overload of .
+ public static byte[] ToInterleaved8(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb, bool dither = false)
+ {
+ var result = new byte[checked(image.Width * image.Height * channels)];
+ ToInterleaved8(image, result, channels, transfer, dither);
+ return result;
+ }
+
+ /// Linear buffer → interleaved 16-bit samples (0..65535).
+ public static void ToInterleaved16(ImageBuffer image, Span destination, int channels, TransferFunction transfer = TransferFunction.Srgb)
+ {
+ CheckLength(destination.Length, image.Width, image.Height, channels);
+ unsafe
+ {
+ fixed (ushort* p = destination)
+ {
+ var ptr = (nint)p;
+ ForRows(image.Height, image.Width, y =>
+ {
+ var row = new Span((ushort*)ptr + (long)y * image.Width * channels, image.Width * channels);
+ EncodeRow16(image, y, row, channels, transfer);
+ });
+ }
+ }
+ }
+
+ /// Allocating overload of .
+ public static ushort[] ToInterleaved16(ImageBuffer image, int channels, TransferFunction transfer = TransferFunction.Srgb)
+ {
+ var result = new ushort[checked(image.Width * image.Height * channels)];
+ ToInterleaved16(image, result, channels, transfer);
+ return result;
+ }
+
+ /// Encodes row into interleaved 8-bit samples (codec edge helper).
+ internal static void EncodeRow8(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer, bool dither)
+ {
+ Span offsets = stackalloc float[8];
+ for (var i = 0; i < 8; i++) offsets[i] = dither ? 0.5f + Bayer[(y & 7) * 8 + i] : 0.5f;
+ var srgb = transfer == TransferFunction.Srgb;
+ var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool.Shared.Rent(image.Width) : null;
+ for (var c = 0; c < channels; c++)
+ {
+ if (c == (channels <= 2 ? 1 : 3))
+ {
+ var a = image.Channels == 4 ? image.Row(3, y) : default;
+ for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (byte)255 : (byte)(Math.Clamp(a[x], 0f, 1f) * 255f + 0.5f);
+ continue;
+ }
+ var src = ColourRow(image, y, c, channels, scratch);
+ for (var x = 0; x < src.Length; x++)
+ {
+ var e = srgb ? ColorSpace.EncodeFast(src[x]) : Math.Clamp(src[x], 0f, 1f);
+ row[x * channels + c] = (byte)Math.Clamp(e * 255f + offsets[x & 7], 0f, 255f);
+ }
+ }
+ if (scratch is not null) ArrayPool.Shared.Return(scratch);
+ }
+
+ /// Encodes row into interleaved 16-bit samples (codec edge helper).
+ internal static void EncodeRow16(ImageBuffer image, int y, Span row, int channels, TransferFunction transfer)
+ {
+ var srgb = transfer == TransferFunction.Srgb;
+ var scratch = channels <= 2 && image.Channels >= 3 ? ArrayPool.Shared.Rent(image.Width) : null;
+ for (var c = 0; c < channels; c++)
+ {
+ if (c == (channels <= 2 ? 1 : 3))
+ {
+ var a = image.Channels == 4 ? image.Row(3, y) : default;
+ for (var x = 0; x < image.Width; x++) row[x * channels + c] = a.IsEmpty ? (ushort)65535 : (ushort)(Math.Clamp(a[x], 0f, 1f) * 65535f + 0.5f);
+ continue;
+ }
+ var src = ColourRow(image, y, c, channels, scratch);
+ for (var x = 0; x < src.Length; x++)
+ {
+ row[x * channels + c] = srgb ? ColorSpace.Encode16(src[x]) : (ushort)(Math.Clamp(src[x], 0f, 1f) * 65535f + 0.5f);
+ }
+ }
+ if (scratch is not null) ArrayPool.Shared.Return(scratch);
+ }
+
+ /// Single-channel buffer replicated into three channels.
+ public static ImageBuffer GrayToRgb(ImageBuffer gray)
+ {
+ if (gray.Channels != 1) throw new ArgumentException("Expected one channel", nameof(gray));
+ var rgb = new ImageBuffer(gray.Width, gray.Height, 3, clear: false);
+ for (var c = 0; c < 3; c++) gray.Plane(0).CopyTo(rgb.Plane(c));
+ return rgb;
+ }
+
+ /// Rec.709 luminance of an RGB(A) buffer.
+ public static ImageBuffer RgbToGray(ImageBuffer rgb)
+ {
+ if (rgb.Channels < 3) throw new ArgumentException("Expected RGB", nameof(rgb));
+ var gray = new ImageBuffer(rgb.Width, rgb.Height, 1, clear: false);
+ var r = rgb.Plane(0);
+ var g = rgb.Plane(1);
+ var b = rgb.Plane(2);
+ var d = gray.Plane(0);
+ var i = 0;
+ if (Vector.IsHardwareAccelerated)
+ {
+ var wr = new Vector(ColorSpace.LumaR);
+ var wg = new Vector(ColorSpace.LumaG);
+ var wb = new Vector(ColorSpace.LumaB);
+ for (; i <= d.Length - Vector.Count; i += Vector.Count)
+ {
+ (new Vector(r[i..]) * wr + new Vector(g[i..]) * wg + new Vector(b[i..]) * wb).CopyTo(d[i..]);
+ }
+ }
+ for (; i < d.Length; i++) d[i] = ColorSpace.Luminance(r[i], g[i], b[i]);
+ return gray;
+ }
+
+ /// Clamps every value into [, ] (NaN becomes ).
+ public static void Clamp(Span values, float min = 0f, float max = 1f)
+ {
+ var i = 0;
+ if (Vector.IsHardwareAccelerated)
+ {
+ var lo = new Vector(min);
+ var hi = new Vector(max);
+ for (; i <= values.Length - Vector.Count; i += Vector.Count)
+ {
+ var v = new Vector(values[i..]);
+ // Max(v, lo) with v as the first operand maps NaN to lo on x86 (maxps returns the second operand).
+ Vector.Min(Vector.ConditionalSelect(Vector.Equals(v, v), Vector.Max(v, lo), lo), hi).CopyTo(values[i..]);
+ }
+ }
+ for (; i < values.Length; i++)
+ {
+ var v = values[i];
+ values[i] = float.IsNaN(v) ? min : Math.Clamp(v, min, max);
+ }
+ }
+
+ /// Size after applying an Exif orientation (5–8 swap width and height).
+ public static (int Width, int Height) OrientedSize(int width, int height, int orientation) =>
+ orientation is >= 5 and <= 8 ? (height, width) : (width, height);
+
+ /// Applies an Exif orientation (1–8) into a new buffer; other values are treated as 1 (copy).
+ public static ImageBuffer ApplyOrientation(ImageBuffer source, int orientation)
+ {
+ int w = source.Width, h = source.Height;
+ var (ow, oh) = OrientedSize(w, h, orientation);
+ var result = new ImageBuffer(ow, oh, source.Channels, clear: false);
+ if (orientation is < 2 or > 8)
+ {
+ source.CopyTo(result);
+ return result;
+ }
+ for (var c = 0; c < source.Channels; c++)
+ {
+ var src = source.Storage.AsMemory(c * source.PlaneLength, source.PlaneLength);
+ var dst = result.Storage.AsMemory(c * result.PlaneLength, result.PlaneLength);
+ if (orientation <= 4)
+ {
+ ForRows(oh, ow, y =>
+ {
+ var sy = orientation is 3 or 4 ? h - 1 - y : y;
+ var s = src.Span.Slice(sy * w, w);
+ var d = dst.Span.Slice(y * ow, ow);
+ s.CopyTo(d);
+ if (orientation is 2 or 3) d.Reverse();
+ });
+ continue;
+ }
+ // Transposing orientations: copy in 32×32 tiles so both sides stay cache-friendly.
+ const int tile = 32;
+ var tilesY = (oh + tile - 1) / tile;
+ ForRows(tilesY, ow * tile, ty =>
+ {
+ var s = src.Span;
+ var d = dst.Span;
+ var y1 = Math.Min(oh, (ty + 1) * tile);
+ for (var x0 = 0; x0 < ow; x0 += tile)
+ {
+ var x1 = Math.Min(ow, x0 + tile);
+ for (var y = ty * tile; y < y1; y++)
+ {
+ for (var x = x0; x < x1; x++)
+ {
+ var (sx, sy) = orientation switch
+ {
+ 5 => (y, x),
+ 6 => (y, h - 1 - x),
+ 7 => (w - 1 - y, h - 1 - x),
+ _ => (w - 1 - y, x),
+ };
+ d[y * ow + x] = s[sy * w + sx];
+ }
+ }
+ }
+ });
+ }
+ return result;
+ }
+
+ /// Linear row feeding output colour channel : gray is replicated, and a gray output
+ /// from RGB takes Rec.709 luminance computed into .
+ private static ReadOnlySpan ColourRow(ImageBuffer image, int y, int c, int channels, float[]? scratch)
+ {
+ if (image.Channels == 1) return image.Row(0, y);
+ if (scratch is null) return image.Row(c, y);
+ var r = image.Row(0, y);
+ var g = image.Row(1, y);
+ var b = image.Row(2, y);
+ var luminance = scratch.AsSpan(0, image.Width);
+ for (var x = 0; x < luminance.Length; x++) luminance[x] = ColorSpace.Luminance(r[x], g[x], b[x]);
+ return luminance;
+ }
+
+ /// De-interleaves one row: colour through (indices clamped to its range), alpha scaled.
+ private static void Scatter(ReadOnlySpan row, ImageBuffer image, int y, int channels, float[] lut, float alphaScale)
+ where T : unmanaged, IBinaryInteger
+ {
+ var w = image.Width;
+ var top = lut.Length - 1;
+ var colour = channels is 1 or 2 ? 1 : 3;
+ for (var c = 0; c < image.Channels; c++)
+ {
+ var dst = image.Row(c, y);
+ if (c == 3)
+ {
+ if (channels is 2 or 4)
+ {
+ var a = channels - 1;
+ for (var x = 0; x < w; x++) dst[x] = Math.Min(int.CreateTruncating(row[x * channels + a]), top) * alphaScale;
+ }
+ else
+ {
+ dst.Fill(1f);
+ }
+ continue;
+ }
+ var s = colour == 1 ? 0 : c;
+ for (var x = 0; x < w; x++) dst[x] = lut[Math.Min(int.CreateTruncating(row[x * channels + s]), top)];
+ }
+ }
+
+ private static int OutputChannels(int channels, int requested)
+ {
+ if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels));
+ if (requested is not (0 or 1 or 3 or 4)) throw new ArgumentOutOfRangeException(nameof(requested));
+ if (requested == 1 && channels > 2) throw new ArgumentException("Use RgbToGray to reduce colour to one channel", nameof(requested));
+ return requested != 0 ? requested : channels <= 2 ? 1 : 3;
+ }
+
+ private static void CheckLength(int length, int width, int height, int channels)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
+ if (channels is < 1 or > 4) throw new ArgumentOutOfRangeException(nameof(channels));
+ if (length < (long)width * height * channels) throw new ArgumentException("Pixel buffer too small");
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static void ForRows(int rows, int rowWork, Action body)
+ {
+ if ((long)rows * rowWork < ParallelThreshold)
+ {
+ for (var y = 0; y < rows; y++) body(y);
+ }
+ else
+ {
+ Parallel.For(0, rows, body);
+ }
+ }
+
+ private static float[] BuildBayer()
+ {
+ // Recursive Bayer matrix: interleave bits of (x ^ y) and y, least significant coordinate bits first.
+ var m = new float[64];
+ for (var y = 0; y < 8; y++)
+ {
+ for (var x = 0; x < 8; x++)
+ {
+ var v = 0;
+ for (var bit = 0; bit < 3; bit++) v = v << 2 | (((x ^ y) >> bit) & 1) << 1 | ((y >> bit) & 1);
+ m[y * 8 + x] = (v + 0.5f) / 64f - 0.5f;
+ }
+ }
+ return m;
+ }
+}
diff --git a/src/Titano.Core/Imaging/Resampler.cs b/src/Titano.Core/Imaging/Resampler.cs
new file mode 100644
index 00000000..225917d1
--- /dev/null
+++ b/src/Titano.Core/Imaging/Resampler.cs
@@ -0,0 +1,201 @@
+using System.Numerics;
+
+namespace Titano.Core.Imaging;
+
+/// Reconstruction filters for .
+public enum ResampleFilter
+{
+ /// Lanczos3 on axes that shrink, Catmull-Rom on axes that grow.
+ Auto,
+
+ /// Exact area average (no ringing; fastest for large reductions such as thumbnails).
+ Box,
+
+ Lanczos3,
+ CatmullRom,
+}
+
+///
+/// Separable two-pass resampling of linear-light s. When shrinking, the kernel is stretched
+/// by the reduction factor (proper low-pass support); weights are normalised and folded at the edges (clamp), so
+/// constant images stay constant and mean energy is preserved. Rows are processed in parallel.
+///
+public static class Resampler
+{
+ /// Resizes into a new buffer with the same channel count.
+ public static ImageBuffer Resize(ImageBuffer source, int width, int height, ResampleFilter filter = ResampleFilter.Auto, int maxDegreeOfParallelism = -1)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
+ var parallel = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism };
+ if (width == source.Width && height == source.Height) return source.Clone();
+ var wx = width == source.Width ? null : Weights.Build(source.Width, width, filter);
+ var wy = height == source.Height ? null : Weights.Build(source.Height, height, filter);
+ if (wx is null) return Vertical(source, wy!, parallel);
+ if (wy is null) return Horizontal(source, wx, parallel);
+
+ // Run the pass that leaves the smaller intermediate work first.
+ var horizontalFirst = (long)source.Height * width * wx.Stride + (long)height * width * wy.Stride
+ <= (long)height * source.Width * wy.Stride + (long)height * width * wx.Stride;
+ using var intermediate = horizontalFirst ? Horizontal(source, wx, parallel) : Vertical(source, wy, parallel);
+ return horizontalFirst ? Vertical(intermediate, wy, parallel) : Horizontal(intermediate, wx, parallel);
+ }
+
+ /// Area-average reduction so that the long edge is at most
+ /// (a copy when the image is already small enough).
+ public static ImageBuffer Thumbnail(ImageBuffer source, int maxLongEdge)
+ {
+ var (w, h) = FitWithin(source.Width, source.Height, maxLongEdge);
+ return w == source.Width && h == source.Height ? source.Clone() : Resize(source, w, h, ResampleFilter.Box);
+ }
+
+ /// Largest size with the same aspect ratio whose long edge is ≤ (never upscales).
+ public static (int Width, int Height) FitWithin(int width, int height, int maxLongEdge)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLongEdge);
+ var longEdge = Math.Max(width, height);
+ if (longEdge <= maxLongEdge) return (width, height);
+ var scale = maxLongEdge / (double)longEdge;
+ return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
+ }
+
+ private static ImageBuffer Horizontal(ImageBuffer source, Weights w, ParallelOptions parallel)
+ {
+ var result = new ImageBuffer(w.Length, source.Height, source.Channels, clear: false);
+ Parallel.For(0, source.Height, parallel, y =>
+ {
+ for (var c = 0; c < source.Channels; c++)
+ {
+ ReadOnlySpan src = source.Row(c, y);
+ var dst = result.Row(c, y);
+ for (var x = 0; x < dst.Length; x++)
+ {
+ dst[x] = Dot(src.Slice(w.Start[x], w.Count[x]), w.Values.AsSpan(x * w.Stride, w.Count[x]));
+ }
+ }
+ });
+ return result;
+ }
+
+ private static ImageBuffer Vertical(ImageBuffer source, Weights w, ParallelOptions parallel)
+ {
+ var result = new ImageBuffer(source.Width, w.Length, source.Channels, clear: false);
+ Parallel.For(0, w.Length, parallel, y =>
+ {
+ var taps = w.Values.AsSpan(y * w.Stride, w.Count[y]);
+ for (var c = 0; c < source.Channels; c++)
+ {
+ var dst = result.Row(c, y);
+ dst.Clear();
+ for (var k = 0; k < taps.Length; k++) MultiplyAdd(source.Row(c, w.Start[y] + k), taps[k], dst);
+ }
+ });
+ return result;
+ }
+
+ private static float Dot(ReadOnlySpan a, ReadOnlySpan b)
+ {
+ var i = 0;
+ var sum = 0f;
+ if (Vector.IsHardwareAccelerated && a.Length >= Vector.Count)
+ {
+ var acc = Vector.Zero;
+ for (; i <= a.Length - Vector.Count; i += Vector.Count) acc += new Vector(a[i..]) * new Vector(b[i..]);
+ sum = Vector.Sum(acc);
+ }
+ for (; i < a.Length; i++) sum += a[i] * b[i];
+ return sum;
+ }
+
+ private static void MultiplyAdd(ReadOnlySpan src, float weight, Span dst)
+ {
+ var i = 0;
+ if (Vector.IsHardwareAccelerated)
+ {
+ var w = new Vector(weight);
+ for (; i <= dst.Length - Vector.Count; i += Vector.Count) (new Vector(dst[i..]) + new Vector(src[i..]) * w).CopyTo(dst[i..]);
+ }
+ for (; i < dst.Length; i++) dst[i] += src[i] * weight;
+ }
+
+ /// Per output sample: a contiguous source range and its normalised weights (stride-padded).
+ private sealed class Weights
+ {
+ public required int Length { get; init; }
+ public required int Stride { get; init; }
+ public required int[] Start { get; init; }
+ public required int[] Count { get; init; }
+ public required float[] Values { get; init; }
+
+ public static Weights Build(int source, int target, ResampleFilter filter)
+ {
+ var scale = target / (double)source;
+ var kind = filter == ResampleFilter.Auto ? (scale < 1 ? ResampleFilter.Lanczos3 : ResampleFilter.CatmullRom) : filter;
+ var radius = kind switch { ResampleFilter.Lanczos3 => 3.0, ResampleFilter.CatmullRom => 2.0, _ => 0.5 };
+ var stretch = Math.Max(1.0, 1 / scale);
+ var stride = (int)Math.Ceiling(2 * radius * stretch) + 2;
+ var start = new int[target];
+ var count = new int[target];
+ var values = new float[target * stride];
+ var taps = new double[source];
+ for (var i = 0; i < target; i++)
+ {
+ double lo, hi;
+ if (kind == ResampleFilter.Box)
+ {
+ lo = i / scale;
+ hi = (i + 1) / scale;
+ }
+ else
+ {
+ var center = (i + 0.5) / scale;
+ lo = center - radius * stretch;
+ hi = center + radius * stretch;
+ }
+ int first = Math.Max(0, (int)Math.Floor(lo) - 1), last = Math.Min(source - 1, (int)Math.Ceiling(hi));
+ int left = (int)Math.Floor(lo) - 1, right = (int)Math.Ceiling(hi);
+ Array.Clear(taps, first, last - first + 1);
+ var sum = 0.0;
+ for (var j = left; j <= right; j++)
+ {
+ double weight;
+ if (kind == ResampleFilter.Box)
+ {
+ weight = Math.Max(0, Math.Min(hi, j + 1) - Math.Max(lo, j));
+ }
+ else
+ {
+ var x = (j + 0.5 - (i + 0.5) / scale) / stretch;
+ weight = kind == ResampleFilter.Lanczos3 ? Lanczos3(x) : CatmullRom(x);
+ }
+ if (weight == 0) continue;
+ taps[Math.Clamp(j, 0, source - 1)] += weight; // clamp-to-edge folds outside taps inward
+ sum += weight;
+ }
+ while (first < last && taps[first] == 0) first++;
+ while (last > first && taps[last] == 0) last--;
+ start[i] = first;
+ count[i] = last - first + 1;
+ for (var j = first; j <= last; j++) values[i * stride + j - first] = (float)(taps[j] / sum);
+ }
+ return new Weights { Length = target, Stride = stride, Start = start, Count = count, Values = values };
+ }
+
+ private static double Lanczos3(double x)
+ {
+ x = Math.Abs(x);
+ if (x < 1e-9) return 1;
+ if (x >= 3) return 0;
+ var px = Math.PI * x;
+ return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
+ }
+
+ private static double CatmullRom(double x)
+ {
+ x = Math.Abs(x);
+ return x < 1 ? (1.5 * x - 2.5) * x * x + 1
+ : x < 2 ? ((-0.5 * x + 2.5) * x - 4) * x + 2
+ : 0;
+ }
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/CodecTestData.cs b/tests/Titano.Core.Tests/Codecs/CodecTestData.cs
new file mode 100644
index 00000000..3f637bd4
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/CodecTestData.cs
@@ -0,0 +1,167 @@
+using System.Text;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// Shared fixtures, synthetic images and image metrics for codec tests.
+internal static class CodecTestData
+{
+ public static byte[] Fixture(string relativePath) =>
+ File.ReadAllBytes(Path.Combine(TestContext.FixturesDirectory, "codecs", relativePath));
+
+ /// Netpbm P5/P6/P7 (PAM) reader for reference images; samples are big-endian when maxval > 255.
+ public static Pnm ReadPnm(byte[] data)
+ {
+ var pos = 0;
+ string Token()
+ {
+ while (pos < data.Length && (char.IsWhiteSpace((char)data[pos]) || data[pos] == '#'))
+ {
+ if (data[pos] == '#') while (pos < data.Length && data[pos] != '\n') pos++;
+ else pos++;
+ }
+ var start = pos;
+ while (pos < data.Length && !char.IsWhiteSpace((char)data[pos])) pos++;
+ return Encoding.ASCII.GetString(data, start, pos - start);
+ }
+ var magic = Token();
+ int width, height, channels, maxVal;
+ if (magic == "P7")
+ {
+ width = height = channels = maxVal = 0;
+ for (var t = Token(); t != "ENDHDR"; t = Token())
+ {
+ switch (t)
+ {
+ case "WIDTH": width = int.Parse(Token()); break;
+ case "HEIGHT": height = int.Parse(Token()); break;
+ case "DEPTH": channels = int.Parse(Token()); break;
+ case "MAXVAL": maxVal = int.Parse(Token()); break;
+ case "TUPLTYPE": Token(); break;
+ }
+ }
+ }
+ else
+ {
+ channels = magic switch { "P5" => 1, "P6" => 3, _ => throw new InvalidDataException(magic) };
+ width = int.Parse(Token());
+ height = int.Parse(Token());
+ maxVal = int.Parse(Token());
+ }
+ pos++;
+ var samples = new int[width * height * channels];
+ for (var i = 0; i < samples.Length; i++)
+ {
+ samples[i] = maxVal > 255 ? data[pos + 2 * i] << 8 | data[pos + 2 * i + 1] : data[pos + i];
+ }
+ return new Pnm(width, height, channels, maxVal, samples);
+ }
+
+ public sealed record Pnm(int Width, int Height, int Channels, int MaxVal, int[] Samples)
+ {
+ public byte[] Bytes => Samples.Select(s => (byte)s).ToArray();
+ public ushort[] Words => Samples.Select(s => (ushort)s).ToArray();
+ }
+
+ /// Deterministic RGB test card: smooth gradients, saturated colour bars, seeded noise and
+ /// text-like one-pixel strokes (the four content classes codecs struggle with).
+ public static byte[] TestCard(int width, int height, int seed = 1)
+ {
+ var rng = new Random(seed);
+ var rgb = new byte[width * height * 3];
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var band = y * 4 / height;
+ int r, g, b;
+ switch (band)
+ {
+ case 0:
+ r = x * 255 / Math.Max(1, width - 1);
+ g = y * 4 * 255 / Math.Max(1, height - 1) / 4 * 4 % 256;
+ b = 255 - r;
+ break;
+ case 1:
+ var bar = x * 8 / width;
+ r = (bar & 4) != 0 ? 230 : 25;
+ g = (bar & 2) != 0 ? 230 : 25;
+ b = (bar & 1) != 0 ? 230 : 25;
+ break;
+ case 2:
+ r = rng.Next(256);
+ g = rng.Next(256);
+ b = rng.Next(256);
+ break;
+ default:
+ var stroke = x % 7 == 0 || y % 9 == 0 || (x + y) % 13 == 0;
+ r = g = b = stroke ? 20 : 235;
+ break;
+ }
+ var i = (y * width + x) * 3;
+ rgb[i] = (byte)r;
+ rgb[i + 1] = (byte)g;
+ rgb[i + 2] = (byte)b;
+ }
+ }
+ return rgb;
+ }
+
+ /// Smooth photographic-like content (low-frequency gradients); compresses like real photos.
+ public static byte[] SmoothImage(int width, int height)
+ {
+ var rgb = new byte[width * height * 3];
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ double u = x / (double)width, v = y / (double)height;
+ var i = (y * width + x) * 3;
+ rgb[i] = (byte)(127.5 + 120 * Math.Sin(6.1 * u + 2.3 * v));
+ rgb[i + 1] = (byte)(127.5 + 120 * Math.Cos(4.7 * u * v + 3.1 * v));
+ rgb[i + 2] = (byte)(127.5 + 120 * Math.Sin(9.3 * v - 1.7 * u + 0.5));
+ }
+ }
+ return rgb;
+ }
+
+ public static double Psnr(ReadOnlySpan a, ReadOnlySpan b) => Psnr(a, b, 255);
+
+ public static double Psnr(ReadOnlySpan a, ReadOnlySpan b, double peak) where T : struct, IConvertible
+ {
+ Assert.Equal(a.Length, b.Length, "sample count");
+ double sum = 0;
+ for (var i = 0; i < a.Length; i++)
+ {
+ var d = a[i].ToDouble(null) - b[i].ToDouble(null);
+ sum += d * d;
+ }
+ var mse = sum / a.Length;
+ return mse == 0 ? 99 : 10 * Math.Log10(peak * peak / mse);
+ }
+
+ public static int MaxAbsDiff(ReadOnlySpan a, ReadOnlySpan b)
+ {
+ Assert.Equal(a.Length, b.Length, "sample count");
+ var max = 0;
+ for (var i = 0; i < a.Length; i++) max = Math.Max(max, Math.Abs(a[i] - b[i]));
+ return max;
+ }
+
+ /// Seeded corruption: the input truncated at points plus single-byte flips.
+ public static IEnumerable Corruptions(byte[] valid, int cases, int seed)
+ {
+ var rng = new Random(seed);
+ for (var i = 0; i < cases; i++)
+ {
+ yield return valid.AsSpan(0, rng.Next(valid.Length)).ToArray();
+ var flipped = (byte[])valid.Clone();
+ var flips = 1 + rng.Next(4);
+ for (var f = 0; f < flips; f++) flipped[rng.Next(flipped.Length)] ^= (byte)(1 << rng.Next(8));
+ yield return flipped;
+ var garbage = (byte[])valid.Clone();
+ garbage[rng.Next(garbage.Length)] = (byte)rng.Next(256);
+ yield return garbage;
+ }
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs b/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs
new file mode 100644
index 00000000..d161083c
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegDecoderTests.cs
@@ -0,0 +1,79 @@
+using Titano.Core.Codecs.Jpeg;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// Decoder output against libjpeg-turbo's djpeg (accurate integer IDCT) on cjpeg-produced fixtures.
+public sealed class JpegDecoderTests(TestContext context)
+{
+ [Theory]
+ [Case("b444", "4:4:4")]
+ [Case("b422", "4:2:2")]
+ [Case("b420", "4:2:0")]
+ [Case("b440", "4:4:0")]
+ [Case("b411", "4:1:1")]
+ [Case("p420", "4:2:0")]
+ [Case("p444", "4:4:4")]
+ [Case("r420", "4:2:0")]
+ [Case("r444", "4:4:4")]
+ public void MatchesDjpeg(string name, string sampling)
+ {
+ var data = Fixture($"jpeg/{name}.jpg");
+ var reference = ReadPnm(Fixture($"jpeg/{name}.ppm"));
+ var image = JpegDecoder.Decode(data);
+ Assert.Equal(reference.Width, image.Width);
+ Assert.Equal(reference.Height, image.Height);
+ Assert.Equal(3, image.Components);
+ Assert.Equal(sampling, image.Info.SamplingNotation);
+ Assert.Empty(image.Warnings);
+ var diff = MaxAbsDiff(image.Pixels8, reference.Samples);
+ context.Log($"{name}: max |diff| = {diff}");
+ Assert.LessOrEqual(diff, 2);
+ }
+
+ [Theory]
+ [Case("gray")]
+ [Case("pgray")]
+ public void GrayMatchesDjpeg(string name)
+ {
+ var image = JpegDecoder.Decode(Fixture($"jpeg/{name}.jpg"));
+ var reference = ReadPnm(Fixture($"jpeg/{name}.pgm"));
+ Assert.Equal(1, image.Components);
+ Assert.Equal(JpegColorSpace.Gray, image.Info.ColorSpace);
+ Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, reference.Samples), 2);
+ }
+
+ [Test]
+ public void ReplicatedUpsamplingMatchesDjpegNoSmooth()
+ {
+ var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { FancyUpsampling = false });
+ Assert.LessOrEqual(MaxAbsDiff(image.Pixels8, ReadPnm(Fixture("jpeg/b420-nosmooth.ppm")).Samples), 2);
+ }
+
+ [Test]
+ public void ReadInfoParsesHeadersOnly()
+ {
+ var info = JpegDecoder.ReadInfo(Fixture("jpeg/p420.jpg"));
+ Assert.Equal(61, info.Width);
+ Assert.Equal(45, info.Height);
+ Assert.Equal(JpegProcess.Progressive, info.Process);
+ Assert.Equal(JpegColorSpace.YCbCr, info.ColorSpace);
+ Assert.Equal(8, info.Precision);
+ var restart = JpegDecoder.ReadInfo(Fixture("jpeg/r444.jpg"));
+ Assert.Equal(5, restart.RestartInterval);
+ }
+
+ [Test]
+ public void AdobeYcckIsConvertedToRgb()
+ {
+ var image = JpegDecoder.Decode(Fixture("jpeg/cmyk.jpg"));
+ Assert.Equal(JpegColorSpace.Ycck, image.Info.ColorSpace);
+ Assert.Equal(4, image.Info.Components);
+ Assert.Equal(3, image.Components);
+ var source = ReadPnm(Fixture("src.ppm"));
+ var psnr = Psnr(image.Pixels8, source.Bytes);
+ context.Log($"YCCK round trip PSNR {psnr:F1} dB");
+ Assert.Greater(psnr, 30);
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs b/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs
new file mode 100644
index 00000000..a0ffe104
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegEncoderTests.cs
@@ -0,0 +1,309 @@
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Imaging;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// Encoder → decoder round trips on synthetic content.
+public sealed class JpegEncoderTests(TestContext context)
+{
+ private const int W = 160, H = 120;
+
+ /// The four synthetic content classes: smooth gradients, colour bars, sensor-like noise, text-like edges.
+ private static byte[] Content(string kind)
+ {
+ var rgb = new byte[W * H * 3];
+ var rng = new Random(11);
+ for (var y = 0; y < H; y++)
+ {
+ for (var x = 0; x < W; x++)
+ {
+ int r, g, b;
+ switch (kind)
+ {
+ case "gradients":
+ r = x * 255 / (W - 1);
+ g = y * 255 / (H - 1);
+ b = (x + y) * 255 / (W + H - 2);
+ break;
+ case "bars":
+ var bar = x / (W / 8);
+ r = (bar & 4) != 0 ? 235 : 16;
+ g = (bar & 2) != 0 ? 235 : 16;
+ b = (bar & 1) != 0 ? 235 : 16;
+ break;
+ case "noise":
+ // Sensor-like: mostly luma noise (σ ≈ 3.7 levels) plus weak chroma noise.
+ var n = rng.Next(-6, 7);
+ r = 120 + x / 4 + n + rng.Next(-2, 3);
+ g = 110 + y / 4 + n + rng.Next(-2, 3);
+ b = 100 + n + rng.Next(-2, 3);
+ break;
+ default:
+ var ink = (x % 11 is 2 or 3 && y % 16 < 12) || (y % 16 is 5 && x % 11 < 8);
+ r = g = b = ink ? 24 : 232;
+ break;
+ }
+ var i = (y * W + x) * 3;
+ rgb[i] = (byte)r;
+ rgb[i + 1] = (byte)g;
+ rgb[i + 2] = (byte)b;
+ }
+ }
+ return rgb;
+ }
+
+ private static double RoundTripPsnr(byte[] rgb, JpegEncodeOptions options, int channels = 3)
+ {
+ var jpeg = JpegEncoder.Encode(rgb, W, H, channels, options);
+ var decoded = JpegDecoder.Decode(jpeg);
+ return Psnr(decoded.Pixels8, rgb);
+ }
+
+ /// PSNR of Rec.601 luma (Y′). 4:2:0 halves chroma resolution by design, so saturated chroma edges
+ /// (colour bars) lose a quarter of the step under triangle upsampling in any codec (libjpeg: 26.7 dB RGB on
+ /// the same bars); the codec's own fidelity is measured on Y′.
+ private static double RoundTripLumaPsnr(byte[] rgb, JpegEncodeOptions options)
+ {
+ var decoded = JpegDecoder.Decode(JpegEncoder.Encode(rgb, W, H, 3, options)).Pixels8!;
+ static double[] Luma(byte[] p)
+ {
+ var y = new double[p.Length / 3];
+ for (var i = 0; i < y.Length; i++) y[i] = 0.299 * p[3 * i] + 0.587 * p[3 * i + 1] + 0.114 * p[3 * i + 2];
+ return y;
+ }
+ return Psnr(Luma(decoded), Luma(rgb), 255);
+ }
+
+ [Theory]
+ [Case("gradients")]
+ [Case("bars")]
+ [Case("noise")]
+ [Case("text")]
+ public void HighQuality444Above40Db(string kind)
+ {
+ var psnr = RoundTripPsnr(Content(kind), new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444 });
+ context.Log($"{kind} q95 4:4:4: {psnr:F2} dB");
+ Assert.GreaterOrEqual(psnr, 40);
+ }
+
+ [Theory]
+ [Case("gradients")]
+ [Case("bars")]
+ [Case("noise")]
+ [Case("text")]
+ public void Quality90Yuv420Above34Db(string kind)
+ {
+ var options = new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 };
+ var psnr = RoundTripLumaPsnr(Content(kind), options);
+ context.Log($"{kind} q90 4:2:0: Y′ {psnr:F2} dB, RGB {RoundTripPsnr(Content(kind), options):F2} dB");
+ Assert.GreaterOrEqual(psnr, 34);
+ }
+
+ [Test]
+ public void PsnrAndSizeGrowWithQuality()
+ {
+ var rgb = TestCard(W, H);
+ var psnr = new List();
+ var sizes = new List();
+ foreach (var q in new[] { 5, 20, 40, 60, 75, 85, 95, 100 })
+ {
+ var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = q, Subsampling = JpegSubsampling.Yuv422 });
+ sizes.Add(jpeg.Length);
+ psnr.Add(Psnr(JpegDecoder.Decode(jpeg).Pixels8, rgb));
+ }
+ context.Log("PSNR: " + string.Join(", ", psnr.Select(p => p.ToString("F1"))));
+ Assert.Monotonic(psnr, strict: true);
+ Assert.Monotonic(sizes, strict: true);
+ }
+
+ [Test]
+ public void OptimizedHuffmanIsSmallerAndPixelIdentical()
+ {
+ var rgb = TestCard(W, H);
+ var standard = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85 });
+ var optimized = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 85, OptimizeHuffman = true });
+ context.Log($"standard {standard.Length} B, optimized {optimized.Length} B");
+ Assert.Less(optimized.Length, standard.Length);
+ Assert.BytesEqual(JpegDecoder.Decode(standard).Pixels8, JpegDecoder.Decode(optimized).Pixels8);
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(7)]
+ [Case(40)]
+ public void RestartIntervalsDecodeIdentically(int interval)
+ {
+ var rgb = TestCard(W, H);
+ var plain = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80 });
+ var restart = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 80, RestartInterval = interval, OptimizeHuffman = true });
+ Assert.Equal(interval, JpegDecoder.ReadInfo(restart).RestartInterval);
+ var decoded = JpegDecoder.Decode(restart);
+ Assert.Empty(decoded.Warnings);
+ Assert.BytesEqual(JpegDecoder.Decode(plain).Pixels8, decoded.Pixels8);
+ }
+
+ [Test]
+ public void App1SegmentsFollowSoiAndReplaceJfif()
+ {
+ var exif = "Exif\0\0II*\0\b\0\0\0\0\0\0\0"u8.ToArray();
+ var xmp = "http://ns.adobe.com/xap/1.0/\0"u8.ToArray();
+ var jpeg = JpegEncoder.Encode(TestCard(32, 16), 32, 16, 3, new JpegEncodeOptions { App1Segments = [exif, xmp] });
+ Assert.Equal(0xE1, jpeg[3]);
+ Assert.BytesEqual(exif, jpeg.AsSpan(6, exif.Length));
+ var second = 4 + (jpeg[4] << 8 | jpeg[5]);
+ Assert.Equal(0xE1, jpeg[second + 1]);
+ Assert.False(jpeg.AsSpan().IndexOf("JFIF"u8) >= 0, "JFIF must be omitted when APP1 is supplied");
+ Assert.Equal(32, JpegDecoder.Decode(jpeg).Width);
+ Assert.Throws(() => JpegEncoder.Encode(TestCard(8, 8), 8, 8, 3, new JpegEncodeOptions { App1Segments = [new byte[65534]] }));
+ }
+
+ [Test]
+ public void GrayBufferEncodesSingleComponent()
+ {
+ using var gray = new ImageBuffer(50, 30, 1);
+ for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = (i % 50) / 49f;
+ var jpeg = JpegEncoder.Encode(gray, new JpegEncodeOptions { Quality = 95 });
+ var info = JpegDecoder.ReadInfo(jpeg);
+ Assert.Equal(1, info.Components);
+ using var back = JpegDecoder.DecodeToLinear(jpeg);
+ Assert.Equal(1, back.Channels);
+ for (var x = 0; x < 50; x += 7) Assert.Approximately(gray[0, x, 15], back[0, x, 15], 0.02);
+ }
+
+ [Test]
+ public void LinearBufferRoundTripWithDither()
+ {
+ using var image = new ImageBuffer(96, 64);
+ for (var y = 0; y < 64; y++)
+ {
+ for (var x = 0; x < 96; x++)
+ {
+ image[0, x, y] = x / 95f;
+ image[1, x, y] = y / 63f * 0.5f;
+ image[2, x, y] = 0.18f;
+ }
+ }
+ var jpeg = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, Subsampling = JpegSubsampling.Yuv444, Dither = true });
+ using var back = JpegDecoder.DecodeToLinear(jpeg);
+ var reference = PixelConvert.ToInterleaved8(image, 3);
+ var decoded = PixelConvert.ToInterleaved8(back, 3);
+ var psnr = Psnr(decoded, reference);
+ context.Log($"linear round trip {psnr:F1} dB");
+ Assert.Greater(psnr, 40);
+ }
+
+ [Test]
+ public void TwelveBitExtendedSequentialDecodes()
+ {
+ const int w = 40, h = 24;
+ var samples = new ushort[w * h];
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++) samples[y * w + x] = (ushort)(x * 4095 / (w - 1) ^ (y * 37 % 256));
+ }
+ var jpeg = TwelveBitEncoder.EncodeGray(samples, w, h);
+ var image = JpegDecoder.Decode(jpeg);
+ Assert.Equal(12, image.BitDepth);
+ Assert.Equal(JpegProcess.ExtendedSequential, image.Info.Process);
+ var psnr = Psnr(image.Pixels16, samples, 4095);
+ context.Log($"12-bit PSNR {psnr:F1} dB");
+ Assert.Greater(psnr, 50);
+ using var linear = JpegDecoder.DecodeToLinear(jpeg);
+ Assert.Approximately(ColorSpace.SrgbToLinear(image.Pixels16![5] / 4095.0), linear[0, 5, 0], 1e-4);
+ }
+
+ /// Minimal SOF1 12-bit gray encoder (quantiser 1, optimal tables) for decoder tests.
+ private static class TwelveBitEncoder
+ {
+ public static byte[] EncodeGray(ushort[] samples, int width, int height)
+ {
+ int bw = (width + 7) / 8, bh = (height + 7) / 8;
+ var blocks = new short[bw * bh][];
+ for (var by = 0; by < bh; by++)
+ {
+ for (var bx = 0; bx < bw; bx++)
+ {
+ var coef = new short[64];
+ for (var v = 0; v < 8; v++)
+ {
+ for (var u = 0; u < 8; u++)
+ {
+ double sum = 0;
+ for (var y = 0; y < 8; y++)
+ {
+ for (var x = 0; x < 8; x++)
+ {
+ var s = samples[Math.Min(by * 8 + y, height - 1) * width + Math.Min(bx * 8 + x, width - 1)] - 2048.0;
+ sum += s * JpegTables.Basis[u * 8 + x] * JpegTables.Basis[v * 8 + y];
+ }
+ }
+ coef[v * 8 + u] = (short)Math.Round(sum);
+ }
+ }
+ blocks[by * bw + bx] = coef;
+ }
+ }
+ var dcFreq = new long[256];
+ var acFreq = new long[256];
+ Walk(blocks, (dc, s) => (dc ? dcFreq : acFreq)[s]++, null);
+ var dcCode = JpegHuffmanCode.Optimal(dcFreq);
+ var acCode = JpegHuffmanCode.Optimal(acFreq);
+ var writer = new JpegBitWriter(1 << 16);
+ Walk(blocks, (dc, s) => { var c = dc ? dcCode : acCode; writer.Reserve(8); writer.Write(c.Code[s], c.Length[s]); }, (v, s) => writer.Write((uint)((v < 0 ? v - 1 : v) & ((1 << s) - 1)), s));
+ writer.Flush();
+
+ using var ms = new MemoryStream();
+ ms.Write([0xFF, 0xD8]);
+ var dqt = new byte[129];
+ dqt[0] = 0x10;
+ for (var k = 0; k < 64; k++) dqt[2 + 2 * k] = 1;
+ JpegEncoder.Segment(ms, 0xDB, dqt);
+ JpegEncoder.Segment(ms, 0xC1, [12, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 1, 1, 0x11, 0]);
+ var dht = new MemoryStream();
+ dht.WriteByte(0x00);
+ dht.Write(dcCode.Bits);
+ dht.Write(dcCode.Values);
+ dht.WriteByte(0x10);
+ dht.Write(acCode.Bits);
+ dht.Write(acCode.Values);
+ JpegEncoder.Segment(ms, 0xC4, dht.ToArray());
+ JpegEncoder.Segment(ms, 0xDA, [1, 1, 0x00, 0, 63, 0]);
+ ms.Write(writer.Written);
+ ms.Write([0xFF, 0xD9]);
+ return ms.ToArray();
+ }
+
+ private static void Walk(short[][] blocks, Action symbol, Action? bits)
+ {
+ var pred = 0;
+ foreach (var b in blocks)
+ {
+ var diff = b[0] - pred;
+ pred = b[0];
+ var s = Size(diff);
+ symbol(true, s);
+ if (s > 0) bits?.Invoke(diff, s);
+ var run = 0;
+ for (var k = 1; k < 64; k++)
+ {
+ int v = b[JpegTables.NaturalOrder[k]];
+ if (v == 0)
+ {
+ run++;
+ continue;
+ }
+ for (; run >= 16; run -= 16) symbol(false, 0xF0);
+ s = Size(v);
+ symbol(false, run << 4 | s);
+ bits?.Invoke(v, s);
+ run = 0;
+ }
+ if (run > 0) symbol(false, 0);
+ }
+ }
+
+ private static int Size(int v) => v == 0 ? 0 : 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)Math.Abs(v));
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs b/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs
new file mode 100644
index 00000000..65ba7c54
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegLosslessTests.cs
@@ -0,0 +1,107 @@
+using Titano.Core.Codecs.Jpeg;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// Lossless JPEG (SOF3) round trips: every predictor, precisions 2–16, components, restarts.
+public sealed class JpegLosslessTests
+{
+ private static ushort[] Raw(int width, int height, int components, int precision, int seed)
+ {
+ var rng = new Random(seed);
+ var max = (1 << precision) - 1;
+ var samples = new ushort[width * height * components];
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ for (var c = 0; c < components; c++)
+ {
+ // Smooth ramp + sensor noise, with a few clipped highlights and black pixels.
+ var v = (x * 3 + y * 5 + c * 97) % (max + 1) * 0.7 + rng.Next(Math.Max(1, max / 64));
+ if (rng.Next(200) == 0) v = max;
+ if (rng.Next(300) == 0) v = 0;
+ samples[(y * width + x) * components + c] = (ushort)Math.Clamp((int)v, 0, max);
+ }
+ }
+ }
+ return samples;
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(2)]
+ [Case(3)]
+ [Case(4)]
+ [Case(5)]
+ [Case(6)]
+ [Case(7)]
+ public void EveryPredictorRoundTrips(int predictor)
+ {
+ var samples = Raw(37, 23, 3, 12, predictor);
+ var jpeg = JpegLosslessEncoder.Encode(samples, 37, 23, 3, 12, predictor);
+ var decoded = JpegLosslessDecoder.Decode(jpeg);
+ Assert.Equal(37, decoded.Width);
+ Assert.Equal(23, decoded.Height);
+ Assert.Equal(3, decoded.Components);
+ Assert.Equal(12, decoded.Precision);
+ Assert.SequenceEqual(samples, decoded.Samples);
+ }
+
+ [Theory]
+ [Case(2, 1)]
+ [Case(8, 1)]
+ [Case(14, 2)]
+ [Case(16, 1)]
+ [Case(16, 4)]
+ public void PrecisionsAndComponentCounts(int precision, int components)
+ {
+ var samples = Raw(19, 11, components, precision, precision);
+ foreach (var predictor in new[] { 1, 4, 7 })
+ {
+ var decoded = JpegLosslessDecoder.Decode(JpegLosslessEncoder.Encode(samples, 19, 11, components, precision, predictor));
+ Assert.SequenceEqual(samples, decoded.Samples);
+ }
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(19)]
+ [Case(25)]
+ [Case(64)]
+ public void RestartIntervalsRoundTrip(int interval)
+ {
+ var samples = Raw(19, 13, 2, 14, interval);
+ foreach (var predictor in new[] { 1, 6 })
+ {
+ var jpeg = JpegLosslessEncoder.Encode(samples, 19, 13, 2, 14, predictor, restartInterval: interval);
+ Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples);
+ }
+ }
+
+ [Test]
+ public void PointTransformRestoresScaledSamples()
+ {
+ var samples = Raw(16, 9, 1, 16, 3).Select(s => (ushort)(s & ~7)).ToArray();
+ var jpeg = JpegLosslessEncoder.Encode(samples, 16, 9, 1, 16, predictor: 5, pointTransform: 3);
+ Assert.SequenceEqual(samples, JpegLosslessDecoder.Decode(jpeg).Samples);
+ }
+
+ [Test]
+ public void GeneralDecoderExposesLosslessAsImage()
+ {
+ var samples = Raw(10, 6, 3, 8, 1);
+ var image = JpegDecoder.Decode(JpegLosslessEncoder.Encode(samples, 10, 6, 3, 8));
+ Assert.Equal(JpegProcess.Lossless, image.Info.Process);
+ Assert.Equal(3, image.Components);
+ Assert.SequenceEqual(samples.Select(s => (byte)s), image.Pixels8!);
+ var wide = Raw(10, 6, 1, 14, 2);
+ var gray = JpegDecoder.Decode(JpegLosslessEncoder.Encode(wide, 10, 6, 1, 14));
+ Assert.Equal(14, gray.BitDepth);
+ Assert.SequenceEqual(wide, gray.Pixels16!);
+ }
+
+ [Test]
+ public void DctStreamIsRejectedByLosslessDecoder() =>
+ Assert.Throws(() => JpegLosslessDecoder.Decode(JpegEncoder.Encode(new byte[48], 4, 4, 3)));
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs
new file mode 100644
index 00000000..39d5ad48
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegPerformanceTests.cs
@@ -0,0 +1,70 @@
+using System.Diagnostics;
+using System.Reflection;
+using Titano.Core.Codecs.Jpeg;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// 24-megapixel baseline 4:2:0 encode/decode timing (decode measured single-threaded).
+[Serial]
+[Category("Performance")]
+public sealed class JpegPerformanceTests(TestContext context)
+{
+ private const int W = 6000, H = 4000;
+
+ [Test]
+ [Timeout(60_000)]
+ public void Decodes24MegapixelOnOneCoreUnderThreeSeconds()
+ {
+ // A Debug build disables the JIT optimiser in Titano.Core: timings would measure the build, not the codec.
+ if (typeof(JpegDecoder).Assembly.GetCustomAttribute()?.IsJITOptimizerDisabled == true)
+ TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)");
+ var rgb = Photo();
+ var sw = Stopwatch.StartNew();
+ var jpeg = JpegEncoder.Encode(rgb, W, H, 3, new JpegEncodeOptions { Quality = 90, Subsampling = JpegSubsampling.Yuv420 });
+ var encode = sw.Elapsed;
+
+ // Best of two runs: the machine is shared, the first run also pays JIT warm-up.
+ var single = TimeSpan.MaxValue;
+ JpegImage? image = null;
+ for (var run = 0; run < 2; run++)
+ {
+ sw.Restart();
+ image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxDegreeOfParallelism = 1 });
+ single = sw.Elapsed < single ? sw.Elapsed : single;
+ }
+ sw.Restart();
+ JpegDecoder.Decode(jpeg);
+ var parallel = sw.Elapsed;
+
+ context.Log($"encode {encode.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / encode.TotalSeconds:F1} MP/s, {jpeg.Length / 1e6:F2} MB); " +
+ $"decode 1 core {single.TotalMilliseconds:F0} ms ({W * (double)H / 1e6 / single.TotalSeconds:F1} MP/s); " +
+ $"decode all cores {parallel.TotalMilliseconds:F0} ms");
+ Console.WriteLine($"[perf] {context.LogText.Trim()}");
+ Assert.Equal(W, image!.Width);
+ Assert.Less(single.TotalSeconds, 3.0);
+ }
+
+ /// Photo-like content: smooth illumination, texture and mild noise (≈ q90 file size of a real photo).
+ private static byte[] Photo()
+ {
+ var rgb = new byte[W * H * 3];
+ Parallel.For(0, H, y =>
+ {
+ var state = (uint)(y * 2654435761u + 1);
+ for (var x = 0; x < W; x++)
+ {
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ var noise = (int)(state & 7) - 4;
+ var texture = ((x >> 3) ^ (y >> 3)) & 15;
+ var i = (y * W + x) * 3;
+ rgb[i] = (byte)Math.Clamp(60 + x * 150 / W + texture + noise, 0, 255);
+ rgb[i + 1] = (byte)Math.Clamp(80 + y * 120 / H + texture + noise, 0, 255);
+ rgb[i + 2] = (byte)Math.Clamp(200 - (x + y) * 140 / (W + H) + noise, 0, 255);
+ }
+ });
+ return rgb;
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs b/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs
new file mode 100644
index 00000000..1b1dd8f9
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegRobustnessTests.cs
@@ -0,0 +1,157 @@
+using Titano.Core.Codecs.Jpeg;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// Corrupt, truncated and hostile JPEG input: only may escape.
+public sealed class JpegRobustnessTests(TestContext context)
+{
+ private static byte[] LosslessSample()
+ {
+ var samples = new ushort[24 * 10 * 2];
+ for (var i = 0; i < samples.Length; i++) samples[i] = (ushort)(i * 37 % 4096);
+ return JpegLosslessEncoder.Encode(samples, 24, 10, 2, 12, predictor: 6, restartInterval: 24);
+ }
+
+ [Theory]
+ [Case("jpeg/b420.jpg")]
+ [Case("jpeg/b411.jpg")]
+ [Case("jpeg/p420.jpg")]
+ [Case("jpeg/p444.jpg")]
+ [Case("jpeg/r420.jpg")]
+ [Case("jpeg/pgray.jpg")]
+ [Case("jpeg/cmyk.jpg")]
+ [Case("lossless")]
+ public void FuzzedInputOnlyThrowsInvalidData(string source)
+ {
+ var valid = source == "lossless" ? LosslessSample() : Fixture(source);
+ var options = new[] { JpegDecodeOptions.Default, new JpegDecodeOptions { MaxLongEdge = 16, FancyUpsampling = false } };
+ int decoded = 0, rejected = 0;
+ var i = 0;
+ foreach (var input in Corruptions(valid, 120, seed: source.Sum(c => c)))
+ {
+ try
+ {
+ JpegDecoder.ReadInfo(input);
+ if (source == "lossless")
+ {
+ var raw = JpegLosslessDecoder.Decode(input);
+ Assert.Equal(raw.Width * raw.Height * raw.Components, raw.Samples.Length);
+ }
+ else
+ {
+ var image = JpegDecoder.Decode(input, options[i++ % 2]);
+ Assert.True(image.Width > 0 && image.Height > 0);
+ }
+ decoded++;
+ }
+ catch (InvalidDataException)
+ {
+ rejected++;
+ }
+ }
+ context.Log($"{source}: {decoded} decoded (possibly partial), {rejected} rejected");
+ }
+
+ [Test]
+ public void CorruptRestartIntervalIsResynchronised()
+ {
+ var data = Fixture("jpeg/r420.jpg");
+ var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples;
+ var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]);
+ var rst1 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD1]);
+ Assert.True(rst0 > 0 && rst1 > rst0, "fixture has restart markers");
+ var corrupt = (byte[])data.Clone();
+ var rng = new Random(5);
+ for (var p = rst0 + 6; p < rst1 - 4; p += 3)
+ {
+ if (corrupt[p - 1] != 0xFF) corrupt[p] = (byte)rng.Next(0xFF);
+ }
+ // A bogus marker inside the damaged interval must be skipped, as libjpeg's resync does.
+ corrupt[rst0 + 10] = 0xFF;
+ corrupt[rst0 + 11] = 0x3A;
+ var image = JpegDecoder.Decode(corrupt);
+ context.Log(string.Join("; ", image.Warnings));
+ Assert.NotEmpty(image.Warnings);
+ AssertRowsMatch(image.Pixels8!, reference, 0, 14);
+ AssertRowsMatch(image.Pixels8!, reference, 34, 45);
+ }
+
+ [Test]
+ public void MissingRestartMarkerSkipsTheLostInterval()
+ {
+ var data = Fixture("jpeg/r420.jpg");
+ var reference = ReadPnm(Fixture("jpeg/r420.ppm")).Samples;
+ var rst0 = data.AsSpan().IndexOf([(byte)0xFF, (byte)0xD0]);
+ var cut = data.AsSpan(0, rst0).ToArray().Concat(data.AsSpan(rst0 + 2).ToArray()).ToArray();
+ var image = JpegDecoder.Decode(cut);
+ Assert.NotEmpty(image.Warnings);
+ AssertRowsMatch(image.Pixels8!, reference, 0, 14);
+ AssertRowsMatch(image.Pixels8!, reference, 34, 45);
+ }
+
+ [Theory]
+ [Case("jpeg/p420.jpg")]
+ [Case("jpeg/b444.jpg")]
+ public void TruncatedScanDataYieldsPartialImage(string name)
+ {
+ var data = Fixture(name);
+ var image = JpegDecoder.Decode(data.AsSpan(0, data.Length * 2 / 3));
+ Assert.Equal(61, image.Width);
+ Assert.Equal(45, image.Height);
+ Assert.NotEmpty(image.Warnings);
+ }
+
+ [Test]
+ public void StructuralErrorsAreRejected()
+ {
+ Assert.Throws(() => JpegDecoder.Decode([]));
+ Assert.Throws(() => JpegDecoder.Decode([0xFF, 0xD8, 0xFF, 0xD9]));
+ Assert.Throws(() => JpegDecoder.ReadInfo([0x89, 0x50, 0x4E, 0x47]));
+ var arithmetic = Fixture("jpeg/b420.jpg");
+ var sof = arithmetic.AsSpan().IndexOf([(byte)0xFF, (byte)0xC0]);
+ arithmetic[sof + 1] = 0xC9;
+ Assert.Throws(() => JpegDecoder.Decode(arithmetic));
+ var huge = Fixture("jpeg/b420.jpg");
+ huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
+ Assert.Throws(() => JpegDecoder.Decode(huge));
+ }
+
+ [Test]
+ public void TablesStreamFeedsAbbreviatedImage()
+ {
+ // TIFF JPEGTables layout: tables in one SOI..EOI stream, the image without DQT/DHT.
+ var full = Fixture("jpeg/b420.jpg");
+ var tables = new MemoryStream();
+ var image = new MemoryStream();
+ tables.Write([0xFF, 0xD8]);
+ image.Write([0xFF, 0xD8]);
+ var pos = 2;
+ while (pos < full.Length)
+ {
+ var marker = full[pos + 1];
+ if (marker == 0xDA)
+ {
+ image.Write(full.AsSpan(pos));
+ break;
+ }
+ var length = full[pos + 2] << 8 | full[pos + 3];
+ (marker is 0xDB or 0xC4 ? tables : image).Write(full.AsSpan(pos, length + 2));
+ pos += length + 2;
+ }
+ tables.Write([0xFF, 0xD9]);
+ Assert.Throws(() => JpegDecoder.Decode(image.ToArray()));
+ var decoded = JpegDecoder.Decode(image.ToArray(), new JpegDecodeOptions { Tables = tables.ToArray() });
+ Assert.BytesEqual(JpegDecoder.Decode(full).Pixels8, decoded.Pixels8);
+ }
+
+ private static void AssertRowsMatch(byte[] actual, int[] reference, int fromRow, int toRow)
+ {
+ var rowBytes = 61 * 3;
+ for (var i = fromRow * rowBytes; i < toRow * rowBytes; i++)
+ {
+ if (Math.Abs(actual[i] - reference[i]) > 2) Assert.Fail($"row {i / rowBytes} differs from the reference");
+ }
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs b/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs
new file mode 100644
index 00000000..ef970575
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/JpegScalingTests.cs
@@ -0,0 +1,94 @@
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Imaging;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+/// DCT-domain scaling (1/2, 1/4, 1/8) and the linear-light decode path.
+public sealed class JpegScalingTests(TestContext context)
+{
+ private const int W = 256, H = 192;
+
+ [Theory]
+ [Case(0, 256, 192)]
+ [Case(200, 256, 192)]
+ [Case(128, 128, 96)]
+ [Case(100, 128, 96)]
+ [Case(64, 64, 48)]
+ [Case(33, 64, 48)]
+ [Case(32, 32, 24)]
+ [Case(1, 32, 24)]
+ public void MaxLongEdgePicksSmallestSufficientScale(int maxLongEdge, int width, int height)
+ {
+ var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3);
+ var image = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = maxLongEdge });
+ Assert.Equal(width, image.Width);
+ Assert.Equal(height, image.Height);
+ Assert.Equal(W, image.Info.Width);
+ }
+
+ [Theory]
+ [Case(2, 38.0)]
+ [Case(4, 34.0)]
+ [Case(8, 30.0)]
+ public void ScaledDecodeApproximatesAreaAverage(int factor, double minPsnr)
+ {
+ var jpeg = JpegEncoder.Encode(SmoothImage(W, H), W, H, 3, new JpegEncodeOptions { Quality = 92 });
+ var full = JpegDecoder.Decode(jpeg).Pixels8!;
+ var scaled = JpegDecoder.Decode(jpeg, new JpegDecodeOptions { MaxLongEdge = W / factor });
+ Assert.Equal(W / factor, scaled.Width);
+ int sw = W / factor, sh = H / factor;
+ var expected = new byte[sw * sh * 3];
+ for (var y = 0; y < sh; y++)
+ {
+ for (var x = 0; x < sw; x++)
+ {
+ for (var c = 0; c < 3; c++)
+ {
+ var sum = 0;
+ for (var dy = 0; dy < factor; dy++)
+ {
+ for (var dx = 0; dx < factor; dx++) sum += full[((y * factor + dy) * W + x * factor + dx) * 3 + c];
+ }
+ expected[(y * sw + x) * 3 + c] = (byte)((sum + factor * factor / 2) / (factor * factor));
+ }
+ }
+ }
+ var psnr = Psnr(scaled.Pixels8, expected);
+ context.Log($"1/{factor}: {psnr:F1} dB vs area average");
+ Assert.Greater(psnr, minPsnr);
+ }
+
+ [Test]
+ public void ScaledOddSizeKeepsEdges()
+ {
+ var image = JpegDecoder.Decode(Fixture("jpeg/b420.jpg"), new JpegDecodeOptions { MaxLongEdge = 31 });
+ Assert.Equal(31, image.Width);
+ Assert.Equal(23, image.Height);
+ var reference = ReadPnm(Fixture("src.ppm"));
+ // Bottom-right pixel of the scaled image must still resemble the source corner (no padding garbage).
+ var pixels = image.Pixels8!;
+ var last = pixels.AsSpan(pixels.Length - 3);
+ var src = reference.Samples.AsSpan(reference.Samples.Length - 3);
+ for (var c = 0; c < 3; c++) Assert.InRange(last[c], src[c] - 70, src[c] + 70);
+ }
+
+ [Test]
+ public void LinearDecodeMatchesLookupOfEightBitDecode()
+ {
+ var data = Fixture("jpeg/b422.jpg");
+ var bytes = JpegDecoder.Decode(data).Pixels8!;
+ using var linear = JpegDecoder.DecodeToLinear(data);
+ Assert.Equal(3, linear.Channels);
+ for (var i = 0; i < 61 * 45; i += 17)
+ {
+ for (var c = 0; c < 3; c++) Assert.Equal(ColorSpace.Linear8(bytes[i * 3 + c]), linear.Plane(c)[i]);
+ }
+ using var gray = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg"));
+ Assert.Equal(1, gray.Channels);
+ using var expanded = JpegDecoder.DecodeToLinear(Fixture("jpeg/gray.jpg"), expandGray: true);
+ Assert.Equal(3, expanded.Channels);
+ Assert.SequenceEqual(gray.Plane(0).ToArray(), expanded.Plane(2).ToArray());
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs b/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs
new file mode 100644
index 00000000..b9d00ecb
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/LinearDngWriterTests.cs
@@ -0,0 +1,124 @@
+using Titano.Core.Codecs.Dng;
+using Titano.Core.Codecs.Tiff;
+using Titano.Core.Imaging;
+using Titano.Core.Metadata.Tiff;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Codecs;
+
+public sealed class LinearDngWriterTests
+{
+ private static ImageBuffer Scene(int w, int h)
+ {
+ var image = new ImageBuffer(w, h);
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++)
+ {
+ image[0, x, y] = x / (float)(w - 1);
+ image[1, x, y] = y / (float)(h - 1) * 0.6f;
+ image[2, x, y] = (x * y % 97) / 96f;
+ }
+ }
+ image[0, 0, 0] = 1.7f; // highlight above white: clipped
+ return image;
+ }
+
+ [Theory]
+ [Case(DngCompression.LosslessJpeg)]
+ [Case(DngCompression.Uncompressed)]
+ public void PixelsRoundTripThroughTheTiffReader(DngCompression compression)
+ {
+ using var image = Scene(300, 70);
+ var dng = LinearDngWriter.Write(image, new LinearDngOptions { Compression = compression, TileSize = 128 });
+ var reader = TiffReader.Open(new MemoryStream(dng))!;
+ var raster = TiffImageReader.ReadRaster(reader, reader.ReadChain()[0]);
+ Assert.Empty(raster.Warnings);
+ Assert.Equal(34892, raster.Photometric);
+ Assert.SequenceEqual(PixelConvert.ToInterleaved16(image, 3, TransferFunction.Linear), raster.Samples!);
+ using var back = TiffImageReader.Decode(dng);
+ Assert.Approximately(1.0, back[0, 0, 0], 1e-6);
+ for (var i = 1; i < image.Data.Length; i += 37)
+ {
+ Assert.Approximately(Math.Clamp(image.Data[i], 0, 1), back.Data[i], 1.0 / 65535);
+ }
+ }
+
+ [Test]
+ public void TagsDescribeLinearRec709()
+ {
+ using var image = Scene(40, 30);
+ var dng = LinearDngWriter.Write(image);
+ var r = TiffReader.Open(new MemoryStream(dng))!;
+ Assert.True(r.LittleEndian);
+ var ifd = r.ReadChain()[0];
+ Assert.SequenceEqual(new uint[] { 1, 4, 0, 0 }, r.GetUInts(ifd, TiffTags.DngVersion)!);
+ Assert.Equal(0u, r.GetUInt(ifd, TiffTags.NewSubfileType));
+ Assert.Equal(34892u, r.GetUInt(ifd, TiffTags.PhotometricInterpretation));
+ Assert.Equal(3u, r.GetUInt(ifd, TiffTags.SamplesPerPixel));
+ Assert.SequenceEqual(new uint[] { 16, 16, 16 }, r.GetUInts(ifd, TiffTags.BitsPerSample)!);
+ Assert.Equal(7u, r.GetUInt(ifd, TiffTags.Compression));
+ Assert.Equal("Titano", r.GetString(ifd, TiffTags.UniqueCameraModel));
+ Assert.Equal(21u, r.GetUInt(ifd, TiffTags.CalibrationIlluminant1));
+ Assert.SequenceEqual(new[] { 1.0, 1.0, 1.0 }, r.GetDoubles(ifd, TiffTags.AsShotNeutral)!);
+ Assert.Equal(0.0, r.GetDouble(ifd, TiffTags.BaselineExposure));
+ Assert.SequenceEqual(new uint[] { 65535, 65535, 65535 }, r.GetUInts(ifd, TiffTags.WhiteLevel)!);
+ Assert.True(ifd.Has(TiffTags.TileWidth) && ifd.Has(TiffTags.TileOffsets) && ifd.Has(TiffTags.TileByteCounts));
+
+ // ColorMatrix1 maps XYZ to camera space: D65 white must land on the camera neutral (1, 1, 1),
+ // and its product with sRGB → XYZ(D65) must be the identity (camera space = linear sRGB).
+ var cm = r.GetDoubles(ifd, TiffTags.ColorMatrix1)!;
+ Assert.Equal(9, cm.Length);
+ double[] d65 = [0.95047, 1.0, 1.08883];
+ double[] srgbToXyz = [0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041];
+ for (var row = 0; row < 3; row++)
+ {
+ Assert.Approximately(1.0, cm[row * 3] * d65[0] + cm[row * 3 + 1] * d65[1] + cm[row * 3 + 2] * d65[2], 2e-3);
+ for (var col = 0; col < 3; col++)
+ {
+ var p = 0.0;
+ for (var k = 0; k < 3; k++) p += cm[row * 3 + k] * srgbToXyz[k * 3 + col];
+ Assert.Approximately(row == col ? 1 : 0, p, 2e-4);
+ }
+ }
+ // ForwardMatrix1 maps the white-balanced neutral to D50 (the DNG SDK's xy 0.3457, 0.3585).
+ var fm = r.GetDoubles(ifd, TiffTags.ForwardMatrix1)!;
+ double[] d50 = [0.3457 / 0.3585, 1.0, (1 - 0.3457 - 0.3585) / 0.3585];
+ for (var row = 0; row < 3; row++) Assert.Approximately(d50[row], fm[row * 3] + fm[row * 3 + 1] + fm[row * 3 + 2], 3e-4);
+ }
+
+ [Test]
+ public void GrayInputExifAndNonSeekableOutput()
+ {
+ using var gray = new ImageBuffer(33, 20, 1);
+ for (var i = 0; i < gray.PlaneLength; i++) gray.Plane(0)[i] = i / (float)gray.PlaneLength;
+ using var sink = new MemoryStream();
+ LinearDngWriter.Write(new ForwardOnlyStream(sink), gray, new LinearDngOptions { Exif = TiffTests.ExifBlock() });
+ var dng = sink.ToArray();
+ TiffTests.AssertExif(dng);
+ using var back = TiffImageReader.Decode(dng);
+ Assert.Equal(3, back.Channels);
+ Assert.Approximately(gray[0, 20, 10], back[2, 20, 10], 1.0 / 65535);
+ }
+
+ /// A write-only, non-seekable stream (pipes, network) to exercise the buffering path.
+ private sealed class ForwardOnlyStream(Stream inner) : Stream
+ {
+ public override bool CanRead => false;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
+ 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 origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ }
+}
diff --git a/tests/Titano.Core.Tests/Codecs/PngTests.cs b/tests/Titano.Core.Tests/Codecs/PngTests.cs
new file mode 100644
index 00000000..636902a4
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/PngTests.cs
@@ -0,0 +1,278 @@
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Titano.Core.Codecs.Png;
+using Titano.Core.Imaging;
+using Titano.Testing;
+using static Titano.Core.Tests.Codecs.CodecTestData;
+
+namespace Titano.Core.Tests.Codecs;
+
+public sealed class PngTests(TestContext context)
+{
+ [Theory]
+ [Case("png/adam7.png", false)]
+ [Case("png/rgb16.png", true)]
+ [Case("png/adam7-16.png", true)]
+ public void RgbFixturesMatchSource(string name, bool sixteen)
+ {
+ var image = PngDecoder.Decode(Fixture(name));
+ Assert.Equal(3, image.Channels);
+ Assert.Empty(image.Warnings);
+ if (sixteen) Assert.SequenceEqual(ReadPnm(Fixture("src16.ppm")).Words, image.Pixels16!);
+ else Assert.SequenceEqual(ReadPnm(Fixture("src.ppm")).Bytes, image.Pixels8!);
+ }
+
+ [Theory]
+ [Case("gray1", 1)]
+ [Case("gray2", 1)]
+ [Case("gray4", 1)]
+ [Case("gray8", 1)]
+ [Case("graya", 2)]
+ [Case("palette4", 3)]
+ [Case("palette-adam7", 3)]
+ [Case("palette-trns", 4)]
+ [Case("rgba", 4)]
+ public void LibpngFixturesMatchReference(string name, int channels)
+ {
+ var image = PngDecoder.Decode(Fixture($"png/{name}.png"));
+ var reference = ReadPnm(Fixture($"png/{name}.pam"));
+ Assert.Equal(channels, image.Channels);
+ Assert.Empty(image.Warnings);
+ var pixels = image.Pixels8!;
+ for (var i = 0; i < image.Width * image.Height; i++)
+ {
+ for (var c = 0; c < channels; c++)
+ {
+ // ImageMagick expands gray to RGB in PAM; compare against its first channel.
+ var refChannel = reference.Channels == channels ? c : c == channels - 1 && channels == 2 ? reference.Channels - 1 : 0;
+ if (pixels[i * channels + c] != reference.Samples[i * reference.Channels + refChannel])
+ Assert.Fail($"{name}: pixel {i} channel {c}: {pixels[i * channels + c]} vs {reference.Samples[i * reference.Channels + refChannel]}");
+ }
+ }
+ }
+
+ [Theory]
+ [Case(PngColorType.Gray, 8)]
+ [Case(PngColorType.Gray, 16)]
+ [Case(PngColorType.GrayAlpha, 8)]
+ [Case(PngColorType.GrayAlpha, 16)]
+ [Case(PngColorType.Rgb, 8)]
+ [Case(PngColorType.Rgb, 16)]
+ [Case(PngColorType.Rgba, 8)]
+ [Case(PngColorType.Rgba, 16)]
+ public void EncoderRoundTrips(PngColorType type, int depth)
+ {
+ const int w = 37, h = 21;
+ var channels = type switch { PngColorType.Gray => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
+ var bytes = new byte[w * h * channels * depth / 8];
+ new Random(depth * 10 + channels).NextBytes(bytes.AsSpan(bytes.Length / 2));
+ for (var i = 0; i < bytes.Length / 2; i++) bytes[i] = (byte)(i * 7);
+ var image = PngDecoder.Decode(PngEncoder.Encode(bytes, w, h, type, depth));
+ Assert.Equal(channels, image.Channels);
+ if (depth == 8)
+ {
+ Assert.SequenceEqual(bytes, image.Pixels8!);
+ }
+ else
+ {
+ var words = new ushort[bytes.Length / 2];
+ for (var i = 0; i < words.Length; i++) words[i] = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(2 * i));
+ Assert.SequenceEqual(words, image.Pixels16!);
+ }
+ }
+
+ [Theory]
+ [Case(0)]
+ [Case(1)]
+ [Case(2)]
+ [Case(3)]
+ [Case(4)]
+ public void EveryFilterTypeDecodes(int filter)
+ {
+ const int w = 23, h = 9;
+ var rgb = TestCard(w, h);
+ var png = RawPng(w, h, PngColorType.Rgb, 8, rgb, filter);
+ Assert.SequenceEqual(rgb, PngDecoder.Decode(png).Pixels8!);
+ var rgba16 = new byte[w * h * 8];
+ new Random(filter).NextBytes(rgba16);
+ var wide = PngDecoder.Decode(RawPng(w, h, PngColorType.Rgba, 16, rgba16, filter, interlaced: true));
+ Assert.Equal((ushort)(rgba16[8 * 5] << 8 | rgba16[8 * 5 + 1]), wide.Pixels16![4 * 5]);
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(2)]
+ [Case(4)]
+ public void SubBytePaletteWithTransparency(int depth)
+ {
+ const int w = 13, h = 7;
+ var colours = 1 << depth;
+ var indices = new byte[w * h];
+ for (var i = 0; i < indices.Length; i++) indices[i] = (byte)(i * 5 % colours);
+ var packed = Pack(indices, w, h, depth);
+ var plte = new byte[colours * 3];
+ for (var i = 0; i < plte.Length; i++) plte[i] = (byte)(i * 37);
+ var trns = new byte[] { 0, 128 };
+ var png = RawPng(w, h, PngColorType.Palette, depth, packed, 4, interlaced: depth == 2, ("PLTE", plte), ("tRNS", trns));
+ var image = PngDecoder.Decode(png);
+ Assert.Equal(4, image.Channels);
+ for (var i = 0; i < indices.Length; i++)
+ {
+ int idx = indices[i];
+ Assert.Equal(plte[3 * idx + 1], image.Pixels8![4 * i + 1]);
+ Assert.Equal(idx < trns.Length ? trns[idx] : (byte)255, image.Pixels8[4 * i + 3]);
+ }
+ }
+
+ [Test]
+ public void ColourKeyTransparency()
+ {
+ var gray = PngDecoder.Decode(RawPng(4, 1, PngColorType.Gray, 4, [0x0F, 0x3F], 0, false, ("tRNS", [0, 3])));
+ Assert.SequenceEqual(new byte[] { 0, 255, 255, 255, 51, 0, 255, 255 }, gray.Pixels8!);
+ var rgb16 = new byte[12];
+ rgb16[1] = 9;
+ var keyed = PngDecoder.Decode(RawPng(2, 1, PngColorType.Rgb, 16, rgb16, 1, false, ("tRNS", [0, 0, 0, 0, 0, 0])));
+ Assert.Equal(4, keyed.Channels);
+ Assert.Equal(ushort.MaxValue, keyed.Pixels16![3]);
+ Assert.Equal((ushort)0, keyed.Pixels16[7]);
+ }
+
+ [Test]
+ public void CrcMismatchIsToleratedWithWarning()
+ {
+ var png = PngEncoder.Encode(TestCard(8, 8), 8, 8, PngColorType.Rgb);
+ png[^13] ^= 0xFF; // last byte of the IDAT CRC (IEND is the final 12 bytes)
+ var image = PngDecoder.Decode(png);
+ Assert.SequenceEqual(TestCard(8, 8), image.Pixels8!);
+ Assert.Contains("CRC", string.Join(";", image.Warnings));
+ }
+
+ [Test]
+ public void ImageBufferRoundTripsAtSixteenBits()
+ {
+ using var image = new ImageBuffer(33, 17, 4);
+ for (var c = 0; c < 4; c++)
+ {
+ var plane = image.Plane(c);
+ for (var i = 0; i < plane.Length; i++) plane[i] = (i * (c + 1) % 97) / 96f;
+ }
+ var png = PngEncoder.Encode(image, 16);
+ Assert.True(png.AsSpan().IndexOf("sRGB"u8) > 0, "sRGB chunk");
+ using var back = PngDecoder.DecodeToLinear(png, keepAlpha: true);
+ Assert.Equal(4, back.Channels);
+ for (var i = 0; i < image.Data.Length; i += 13) Assert.Approximately(image.Data[i], back.Data[i], 2e-4);
+ using var eight = PngDecoder.DecodeToLinear(PngEncoder.Encode(image));
+ Assert.Equal(3, eight.Channels);
+ Assert.Approximately(image[1, 5, 5], eight[1, 5, 5], 0.01);
+ }
+
+ [Theory]
+ [Case("png/adam7.png")]
+ [Case("png/palette-trns.png")]
+ [Case("png/gray2.png")]
+ [Case("png/adam7-16.png")]
+ public void FuzzedInputOnlyThrowsInvalidData(string name)
+ {
+ int ok = 0, rejected = 0;
+ foreach (var input in Corruptions(Fixture(name), 150, seed: name.Length))
+ {
+ try
+ {
+ var image = PngDecoder.Decode(input);
+ Assert.True(image.Width > 0);
+ ok++;
+ }
+ catch (InvalidDataException)
+ {
+ rejected++;
+ }
+ }
+ context.Log($"{name}: {ok} decoded, {rejected} rejected");
+ }
+
+ [Test]
+ public void StructuralErrorsAreRejected()
+ {
+ Assert.Throws(() => PngDecoder.Decode([]));
+ Assert.Throws(() => PngDecoder.Decode(Fixture("jpeg/b420.jpg")));
+ var palette = Fixture("png/palette4.png");
+ var plte = palette.AsSpan().IndexOf("PLTE"u8);
+ palette[plte] = (byte)'X'; // drop the palette (and make an unknown critical chunk)
+ Assert.Throws(() => PngDecoder.Decode(palette));
+ Assert.Throws(() => PngEncoder.Encode(new byte[4], 2, 2, PngColorType.Palette));
+ }
+
+ /// Builds a PNG with every row filtered by (test-side writer).
+ private static byte[] RawPng(int w, int h, PngColorType type, int depth, byte[] rows, int filter, bool interlaced = false, params (string Type, byte[] Data)[] chunks)
+ {
+ var channels = type switch { PngColorType.Gray or PngColorType.Palette => 1, PngColorType.GrayAlpha => 2, PngColorType.Rgb => 3, _ => 4 };
+ var bits = channels * depth;
+ var bpp = Math.Max(1, bits / 8);
+ var stride = (w * bits + 7) / 8;
+ var passes = interlaced
+ ? new[] { (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2) }
+ : [(0, 0, 1, 1)];
+ using var raw = new MemoryStream();
+ foreach (var (px, py, dx, dy) in passes)
+ {
+ if (px >= w || py >= h) continue;
+ var count = (w - px + dx - 1) / dx;
+ var rowBytes = (count * bits + 7) / 8;
+ var prev = new byte[rowBytes];
+ for (var y = py; y < h; y += dy)
+ {
+ // Gather this pass's pixels (bit-exact copy of their samples).
+ var row = new byte[rowBytes];
+ for (int i = 0, x = px; i < count; i++, x += dx)
+ {
+ for (var b = 0; b < bits; b++)
+ {
+ var src = y * stride * 8 + x * bits + b;
+ if ((rows[src >> 3] >> (7 - (src & 7)) & 1) != 0) row[(i * bits + b) >> 3] |= (byte)(0x80 >> ((i * bits + b) & 7));
+ }
+ }
+ raw.WriteByte((byte)filter);
+ for (var i = 0; i < rowBytes; i++)
+ {
+ int a = i >= bpp ? row[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0;
+ var predicted = filter switch { 0 => 0, 1 => a, 2 => b, 3 => (a + b) >> 1, _ => PngEncoder.Paeth(a, b, c) };
+ raw.WriteByte((byte)(row[i] - predicted));
+ }
+ prev = row;
+ }
+ }
+ using var z = new MemoryStream();
+ using (var deflate = new ZLibStream(z, CompressionLevel.Fastest, leaveOpen: true)) deflate.Write(raw.ToArray());
+ using var png = new MemoryStream();
+ png.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
+ var ihdr = new byte[13];
+ BinaryPrimitives.WriteInt32BigEndian(ihdr, w);
+ BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), h);
+ ihdr[8] = (byte)depth;
+ ihdr[9] = (byte)type;
+ ihdr[12] = (byte)(interlaced ? 1 : 0);
+ PngEncoder.WriteChunk(png, "IHDR", ihdr);
+ foreach (var (t, d) in chunks) PngEncoder.WriteChunk(png, t, d);
+ var compressed = z.ToArray();
+ var half = compressed.Length / 2;
+ PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(0, half));
+ PngEncoder.WriteChunk(png, "IDAT", compressed.AsSpan(half));
+ PngEncoder.WriteChunk(png, "IEND", []);
+ return png.ToArray();
+ }
+
+ private static byte[] Pack(byte[] values, int w, int h, int depth)
+ {
+ var stride = (w * depth + 7) / 8;
+ var packed = new byte[stride * h];
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++)
+ {
+ var bit = x * depth;
+ packed[y * stride + (bit >> 3)] |= (byte)(values[y * w + x] << (8 - depth - (bit & 7)));
+ }
+ }
+ return packed;
+ }
+}
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..c5414c95
--- /dev/null
+++ b/tests/Titano.Core.Tests/Codecs/TiffTests.cs
@@ -0,0 +1,329 @@
+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 SingleStripLargerThanTheReaderCapDecodes()
+ {
+ // Photoshop-style single uncompressed strip of 70 MB (TiffReader reads at most 64 MB per call).
+ const int w = 5000, h = 7000;
+ var strip = new byte[w * h * 2];
+ for (var i = 0; i < strip.Length; i += 2) BinaryPrimitives.WriteUInt16LittleEndian(strip.AsSpan(i), (ushort)(i * 7));
+ var tiff = TiffTestEncoders.Build(d => Layout(d, w, h, 1, 16, compression: 1), [strip], tiled: false);
+ var raster = Raster(tiff);
+ Assert.Empty(raster.Warnings);
+ Assert.Equal(unchecked((ushort)((w * h - 1) * 2 * 7)), raster.Samples![^1]);
+ Assert.Equal(unchecked((ushort)(12345 * 2 * 7)), raster.Samples[12345]);
+ }
+
+ [Test]
+ public void PackedTwelveBitSamplesUnpack()
+ {
+ 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/Titano.Core.Tests/Imaging/PixelConvertTests.cs b/tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs
new file mode 100644
index 00000000..17b2954e
--- /dev/null
+++ b/tests/Titano.Core.Tests/Imaging/PixelConvertTests.cs
@@ -0,0 +1,128 @@
+using Titano.Core.Imaging;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Imaging;
+
+public sealed class PixelConvertTests
+{
+ [Theory]
+ [Case(1)]
+ [Case(2)]
+ [Case(3)]
+ [Case(4)]
+ public void EightBitRoundTripIsExact(int channels)
+ {
+ const int w = 19, h = 7;
+ var pixels = new byte[w * h * channels];
+ new Random(channels).NextBytes(pixels);
+ var keepAlpha = channels is 2 or 4;
+ using var image = PixelConvert.FromInterleaved8(pixels, w, h, channels, outputChannels: keepAlpha ? 4 : 0);
+ Assert.Equal(keepAlpha ? 4 : channels == 1 ? 1 : 3, image.Channels);
+ var back = PixelConvert.ToInterleaved8(image, channels);
+ Assert.SequenceEqual(pixels, back);
+ }
+
+ [Test]
+ public void SixteenBitRoundTripWithinOneCode()
+ {
+ var samples = Enumerable.Range(0, 3 * 4096).Select(i => (ushort)(i * 16 % 65536)).ToArray();
+ using var image = PixelConvert.FromInterleaved16(samples, 64, 64, 3);
+ var back = PixelConvert.ToInterleaved16(image, 3);
+ for (var i = 0; i < samples.Length; i++) Assert.InRange(back[i], samples[i] - 1, samples[i] + 1);
+ using var linear = PixelConvert.FromInterleaved16(samples, 64, 64, 3, TransferFunction.Linear);
+ Assert.SequenceEqual(samples, PixelConvert.ToInterleaved16(linear, 3, TransferFunction.Linear));
+ }
+
+ [Test]
+ public void CustomMaximumScalesTwelveBitData()
+ {
+ ushort[] samples = [0, 2048, 4095];
+ using var image = PixelConvert.FromInterleaved16(samples, 3, 1, 1, TransferFunction.Linear, maxValue: 4095);
+ Assert.Approximately(2048 / 4095.0, image[0, 1, 0], 1e-6);
+ Assert.Equal(1f, image[0, 2, 0]);
+ }
+
+ [Test]
+ public void GrayRgbConversions()
+ {
+ using var gray = PixelConvert.FromInterleaved8([0, 128, 255], 3, 1, 1);
+ using var rgb = PixelConvert.GrayToRgb(gray);
+ Assert.Equal(3, rgb.Channels);
+ Assert.Equal(gray[0, 1, 0], rgb[2, 1, 0]);
+ using var back = PixelConvert.RgbToGray(rgb);
+ Assert.Approximately(gray[0, 1, 0], back[0, 1, 0], 1e-6);
+ using var colour = PixelConvert.FromInterleaved8([255, 0, 0], 1, 1, 3, TransferFunction.Linear);
+ Assert.Equal((byte)Math.Round(ColorSpace.LinearToSrgb(ColorSpace.LumaR) * 255), PixelConvert.ToInterleaved8(colour, 1)[0]);
+ }
+
+ [Theory]
+ [Case(1)]
+ [Case(2)]
+ [Case(3)]
+ [Case(4)]
+ [Case(5)]
+ [Case(6)]
+ [Case(7)]
+ [Case(8)]
+ public void OrientationMatchesExifDefinition(int orientation)
+ {
+ // A 3×2 image with unique values; Exif row 0 / column 0 placement per orientation (CIPA DC-008 table).
+ using var source = new ImageBuffer(3, 2, 1);
+ for (var i = 0; i < 6; i++) source.Plane(0)[i] = i;
+ using var result = PixelConvert.ApplyOrientation(source, orientation);
+ float[] expected = orientation switch
+ {
+ 1 => [0, 1, 2, 3, 4, 5],
+ 2 => [2, 1, 0, 5, 4, 3],
+ 3 => [5, 4, 3, 2, 1, 0],
+ 4 => [3, 4, 5, 0, 1, 2],
+ 5 => [0, 3, 1, 4, 2, 5],
+ 6 => [3, 0, 4, 1, 5, 2],
+ 7 => [5, 2, 4, 1, 3, 0],
+ _ => [2, 5, 1, 4, 0, 3],
+ };
+ Assert.Equal(orientation >= 5 ? 2 : 3, result.Width);
+ Assert.SequenceEqual(expected, result.Plane(0).ToArray());
+ }
+
+ [Test]
+ public void LargeOrientationUsesTilesCorrectly()
+ {
+ using var source = new ImageBuffer(301, 157, 3);
+ for (var i = 0; i < source.Data.Length; i++) source.Data[i] = i;
+ using var rotated = PixelConvert.ApplyOrientation(source, 6);
+ using var back = PixelConvert.ApplyOrientation(rotated, 8);
+ Assert.SequenceEqual(source.Data.ToArray(), back.Data.ToArray());
+ }
+
+ [Test]
+ public void ClampHandlesNaNAndRange()
+ {
+ var values = Enumerable.Range(0, 37).Select(i => i % 5 == 0 ? float.NaN : i / 10f - 1f).ToArray();
+ PixelConvert.Clamp(values);
+ for (var i = 0; i < values.Length; i++) Assert.InRange(values[i], 0, 1);
+ Assert.Equal(0f, values[5]);
+ }
+
+ [Test]
+ public void DitherBreaksBandingButKeepsTheMean()
+ {
+ using var ramp = new ImageBuffer(256, 64, 1);
+ for (var y = 0; y < 64; y++)
+ {
+ for (var x = 0; x < 256; x++) ramp[0, x, y] = (float)ColorSpace.SrgbToLinear((100 + x / 64.0) / 255);
+ }
+ var plain = PixelConvert.ToInterleaved8(ramp, 1);
+ var dithered = PixelConvert.ToInterleaved8(ramp, 1, dither: true);
+ Assert.True(plain.Distinct().Count() <= 5, "a 4-code ramp quantises to few levels");
+ for (var x0 = 0; x0 < 256; x0 += 64)
+ {
+ var mean = 0.0;
+ for (var y = 0; y < 64; y++)
+ {
+ for (var x = x0; x < x0 + 64; x++) mean += dithered[y * 256 + x];
+ }
+ Assert.Approximately(100 + (x0 + 31.5) / 64.0, mean / (64 * 64), 0.15);
+ }
+ }
+}
diff --git a/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs b/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs
new file mode 100644
index 00000000..4497cebb
--- /dev/null
+++ b/tests/Titano.Core.Tests/Imaging/ResamplerTests.cs
@@ -0,0 +1,156 @@
+using System.Diagnostics;
+using Titano.Core.Imaging;
+using Titano.Testing;
+
+namespace Titano.Core.Tests.Imaging;
+
+public sealed class ResamplerTests(TestContext context)
+{
+ private static ImageBuffer Filled(int w, int h, Func value, int channels = 3)
+ {
+ var image = new ImageBuffer(w, h, channels);
+ for (var c = 0; c < channels; c++)
+ {
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++) image[c, x, y] = value(c, x, y);
+ }
+ }
+ return image;
+ }
+
+ [Theory]
+ [Case(ResampleFilter.Lanczos3, 97, 31)]
+ [Case(ResampleFilter.Lanczos3, 400, 260)]
+ [Case(ResampleFilter.CatmullRom, 400, 260)]
+ [Case(ResampleFilter.CatmullRom, 20, 15)]
+ [Case(ResampleFilter.Box, 37, 23)]
+ [Case(ResampleFilter.Box, 333, 211)]
+ [Case(ResampleFilter.Auto, 300, 40)]
+ public void ConstantImageStaysConstant(ResampleFilter filter, int width, int height)
+ {
+ using var source = Filled(150, 100, (c, _, _) => 0.25f + 0.25f * c);
+ using var result = Resampler.Resize(source, width, height, filter);
+ Assert.Equal(width, result.Width);
+ Assert.Equal(height, result.Height);
+ for (var c = 0; c < 3; c++)
+ {
+ foreach (var v in result.Plane(c)) Assert.Approximately(0.25 + 0.25 * c, v, 1e-5);
+ }
+ }
+
+ [Theory]
+ [Case(ResampleFilter.Lanczos3)]
+ [Case(ResampleFilter.Box)]
+ [Case(ResampleFilter.CatmullRom)]
+ public void DownscalePreservesEnergy(ResampleFilter filter)
+ {
+ var rng = new Random(4);
+ using var source = Filled(640, 480, (_, x, y) => (float)(rng.NextDouble() * 0.5 + 0.4 * Math.Sin(x * 0.05) * Math.Cos(y * 0.07) + 0.4), 1);
+ using var result = Resampler.Resize(source, 213, 157, filter);
+ double Mean(ImageBuffer b) => b.Plane(0).ToArray().Average(v => (double)v);
+ var ratio = Mean(result) / Mean(source);
+ context.Log($"{filter}: mean ratio {ratio:F5}");
+ Assert.Approximately(1, ratio, 0.005);
+ }
+
+ [Theory]
+ [Case(ResampleFilter.Lanczos3, 0.3)]
+ [Case(ResampleFilter.Lanczos3, 2.7)]
+ [Case(ResampleFilter.CatmullRom, 3.0)]
+ [Case(ResampleFilter.CatmullRom, 0.45)]
+ [Case(ResampleFilter.Box, 0.3)]
+ public void StepRingingStaysWithinKernelBounds(ResampleFilter filter, double scale)
+ {
+ const int w = 200;
+ using var step = Filled(w, 4, (_, x, _) => x < w / 2 + 0.3 ? 0f : 1f, 1);
+ using var result = Resampler.Resize(step, (int)(w * scale), 4, filter);
+ var values = result.Row(0, 1).ToArray();
+ var bound = StepBound(filter, scale);
+ context.Log($"{filter} ×{scale}: range [{values.Min():F4}, {values.Max():F4}], bound {bound:F4}");
+ Assert.GreaterOrEqual(values.Min(), -bound - 1e-4);
+ Assert.LessOrEqual(values.Max(), 1 + bound + 1e-4);
+ if (filter == ResampleFilter.Box)
+ {
+ Assert.GreaterOrEqual(values.Min(), 0);
+ Assert.LessOrEqual(values.Max(), 1 + 1e-6);
+ }
+ Assert.Approximately(0, values[0], 1e-5);
+ Assert.Approximately(1, values[^1], 1e-5);
+ }
+
+ ///
+ /// The "Lanczos bound" for a step at this scale: every output sample is a normalised sum of kernel taps spaced
+ /// 1/stretch apart, so on a step it equals a partial sum of those taps. The bound is the largest excursion
+ /// outside [0, 1] of any partial sum, over all sub-pixel phases.
+ ///
+ private static double StepBound(ResampleFilter filter, double scale)
+ {
+ if (filter == ResampleFilter.Box) return 0;
+ var radius = filter == ResampleFilter.Lanczos3 ? 3.0 : 2.0;
+ var stretch = Math.Max(1, 1 / scale);
+ var reach = (int)Math.Ceiling(radius * stretch) + 1;
+ var worst = 0.0;
+ for (var phase = 0.0; phase < 1; phase += 1 / 512.0)
+ {
+ var taps = new List();
+ for (var k = -reach; k <= reach; k++) taps.Add(Kernel(filter, (k + phase) / stretch));
+ var total = taps.Sum();
+ var running = 0.0;
+ foreach (var t in taps)
+ {
+ running += t / total;
+ worst = Math.Max(worst, Math.Max(running - 1, -running));
+ }
+ }
+ return worst;
+ }
+
+ private static double Kernel(ResampleFilter filter, double x)
+ {
+ var a = Math.Abs(x);
+ if (filter == ResampleFilter.Lanczos3) return a < 1e-12 ? 1 : a >= 3 ? 0 : 3 * Math.Sin(Math.PI * a) * Math.Sin(Math.PI * a / 3) / (Math.PI * Math.PI * a * a);
+ return a < 1 ? (1.5 * a - 2.5) * a * a + 1 : a < 2 ? ((-0.5 * a + 2.5) * a - 4) * a + 2 : 0;
+ }
+
+ [Test]
+ public void ThumbnailFitsAndAveragesAreas()
+ {
+ using var source = Filled(1200, 800, (c, x, _) => x % 2 == 0 ? 1f : 0f);
+ using var thumb = Resampler.Thumbnail(source, 300);
+ Assert.Equal(300, thumb.Width);
+ Assert.Equal(200, thumb.Height);
+ foreach (var v in thumb.Plane(1)) Assert.Approximately(0.5, v, 1e-5);
+ Assert.Equal((300, 200), Resampler.FitWithin(1200, 800, 300));
+ Assert.Equal((10, 20), Resampler.FitWithin(10, 20, 300));
+ using var small = Resampler.Thumbnail(thumb, 1000);
+ Assert.Equal(300, small.Width);
+ }
+
+ [Test]
+ public void UpscaleInterpolatesThroughSamples()
+ {
+ using var source = Filled(16, 16, (_, x, y) => x * 0.05f + y * 0.01f, 1);
+ using var up = Resampler.Resize(source, 64, 64, ResampleFilter.CatmullRom);
+ // Catmull-Rom reproduces linear ramps exactly away from the edges.
+ for (var x = 8; x < 56; x++)
+ {
+ var sx = (x + 0.5) / 4 - 0.5;
+ Assert.Approximately(sx * 0.05 + ((20 + 0.5) / 4 - 0.5) * 0.01, up[0, x, 20], 1e-4);
+ }
+ }
+
+ [Test]
+ public void TwentyFourMegapixelThumbnailIsFast()
+ {
+ using var source = new ImageBuffer(6000, 4000, 3, clear: true);
+ var sw = Stopwatch.StartNew();
+ using var thumb = Resampler.Thumbnail(source, 320);
+ var box = sw.Elapsed;
+ sw.Restart();
+ using var lanczos = Resampler.Resize(source, 1920, 1280);
+ context.Log($"24 MP → 320 px box {box.TotalMilliseconds:F0} ms; → 1920 px Lanczos3 {sw.Elapsed.TotalMilliseconds:F0} ms");
+ Assert.Equal(320, thumb.Width);
+ Assert.Less(box.TotalSeconds, 2.5);
+ }
+}
diff --git a/tests/fixtures/codecs/jpeg/b411.jpg b/tests/fixtures/codecs/jpeg/b411.jpg
new file mode 100644
index 00000000..7331b1e5
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b411.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/b411.ppm b/tests/fixtures/codecs/jpeg/b411.ppm
new file mode 100644
index 00000000..e05451f9
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b411.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/b420-nosmooth.ppm b/tests/fixtures/codecs/jpeg/b420-nosmooth.ppm
new file mode 100644
index 00000000..f29d6a77
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b420-nosmooth.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/b420.jpg b/tests/fixtures/codecs/jpeg/b420.jpg
new file mode 100644
index 00000000..0181451d
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b420.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/b420.ppm b/tests/fixtures/codecs/jpeg/b420.ppm
new file mode 100644
index 00000000..4fada5ab
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b420.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/b422.jpg b/tests/fixtures/codecs/jpeg/b422.jpg
new file mode 100644
index 00000000..0624bc3a
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b422.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/b422.ppm b/tests/fixtures/codecs/jpeg/b422.ppm
new file mode 100644
index 00000000..37088094
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b422.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/b440.jpg b/tests/fixtures/codecs/jpeg/b440.jpg
new file mode 100644
index 00000000..e7294bbd
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b440.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/b440.ppm b/tests/fixtures/codecs/jpeg/b440.ppm
new file mode 100644
index 00000000..edb57f27
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b440.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/b444.jpg b/tests/fixtures/codecs/jpeg/b444.jpg
new file mode 100644
index 00000000..315fd5f5
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b444.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/b444.ppm b/tests/fixtures/codecs/jpeg/b444.ppm
new file mode 100644
index 00000000..2d0ce918
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/b444.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/cmyk.jpg b/tests/fixtures/codecs/jpeg/cmyk.jpg
new file mode 100644
index 00000000..a5fce73c
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/cmyk.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/gray.jpg b/tests/fixtures/codecs/jpeg/gray.jpg
new file mode 100644
index 00000000..86533a0f
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/gray.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/gray.pgm b/tests/fixtures/codecs/jpeg/gray.pgm
new file mode 100644
index 00000000..2a3b7f1d
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/gray.pgm differ
diff --git a/tests/fixtures/codecs/jpeg/p420.jpg b/tests/fixtures/codecs/jpeg/p420.jpg
new file mode 100644
index 00000000..cd78ae91
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/p420.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/p420.ppm b/tests/fixtures/codecs/jpeg/p420.ppm
new file mode 100644
index 00000000..0faf5be8
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/p420.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/p444.jpg b/tests/fixtures/codecs/jpeg/p444.jpg
new file mode 100644
index 00000000..064da6eb
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/p444.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/p444.ppm b/tests/fixtures/codecs/jpeg/p444.ppm
new file mode 100644
index 00000000..d4864ccd
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/p444.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/pgray.jpg b/tests/fixtures/codecs/jpeg/pgray.jpg
new file mode 100644
index 00000000..06b705b4
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/pgray.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/pgray.pgm b/tests/fixtures/codecs/jpeg/pgray.pgm
new file mode 100644
index 00000000..2a3b7f1d
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/pgray.pgm differ
diff --git a/tests/fixtures/codecs/jpeg/r420.jpg b/tests/fixtures/codecs/jpeg/r420.jpg
new file mode 100644
index 00000000..d831c18d
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/r420.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/r420.ppm b/tests/fixtures/codecs/jpeg/r420.ppm
new file mode 100644
index 00000000..86af7fd9
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/r420.ppm differ
diff --git a/tests/fixtures/codecs/jpeg/r444.jpg b/tests/fixtures/codecs/jpeg/r444.jpg
new file mode 100644
index 00000000..cebd1513
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/r444.jpg differ
diff --git a/tests/fixtures/codecs/jpeg/r444.ppm b/tests/fixtures/codecs/jpeg/r444.ppm
new file mode 100644
index 00000000..84db23e9
Binary files /dev/null and b/tests/fixtures/codecs/jpeg/r444.ppm differ
diff --git a/tests/fixtures/codecs/make-fixtures.sh b/tests/fixtures/codecs/make-fixtures.sh
new file mode 100755
index 00000000..f499e9f5
--- /dev/null
+++ b/tests/fixtures/codecs/make-fixtures.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# Regenerates the codec reference fixtures (dev-only tools: python3, libjpeg-turbo-progs, imagemagick, libtiff-tools).
+# Every output is < 50 KB. Run from this directory: ./make-fixtures.sh
+set -euo pipefail
+cd "$(dirname "$0")"
+mkdir -p jpeg png tiff
+
+# 61x45 source (odd size exercises MCU/tile padding): gradients, colour bars, seeded noise and hard edges.
+python3 - <<'EOF'
+import random
+W, H = 61, 45
+random.seed(7)
+px8, px16 = [], []
+for y in range(H):
+ for x in range(W):
+ if y < 15:
+ r, g, b = x / (W - 1), y / 14, 1 - x / (W - 1)
+ elif y < 30:
+ bar = (x * 8) // W
+ r, g, b = (bar >> 2) & 1, (bar >> 1) & 1, bar & 1
+ r, g, b = 0.1 + 0.8 * r, 0.1 + 0.8 * g, 0.1 + 0.8 * b
+ else:
+ n = random.random()
+ edge = 1.0 if ((x // 3) + (y // 3)) % 2 == 0 else 0.0
+ r, g, b = 0.6 * edge + 0.4 * n, 0.5 * n, 0.8 * edge
+ px8 += [round(v * 255) for v in (r, g, b)]
+ px16 += [round(v * 65535) for v in (r, g, b)]
+with open("src.ppm", "wb") as f:
+ f.write(b"P6\n%d %d\n255\n" % (W, H)); f.write(bytes(px8))
+with open("src16.ppm", "wb") as f:
+ f.write(b"P6\n%d %d\n65535\n" % (W, H))
+ f.write(b"".join(v.to_bytes(2, "big") for v in px16))
+EOF
+
+# JPEG: cjpeg encodes, djpeg (accurate integer IDCT, fancy upsampling) provides the reference pixels.
+for s in "444:1x1" "422:2x1" "420:2x2" "440:1x2" "411:4x1"; do
+ name=${s%%:*}; f=${s##*:}
+ cjpeg -quality 88 -sample "$f" src.ppm > "jpeg/b$name.jpg"
+ djpeg -ppm "jpeg/b$name.jpg" > "jpeg/b$name.ppm"
+done
+djpeg -nosmooth -ppm jpeg/b420.jpg > jpeg/b420-nosmooth.ppm
+cjpeg -quality 85 -sample 2x2 -progressive src.ppm > jpeg/p420.jpg && djpeg -ppm jpeg/p420.jpg > jpeg/p420.ppm
+cjpeg -quality 92 -sample 1x1 -progressive src.ppm > jpeg/p444.jpg && djpeg -ppm jpeg/p444.jpg > jpeg/p444.ppm
+cjpeg -quality 90 -sample 2x2 -restart 1 src.ppm > jpeg/r420.jpg && djpeg -ppm jpeg/r420.jpg > jpeg/r420.ppm
+cjpeg -quality 90 -sample 1x1 -restart 5B -optimize src.ppm > jpeg/r444.jpg && djpeg -ppm jpeg/r444.jpg > jpeg/r444.ppm
+cjpeg -quality 90 -grayscale src.ppm > jpeg/gray.jpg && djpeg -pnm jpeg/gray.jpg > jpeg/gray.pgm
+cjpeg -quality 90 -grayscale -progressive src.ppm > jpeg/pgray.jpg && djpeg -pnm jpeg/pgray.jpg > jpeg/pgray.pgm
+convert src.ppm -quality 95 -colorspace CMYK jpeg/cmyk.jpg
+
+# PNG: ImageMagick/libpng writers; pixels compare against src.ppm / src16.ppm.
+convert src.ppm -interlace PNG png24:png/adam7.png
+convert src16.ppm -define png:bit-depth=16 png48:png/rgb16.png
+convert src16.ppm -interlace PNG -define png:bit-depth=16 png48:png/adam7-16.png
+convert src.ppm -colorspace Gray -define png:color-type=0 -define png:bit-depth=8 png/gray8.png
+convert src.ppm -colorspace Gray -depth 4 -define png:color-type=0 -define png:bit-depth=4 png/gray4.png
+convert src.ppm -colorspace Gray -depth 2 -define png:color-type=0 -define png:bit-depth=2 png/gray2.png
+convert src.ppm -colorspace Gray -threshold 50% -define png:color-type=0 -define png:bit-depth=1 png/gray1.png
+convert src.ppm -colors 16 -transparent "$(convert src.ppm -colors 16 -format '%[pixel:p{0,40}]' info:)" png8:png/palette-trns.png
+convert src.ppm -colors 16 -interlace PNG png8:png/palette-adam7.png
+convert src.ppm -colors 12 -define png:color-type=3 -define png:bit-depth=4 png/palette4.png
+convert src.ppm \( src.ppm -colorspace Gray \) -alpha off -compose CopyOpacity -composite png32:png/rgba.png
+convert src.ppm -colorspace Gray \( src.ppm -channel R -separate \) -alpha off -compose CopyOpacity -composite -define png:color-type=4 png/graya.png
+for f in gray1 gray2 gray4 gray8 graya palette-trns palette-adam7 palette4 rgba; do convert "png/$f.png" -depth 8 "png/$f.pam"; done
+
+# TIFF: ImageMagick/libtiff writers in every supported layout and compression.
+convert src.ppm -compress LZW -define tiff:predictor=2 tiff/lzw-pred.tif
+convert src.ppm -compress RLE tiff/packbits.tif
+convert src.ppm -compress None -define tiff:rows-per-strip=7 tiff/none-strips.tif
+convert src16.ppm -depth 16 -compress Zip -define tiff:predictor=2 tiff/deflate16-pred.tif
+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/png/adam7-16.png b/tests/fixtures/codecs/png/adam7-16.png
new file mode 100644
index 00000000..cf5c5c4e
Binary files /dev/null and b/tests/fixtures/codecs/png/adam7-16.png differ
diff --git a/tests/fixtures/codecs/png/adam7.png b/tests/fixtures/codecs/png/adam7.png
new file mode 100644
index 00000000..0c03608f
Binary files /dev/null and b/tests/fixtures/codecs/png/adam7.png differ
diff --git a/tests/fixtures/codecs/png/gray1.pam b/tests/fixtures/codecs/png/gray1.pam
new file mode 100644
index 00000000..5927d797
Binary files /dev/null and b/tests/fixtures/codecs/png/gray1.pam differ
diff --git a/tests/fixtures/codecs/png/gray1.png b/tests/fixtures/codecs/png/gray1.png
new file mode 100644
index 00000000..c60c4723
Binary files /dev/null and b/tests/fixtures/codecs/png/gray1.png differ
diff --git a/tests/fixtures/codecs/png/gray2.pam b/tests/fixtures/codecs/png/gray2.pam
new file mode 100644
index 00000000..e5ea0dd9
Binary files /dev/null and b/tests/fixtures/codecs/png/gray2.pam differ
diff --git a/tests/fixtures/codecs/png/gray2.png b/tests/fixtures/codecs/png/gray2.png
new file mode 100644
index 00000000..2b998fd7
Binary files /dev/null and b/tests/fixtures/codecs/png/gray2.png differ
diff --git a/tests/fixtures/codecs/png/gray4.pam b/tests/fixtures/codecs/png/gray4.pam
new file mode 100644
index 00000000..3ddb45bd
Binary files /dev/null and b/tests/fixtures/codecs/png/gray4.pam differ
diff --git a/tests/fixtures/codecs/png/gray4.png b/tests/fixtures/codecs/png/gray4.png
new file mode 100644
index 00000000..e1d927f9
Binary files /dev/null and b/tests/fixtures/codecs/png/gray4.png differ
diff --git a/tests/fixtures/codecs/png/gray8.pam b/tests/fixtures/codecs/png/gray8.pam
new file mode 100644
index 00000000..83a4c570
Binary files /dev/null and b/tests/fixtures/codecs/png/gray8.pam differ
diff --git a/tests/fixtures/codecs/png/gray8.png b/tests/fixtures/codecs/png/gray8.png
new file mode 100644
index 00000000..45b3a890
Binary files /dev/null and b/tests/fixtures/codecs/png/gray8.png differ
diff --git a/tests/fixtures/codecs/png/graya.pam b/tests/fixtures/codecs/png/graya.pam
new file mode 100644
index 00000000..d12dfabe
Binary files /dev/null and b/tests/fixtures/codecs/png/graya.pam differ
diff --git a/tests/fixtures/codecs/png/graya.png b/tests/fixtures/codecs/png/graya.png
new file mode 100644
index 00000000..273e65c7
Binary files /dev/null and b/tests/fixtures/codecs/png/graya.png differ
diff --git a/tests/fixtures/codecs/png/palette-adam7.pam b/tests/fixtures/codecs/png/palette-adam7.pam
new file mode 100644
index 00000000..4ef76b4c
Binary files /dev/null and b/tests/fixtures/codecs/png/palette-adam7.pam differ
diff --git a/tests/fixtures/codecs/png/palette-adam7.png b/tests/fixtures/codecs/png/palette-adam7.png
new file mode 100644
index 00000000..6f333e4d
Binary files /dev/null and b/tests/fixtures/codecs/png/palette-adam7.png differ
diff --git a/tests/fixtures/codecs/png/palette-trns.pam b/tests/fixtures/codecs/png/palette-trns.pam
new file mode 100644
index 00000000..50bd0431
Binary files /dev/null and b/tests/fixtures/codecs/png/palette-trns.pam differ
diff --git a/tests/fixtures/codecs/png/palette-trns.png b/tests/fixtures/codecs/png/palette-trns.png
new file mode 100644
index 00000000..93807bb3
Binary files /dev/null and b/tests/fixtures/codecs/png/palette-trns.png differ
diff --git a/tests/fixtures/codecs/png/palette4.pam b/tests/fixtures/codecs/png/palette4.pam
new file mode 100644
index 00000000..0595ac69
Binary files /dev/null and b/tests/fixtures/codecs/png/palette4.pam differ
diff --git a/tests/fixtures/codecs/png/palette4.png b/tests/fixtures/codecs/png/palette4.png
new file mode 100644
index 00000000..38f588a6
Binary files /dev/null and b/tests/fixtures/codecs/png/palette4.png differ
diff --git a/tests/fixtures/codecs/png/rgb16.png b/tests/fixtures/codecs/png/rgb16.png
new file mode 100644
index 00000000..3b1269cc
Binary files /dev/null and b/tests/fixtures/codecs/png/rgb16.png differ
diff --git a/tests/fixtures/codecs/png/rgba.pam b/tests/fixtures/codecs/png/rgba.pam
new file mode 100644
index 00000000..9b59332c
Binary files /dev/null and b/tests/fixtures/codecs/png/rgba.pam differ
diff --git a/tests/fixtures/codecs/png/rgba.png b/tests/fixtures/codecs/png/rgba.png
new file mode 100644
index 00000000..2cf5a36f
Binary files /dev/null and b/tests/fixtures/codecs/png/rgba.png differ
diff --git a/tests/fixtures/codecs/src.ppm b/tests/fixtures/codecs/src.ppm
new file mode 100644
index 00000000..d0c8f458
Binary files /dev/null and b/tests/fixtures/codecs/src.ppm differ
diff --git a/tests/fixtures/codecs/src16.ppm b/tests/fixtures/codecs/src16.ppm
new file mode 100644
index 00000000..bf7e7d73
Binary files /dev/null and b/tests/fixtures/codecs/src16.ppm differ
diff --git a/tests/fixtures/codecs/tiff/deflate16-pred.tif b/tests/fixtures/codecs/tiff/deflate16-pred.tif
new file mode 100644
index 00000000..03855b81
Binary files /dev/null and b/tests/fixtures/codecs/tiff/deflate16-pred.tif differ
diff --git a/tests/fixtures/codecs/tiff/float32-pred3.tif b/tests/fixtures/codecs/tiff/float32-pred3.tif
new file mode 100644
index 00000000..85ab48d6
Binary files /dev/null and b/tests/fixtures/codecs/tiff/float32-pred3.tif differ
diff --git a/tests/fixtures/codecs/tiff/gray-miniswhite.tif b/tests/fixtures/codecs/tiff/gray-miniswhite.tif
new file mode 100644
index 00000000..adb090f9
Binary files /dev/null and b/tests/fixtures/codecs/tiff/gray-miniswhite.tif differ
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-rgb.tif b/tests/fixtures/codecs/tiff/jpeg-rgb.tif
new file mode 100644
index 00000000..36dc1b3a
Binary files /dev/null and b/tests/fixtures/codecs/tiff/jpeg-rgb.tif 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
diff --git a/tests/fixtures/codecs/tiff/jpeg-ycbcr.tif b/tests/fixtures/codecs/tiff/jpeg-ycbcr.tif
new file mode 100644
index 00000000..389a331f
Binary files /dev/null and b/tests/fixtures/codecs/tiff/jpeg-ycbcr.tif differ
diff --git a/tests/fixtures/codecs/tiff/lzw-pred.tif b/tests/fixtures/codecs/tiff/lzw-pred.tif
new file mode 100644
index 00000000..5825b301
Binary files /dev/null and b/tests/fixtures/codecs/tiff/lzw-pred.tif differ
diff --git a/tests/fixtures/codecs/tiff/lzw-tiled.tif b/tests/fixtures/codecs/tiff/lzw-tiled.tif
new file mode 100644
index 00000000..6a00cd59
Binary files /dev/null and b/tests/fixtures/codecs/tiff/lzw-tiled.tif differ
diff --git a/tests/fixtures/codecs/tiff/none-strips.tif b/tests/fixtures/codecs/tiff/none-strips.tif
new file mode 100644
index 00000000..557a5155
Binary files /dev/null and b/tests/fixtures/codecs/tiff/none-strips.tif differ
diff --git a/tests/fixtures/codecs/tiff/packbits.tif b/tests/fixtures/codecs/tiff/packbits.tif
new file mode 100644
index 00000000..ebd9b5eb
Binary files /dev/null and b/tests/fixtures/codecs/tiff/packbits.tif differ
diff --git a/tests/fixtures/codecs/tiff/planar-zip.tif b/tests/fixtures/codecs/tiff/planar-zip.tif
new file mode 100644
index 00000000..15390b00
Binary files /dev/null and b/tests/fixtures/codecs/tiff/planar-zip.tif differ