Files
Chronos/tests/Titano.Core.Tests/Raw/SyntheticRaw.cs
T
Claude 1b3a691f76 feat(raw): DNG development pipeline with AHD demosaic, opcodes and DNG colour
Reads CFA and LinearRaw DNGs (compression 1/7/8/34892), linearises with
LinearizationTable, BlackLevel (repeat + deltas) and WhiteLevel over the
ActiveArea, applies OpcodeList1-3 (GainMap, WarpRectilinear,
FixVignetteRadial, FixBadPixels*, TrimBounds, MapTable/MapPolynomial,
Delta/ScalePer*), solves white balance per DNG 1.6 chapter 6 (CCT
interpolation, ForwardMatrix, Bradford to D65), demosaics with AHD
(Hirakawa & Parks 2005), bilinear, a neighbourhood interpolation for
non-Bayer CFAs or binning, and reconstructs clipped highlights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 10:56:34 +00:00

455 lines
21 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Codecs.Dng;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Codecs.Raw;
using Titano.Core.Codecs.Tiff;
using Titano.Core.Imaging;
using Titano.Core.Mathematics;
using Titano.Core.Metadata.Tiff;
namespace Titano.Core.Tests.Raw;
/// <summary>Synthetic scenes and the camera model used to turn them into raw data with known answers.</summary>
internal static class SyntheticRaw
{
/// <summary>Canon EOS 5D Mark III ColorMatrix (XYZ → camera, D65), the adobe_coeff values divided by 10 000.</summary>
public static Matrix3 CameraMatrix { get; } = new(0.6722, -0.0635, -0.0963, -0.4287, 1.2460, 0.2028, -0.0908, 0.2162, 0.5668);
/// <summary>A second (tungsten) matrix for interpolation tests: the D65 one with a warmer bias.</summary>
public static Matrix3 TungstenMatrix { get; } = new(0.7300, -0.1100, -0.0800, -0.4000, 1.2000, 0.2400, -0.0500, 0.1500, 0.7400);
/// <summary>Smooth colourful linear Rec.709 scene with values in roughly 0.03–0.7.</summary>
public static ImageBuffer Smooth(int width, int height)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
double u = x / (double)width, v = y / (double)height;
image[0, x, y] = (float)(0.25 + 0.2 * double.Sin(2 * double.Pi * (u * 1.3 + 0.1)) * double.Cos(2 * double.Pi * v * 0.7));
image[1, x, y] = (float)(0.3 + 0.2 * double.Cos(2 * double.Pi * (u * 0.8 - v * 0.9)));
image[2, x, y] = (float)(0.2 + 0.15 * double.Sin(2 * double.Pi * (v * 1.1 + u * 0.4 + 0.3)));
}
}
return image;
}
/// <summary>Gray scene with a sharp vertical edge (dark left, bright right) and a sharp horizontal one.</summary>
public static ImageBuffer Edges(int width, int height)
{
var image = new ImageBuffer(width, height);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var v = (x >= width / 2 ? 0.6f : 0.08f) * (y >= height / 2 ? 0.5f : 1f);
for (var c = 0; c < 3; c++) image[c, x, y] = v;
}
}
return image;
}
/// <summary>Camera response of a scene lit by <paramref name="white"/>: Bradford(D65 → white) · Rec.709 → XYZ, then
/// XYZ → camera, scaled so the white's camera neutral peaks at 1. Returns per-pixel camera RGB and that neutral.</summary>
public static (float[][] Camera, Vector3D Neutral) ToCamera(ImageBuffer scene, Matrix3 xyzToCamera, Chromaticity white)
{
var whiteXyz = white.ToXyz();
var neutral = xyzToCamera * whiteXyz;
var s = double.Max(neutral.X, double.Max(neutral.Y, neutral.Z));
var m = xyzToCamera * Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), whiteXyz) * Matrix3.Rec709ToXyz;
var camera = new float[3][];
for (var c = 0; c < 3; c++) camera[c] = new float[scene.PlaneLength];
for (var i = 0; i < scene.PlaneLength; i++)
{
var v = m * new Vector3D(scene.Plane(0)[i], scene.Plane(1)[i], scene.Plane(2)[i]);
camera[0][i] = (float)(v.X / s);
camera[1][i] = (float)(v.Y / s);
camera[2][i] = (float)(v.Z / s);
}
return (camera, new Vector3D(neutral.X / s, neutral.Y / s, neutral.Z / s));
}
/// <summary>PSNR in dB between two RGB buffers on sRGB-encoded values, ignoring <paramref name="border"/> pixels.</summary>
public static double Psnr(ImageBuffer expected, ImageBuffer actual, int border)
{
double sum = 0;
long n = 0;
for (var c = 0; c < 3; c++)
{
for (var y = border; y < expected.Height - border; y++)
{
for (var x = border; x < expected.Width - border; x++)
{
var d = ColorSpace.EncodeFast(expected[c, x, y]) - ColorSpace.EncodeFast(actual[c, x, y]);
sum += d * d;
n++;
}
}
}
return 10 * double.Log10(1 / double.Max(sum / n, 1e-12));
}
/// <summary>Mean CIE76 ΔE between two linear Rec.709 buffers (D65 white), ignoring <paramref name="border"/> pixels.</summary>
public static double MeanDeltaE(ImageBuffer expected, ImageBuffer actual, int border)
{
double sum = 0;
long n = 0;
for (var y = border; y < expected.Height - border; y++)
{
for (var x = border; x < expected.Width - border; x++)
{
var a = Lab(expected, x, y);
var b = Lab(actual, x, y);
sum += double.Sqrt((a.L - b.L) * (a.L - b.L) + (a.A - b.A) * (a.A - b.A) + (a.B - b.B) * (a.B - b.B));
n++;
}
}
return sum / n;
}
private static (double L, double A, double B) Lab(ImageBuffer image, int x, int y)
{
var xyz = Matrix3.Rec709ToXyz * new Vector3D(image[0, x, y], image[1, x, y], image[2, x, y]);
var w = Chromaticity.D65.ToXyz();
static double F(double t) => t > 216.0 / 24389 ? double.Cbrt(t) : (24389.0 / 27 * t + 16) / 116;
double fx = F(xyz.X / w.X), fy = F(xyz.Y / w.Y), fz = F(xyz.Z / w.Z);
return (116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz));
}
}
/// <summary>Description of a synthetic DNG written by <see cref="SyntheticDng"/>.</summary>
internal sealed record DngSpec
{
/// <summary>CFA pattern anchored at the active area; null writes a 3-sample LinearRaw image.</summary>
public CfaPattern? Cfa { get; init; } = CfaPattern.Bayer("RGGB");
/// <summary>Masked border around the scene (active area offset); the crop is relative to the active area.</summary>
public int MarginLeft { get; init; }
public int MarginTop { get; init; }
public int MarginRight { get; init; }
public int MarginBottom { get; init; }
/// <summary>DefaultCrop relative to the active area (null: none).</summary>
public RawRect? Crop { get; init; }
public int White { get; init; } = 16383;
/// <summary>Black pattern (rows × columns) or a single value.</summary>
public int BlackRows { get; init; } = 1;
public int BlackColumns { get; init; } = 1;
public double[] Black { get; init; } = [512];
public double[]? BlackDeltaH { get; init; }
public double[]? BlackDeltaV { get; init; }
/// <summary>Forward linearisation table (stored code → linear value).</summary>
public ushort[]? Linearization { get; init; }
/// <summary>1 (uncompressed), 7 (lossless JPEG) or 8 (Deflate with horizontal predictor).</summary>
public int Compression { get; init; } = 7;
/// <summary>Lossless JPEG tiles encode CFA rows as two interleaved components at half width (as the DNG SDK does).</summary>
public bool TwoComponentTiles { get; init; } = true;
public int TileSize { get; init; } = 64;
public Matrix3 ColorMatrix1 { get; init; } = SyntheticRaw.CameraMatrix;
/// <summary>XYZ → camera used to synthesise the raw values (default: <see cref="ColorMatrix1"/>).</summary>
public Matrix3? CaptureMatrix { get; init; }
public int Illuminant1 { get; init; } = 21;
public Matrix3? ColorMatrix2 { get; init; }
public int Illuminant2 { get; init; }
public Matrix3? ForwardMatrix1 { get; init; }
/// <summary>Scene illuminant; the file records it as AsShotNeutral or, with <see cref="WriteWhiteXy"/>, AsShotWhiteXY.</summary>
public Chromaticity SceneWhite { get; init; } = Chromaticity.D65;
public bool WriteWhiteXy { get; init; }
public double BaselineExposure { get; init; }
public byte[]? OpcodeList1 { get; init; }
public byte[]? OpcodeList2 { get; init; }
public byte[]? OpcodeList3 { get; init; }
public ushort Orientation { get; init; } = 1;
/// <summary>Put the raw image in a SubIFD behind an IFD0 thumbnail, like camera DNGs.</summary>
public bool RawInSubIfd { get; init; }
/// <summary>Raw-value transform applied after mosaicking (e.g. the inverse of a gain map), stored-unit domain.</summary>
public Func<int, int, float, float>? RawTransform { get; init; }
}
/// <summary>Writes synthetic DNGs from a linear scene with a known camera model (test-side writer).</summary>
internal static class SyntheticDng
{
public static byte[] Write(ImageBuffer scene, DngSpec spec)
{
var (camera, neutral) = SyntheticRaw.ToCamera(scene, spec.CaptureMatrix ?? spec.ColorMatrix1, spec.SceneWhite);
int sw = scene.Width, sh = scene.Height;
int w = sw + spec.MarginLeft + spec.MarginRight, h = sh + spec.MarginTop + spec.MarginBottom;
var spp = spec.Cfa is null ? 3 : 1;
var samples = new ushort[w * h * spp];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
int ax = x - spec.MarginLeft, ay = y - spec.MarginTop;
var inside = ax >= 0 && ay >= 0 && ax < sw && ay < sh;
for (var s = 0; s < spp; s++)
{
var black = BlackAt(spec, ax, ay, s, spp);
double linear = black;
if (inside)
{
var c = spec.Cfa?.ColorAt(ax, ay) ?? s;
var raw = camera[c][ay * sw + ax];
if (spec.RawTransform is { } t) raw = t(ax, ay, raw);
linear = black + raw * (spec.White - black);
}
linear = double.Clamp(linear, 0, spec.White);
samples[(y * w + x) * spp + s] = spec.Linearization is { } table ? Inverse(table, linear) : (ushort)double.Round(linear);
}
}
}
return Assemble(spec, samples, w, h, spp, neutral);
}
/// <summary>Black level of the spec at active-area coordinates (outside the area: the pattern without deltas).</summary>
public static double BlackAt(DngSpec spec, int ax, int ay, int s, int spp)
{
var row = ((ay % spec.BlackRows) + spec.BlackRows) % spec.BlackRows;
var col = ((ax % spec.BlackColumns) + spec.BlackColumns) % spec.BlackColumns;
var b = spec.Black.Length == 1 ? spec.Black[0] : spec.Black[(row * spec.BlackColumns + col) * spp + s];
if (spec.BlackDeltaH is { } dh && ax >= 0 && ax < dh.Length) b += dh[ax];
if (spec.BlackDeltaV is { } dv && ay >= 0 && ay < dv.Length) b += dv[ay];
return b;
}
private static ushort Inverse(ushort[] table, double value)
{
var best = 0;
for (var i = 1; i < table.Length; i++)
{
if (double.Abs(table[i] - value) < double.Abs(table[best] - value)) best = i;
}
return (ushort)best;
}
private static byte[] Assemble(DngSpec spec, ushort[] samples, int w, int h, int spp, Vector3D neutral)
{
using var output = new MemoryStream();
output.Write("II*\0\0\0\0\0"u8);
var raw = new TiffDirectory();
raw.Long(TiffTags.NewSubfileType, 0);
raw.Long(TiffTags.ImageWidth, (uint)w);
raw.Long(TiffTags.ImageLength, (uint)h);
raw.Short(TiffTags.BitsPerSample, [.. Enumerable.Repeat((ushort)16, spp)]);
raw.Short(TiffTags.Compression, (ushort)spec.Compression);
raw.Short(TiffTags.PhotometricInterpretation, (ushort)(spec.Cfa is null ? 34892 : 32803));
raw.Short(TiffTags.SamplesPerPixel, (ushort)spp);
raw.Short(TiffTags.PlanarConfiguration, 1);
if (spec.Compression == 8) raw.Short(TiffTags.Predictor, 2);
WriteData(spec, raw, output, samples, w, h, spp);
if (spec.Cfa is { } cfa)
{
raw.Short(TiffTags.CfaRepeatPatternDim, (ushort)cfa.Height, (ushort)cfa.Width);
var pattern = new byte[cfa.Width * cfa.Height];
for (var i = 0; i < pattern.Length; i++) pattern[i] = (byte)cfa.ColorAt(i % cfa.Width, i / cfa.Width);
raw.Bytes(TiffTags.CfaPattern, pattern);
raw.Bytes(TiffTags.CfaPlaneColor, 0, 1, 2);
raw.Short(TiffTags.CfaLayout, 1);
}
if (spec.MarginLeft + spec.MarginTop + spec.MarginRight + spec.MarginBottom > 0)
raw.Long(TiffTags.ActiveArea, (uint)spec.MarginTop, (uint)spec.MarginLeft, (uint)(h - spec.MarginBottom), (uint)(w - spec.MarginRight));
if (spec.Crop is { } crop)
{
raw.Long(TiffTags.DefaultCropOrigin, (uint)crop.Left, (uint)crop.Top);
raw.Long(TiffTags.DefaultCropSize, (uint)crop.Width, (uint)crop.Height);
}
if (spec.Linearization is { } table) raw.Short(TiffTags.LinearizationTable, table);
if (spec.BlackRows * spec.BlackColumns > 1) raw.Short(TiffTags.BlackLevelRepeatDim, (ushort)spec.BlackRows, (ushort)spec.BlackColumns);
raw.Rational(TiffTags.BlackLevel, [.. spec.Black.Select(b => ((uint)double.Round(b * 100), 100u))]);
if (spec.BlackDeltaH is { } dh) raw.SRational(TiffTags.BlackLevelDeltaH, [.. dh.Select(d => ((int)double.Round(d * 100), 100))]);
if (spec.BlackDeltaV is { } dv) raw.SRational(TiffTags.BlackLevelDeltaV, [.. dv.Select(d => ((int)double.Round(d * 100), 100))]);
raw.Long(TiffTags.WhiteLevel, [.. Enumerable.Repeat((uint)spec.White, spp)]);
if (spec.OpcodeList1 is { } o1) raw.Add(TiffTags.OpcodeList1, TiffType.Undefined, o1.Length, o1);
if (spec.OpcodeList2 is { } o2) raw.Add(TiffTags.OpcodeList2, TiffType.Undefined, o2.Length, o2);
if (spec.OpcodeList3 is { } o3) raw.Add(TiffTags.OpcodeList3, TiffType.Undefined, o3.Length, o3);
var ifd0 = raw;
if (spec.RawInSubIfd)
{
ifd0 = new TiffDirectory();
ifd0.Long(TiffTags.NewSubfileType, 1);
ifd0.Long(TiffTags.ImageWidth, 4);
ifd0.Long(TiffTags.ImageLength, 4);
ifd0.Short(TiffTags.BitsPerSample, 8, 8, 8);
ifd0.Short(TiffTags.Compression, 1);
ifd0.Short(TiffTags.PhotometricInterpretation, 2);
ifd0.Short(TiffTags.SamplesPerPixel, 3);
ifd0.Long(TiffTags.StripOffsets, 8);
ifd0.Long(TiffTags.StripByteCounts, 48);
ifd0.Child(TiffTags.SubIfds, raw);
}
ifd0.Ascii(TiffTags.Make, "Titano");
ifd0.Ascii(TiffTags.Model, "Synthetic");
ifd0.Short(TiffTags.Orientation, spec.Orientation);
ifd0.Bytes(TiffTags.DngVersion, 1, 6, 0, 0);
ifd0.Bytes(TiffTags.DngBackwardVersion, 1, 1, 0, 0);
ifd0.Ascii(TiffTags.UniqueCameraModel, "Titano Synthetic");
ifd0.SRational(TiffTags.ColorMatrix1, Rationals(spec.ColorMatrix1));
ifd0.Short(TiffTags.CalibrationIlluminant1, (ushort)spec.Illuminant1);
if (spec.ColorMatrix2 is { } cm2)
{
ifd0.SRational(TiffTags.ColorMatrix2, Rationals(cm2));
ifd0.Short(TiffTags.CalibrationIlluminant2, (ushort)spec.Illuminant2);
}
if (spec.ForwardMatrix1 is { } fm) ifd0.SRational(TiffTags.ForwardMatrix1, Rationals(fm));
if (spec.WriteWhiteXy)
{
ifd0.Rational(TiffTags.AsShotWhiteXy, ((uint)double.Round(spec.SceneWhite.X * 1e6), 1_000_000u), ((uint)double.Round(spec.SceneWhite.Y * 1e6), 1_000_000u));
}
else
{
ifd0.Rational(TiffTags.AsShotNeutral, R(neutral.X), R(neutral.Y), R(neutral.Z));
}
ifd0.SRational(TiffTags.BaselineExposure, ((int)double.Round(spec.BaselineExposure * 1000), 1000));
TiffWriter.WriteDirectory(output, 0, ifd0);
return output.ToArray();
}
private static (uint, uint) R(double v) => ((uint)double.Round(v * 1_000_000), 1_000_000u);
private static (int, int)[] Rationals(Matrix3 m) =>
[.. new[] { m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33 }.Select(v => ((int)double.Round(v * 1_000_000), 1_000_000))];
private static void WriteData(DngSpec spec, TiffDirectory raw, Stream output, ushort[] samples, int w, int h, int spp)
{
if (spec.Compression == 7)
{
var t = spec.TileSize;
int across = (w + t - 1) / t, down = (h + t - 1) / t;
var offsets = new uint[across * down];
var counts = new uint[across * down];
for (var ty = 0; ty < down; ty++)
{
for (var tx = 0; tx < across; tx++)
{
var tile = new ushort[t * t * spp];
for (var y = 0; y < t; y++)
{
for (var x = 0; x < t; x++)
{
int sx = int.Min(tx * t + x, w - 1), sy = int.Min(ty * t + y, h - 1);
for (var s = 0; s < spp; s++) tile[(y * t + x) * spp + s] = samples[(sy * w + sx) * spp + s];
}
}
var twoComponents = spec.TwoComponentTiles && spp == 1;
var jpeg = twoComponents ? JpegLosslessEncoder.Encode(tile, t / 2, t, 2, 16) : JpegLosslessEncoder.Encode(tile, t, t, spp, 16);
offsets[ty * across + tx] = (uint)output.Position;
counts[ty * across + tx] = (uint)jpeg.Length;
output.Write(jpeg);
if (output.Position % 2 != 0) output.WriteByte(0);
}
}
raw.Long(TiffTags.TileWidth, (uint)t);
raw.Long(TiffTags.TileLength, (uint)t);
raw.Long(TiffTags.TileOffsets, offsets);
raw.Long(TiffTags.TileByteCounts, counts);
return;
}
var bytes = new byte[samples.Length * 2];
if (spec.Compression == 8)
{
// Horizontal differencing per row (Predictor 2), then zlib.
var rowSamples = w * spp;
var diff = new ushort[samples.Length];
for (var y = 0; y < h; y++)
{
for (var i = 0; i < rowSamples; i++)
{
var k = y * rowSamples + i;
diff[k] = i < spp ? samples[k] : (ushort)(samples[k] - samples[k - spp]);
}
}
for (var i = 0; i < diff.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), diff[i]);
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) z.Write(bytes);
bytes = ms.ToArray();
}
else
{
for (var i = 0; i < samples.Length; i++) BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2 * i), samples[i]);
}
raw.Long(TiffTags.StripOffsets, (uint)output.Position);
raw.Long(TiffTags.StripByteCounts, (uint)bytes.Length);
raw.Long(TiffTags.RowsPerStrip, (uint)h);
output.Write(bytes);
}
}
/// <summary>Big-endian opcode list builder for tests (DNG 1.6 chapter 7 layout).</summary>
internal sealed class OpcodeListBuilder
{
private readonly List<byte[]> _ops = [];
public OpcodeListBuilder Add(uint id, uint flags, Action<BigEndian> parameters)
{
var p = new BigEndian();
parameters(p);
var body = p.ToArray();
var head = new BigEndian().U32(id).U32(0x01030000).U32(flags).U32((uint)body.Length).ToArray();
_ops.Add([.. head, .. body]);
return this;
}
public byte[] Build() => [.. new BigEndian().U32((uint)_ops.Count).ToArray(), .. _ops.SelectMany(o => o)];
/// <summary>Area spec (top, left, bottom, right, plane, planes, row pitch, column pitch).</summary>
public static void Area(BigEndian p, int top, int left, int bottom, int right, int plane = 0, int planes = 1, int rowPitch = 1, int colPitch = 1) =>
p.U32((uint)top).U32((uint)left).U32((uint)bottom).U32((uint)right).U32((uint)plane).U32((uint)planes).U32((uint)rowPitch).U32((uint)colPitch);
internal sealed class BigEndian
{
private readonly MemoryStream _ms = new();
public BigEndian U32(uint v)
{
Span<byte> b = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian U16(ushort v)
{
Span<byte> b = stackalloc byte[2];
BinaryPrimitives.WriteUInt16BigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian F32(float v)
{
Span<byte> b = stackalloc byte[4];
BinaryPrimitives.WriteSingleBigEndian(b, v);
_ms.Write(b);
return this;
}
public BigEndian F64(double v)
{
Span<byte> b = stackalloc byte[8];
BinaryPrimitives.WriteDoubleBigEndian(b, v);
_ms.Write(b);
return this;
}
public byte[] ToArray() => _ms.ToArray();
}
}