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
This commit is contained in:
15 files changed
+3559
No files matched your search
@@ -0,0 +1,224 @@
|
||||
using Titano.Core.Codecs.Dng;
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>Synthetic DNG round trips: a known linear scene is mosaicked through a known camera model, written with the
|
||||
/// DNG feature under test, decoded, and compared with the scene.</summary>
|
||||
public sealed class DngDecoderTests(TestContext context)
|
||||
{
|
||||
private const int W = 96, H = 72;
|
||||
|
||||
private static RawDecodeResult Decode(byte[] dng, RawDecodeOptions? options = null) =>
|
||||
RawDecoder.Decode(new MemoryStream(dng), "test.dng", options);
|
||||
|
||||
[Theory]
|
||||
[Case("RGGB")]
|
||||
[Case("BGGR")]
|
||||
[Case("GRBG")]
|
||||
[Case("GBRG")]
|
||||
public void BayerPatternsRoundTrip(string layout)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = CfaPattern.Bayer(layout) });
|
||||
using var result = Decode(dng);
|
||||
Assert.Equal(W, result.Image.Width);
|
||||
Assert.Equal(H, result.Image.Height);
|
||||
Assert.Equal(layout, result.Info.Layout);
|
||||
var psnr = SyntheticRaw.Psnr(scene, result.Image, 4);
|
||||
var de = SyntheticRaw.MeanDeltaE(scene, result.Image, 4);
|
||||
context.Log($"{layout}: PSNR {psnr:F1} dB, mean ΔE {de:F2}");
|
||||
Assert.GreaterOrEqual(psnr, 40);
|
||||
Assert.Less(de, 1.0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(1, false)]
|
||||
[Case(7, false)]
|
||||
[Case(7, true)]
|
||||
[Case(8, false)]
|
||||
public void CompressionsDecodeIdentically(int compression, bool twoComponents)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var reference = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = 1 }));
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Compression = compression, TwoComponentTiles = twoComponents, RawInSubIfd = true }));
|
||||
Assert.Empty(result.Warnings);
|
||||
Assert.SequenceEqual(reference.Image.Data.ToArray(), result.Image.Data.ToArray());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LinearRawRoundTripsExactly()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null }));
|
||||
Assert.Equal("linear", result.Info.Layout);
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 0), 60);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BlackLevelPatternAndDeltasAreSubtracted()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var deltaH = Enumerable.Range(0, W).Select(x => (double)(x % 7)).ToArray();
|
||||
var deltaV = Enumerable.Range(0, H).Select(y => y * 0.5).ToArray();
|
||||
var spec = new DngSpec { BlackRows = 2, BlackColumns = 2, Black = [500, 520, 530, 510], BlackDeltaH = deltaH, BlackDeltaV = deltaV, MarginLeft = 4, MarginTop = 2 };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LinearizationTableIsApplied()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
// 4096 codes covering 0..16383 with a square law: dense in the shadows, sparse in the highlights.
|
||||
var table = Enumerable.Range(0, 4096).Select(i => (ushort)double.Round(16383.0 * i * i / (4095.0 * 4095.0))).ToArray();
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { Linearization = table, Black = [0] }));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ActiveAreaAndDefaultCropSelectTheImage()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec { MarginLeft = 6, MarginTop = 4, MarginRight = 2, MarginBottom = 3, Crop = new RawRect(8, 6, 8 + 64, 6 + 48) };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.Equal(64, result.Image.Width);
|
||||
Assert.Equal(48, result.Image.Height);
|
||||
Assert.Equal(64, result.Info.Width);
|
||||
using var expected = Crop(scene, 8, 6, 64, 48);
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 40);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(false)]
|
||||
[Case(true)]
|
||||
public void WhiteBalanceFromAsShotNeutralOrWhiteXy(bool whiteXy)
|
||||
{
|
||||
// Scene lit by tungsten (2850 K): decoding must adapt it back to the D65 scene.
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var tungsten = new Chromaticity(0.44757, 0.40745);
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { SceneWhite = tungsten, WriteWhiteXy = whiteXy }));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
Assert.Less(SyntheticRaw.MeanDeltaE(scene, result.Image, 4), 1.5);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DualIlluminantMatricesInterpolateByTemperature()
|
||||
{
|
||||
var profile = new DngColorProfile
|
||||
{
|
||||
ColorMatrix1 = SyntheticRaw.TungstenMatrix,
|
||||
CalibrationIlluminant1 = 17,
|
||||
ColorMatrix2 = SyntheticRaw.CameraMatrix,
|
||||
CalibrationIlluminant2 = 21,
|
||||
};
|
||||
var warm = new Chromaticity(0.44757, 0.40745);
|
||||
var mid = ColorTemperatureXy(4200);
|
||||
Assert.Approximately(2850, DngColorProfile.Temperature(warm), 15);
|
||||
Assert.Approximately(6504, DngColorProfile.Temperature(Chromaticity.D65), 30);
|
||||
AssertMatrix(SyntheticRaw.TungstenMatrix, profile.XyzToCamera(warm), 1e-3);
|
||||
AssertMatrix(SyntheticRaw.CameraMatrix, profile.XyzToCamera(Chromaticity.D65), 1e-9);
|
||||
// Between the calibrations the weight is linear in inverse temperature.
|
||||
var t = DngColorProfile.Temperature(mid);
|
||||
var g = (1 / t - 1 / 6500.0) / (1 / 2850.0 - 1 / 6500.0);
|
||||
Assert.Approximately(g * SyntheticRaw.TungstenMatrix.M11 + (1 - g) * SyntheticRaw.CameraMatrix.M11, profile.XyzToCamera(mid).M11, 1e-9);
|
||||
|
||||
// A DNG with both matrices, shot at 4200 K, decodes back to the scene.
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec
|
||||
{
|
||||
ColorMatrix1 = SyntheticRaw.TungstenMatrix,
|
||||
Illuminant1 = 17,
|
||||
ColorMatrix2 = SyntheticRaw.CameraMatrix,
|
||||
Illuminant2 = 21,
|
||||
CaptureMatrix = profile.XyzToCamera(mid),
|
||||
SceneWhite = mid,
|
||||
};
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForwardMatrixMapsNeutralToWhite()
|
||||
{
|
||||
// ForwardMatrix = Rec.709 → XYZ(D50) with camera = linear Rec.709: a gray scene must stay gray.
|
||||
var fm = Matrix3.BradfordAdaptation(Chromaticity.D65.ToXyz(), Chromaticity.D50.ToXyz()) * Matrix3.Rec709ToXyz;
|
||||
using var scene = new ImageBuffer(32, 32);
|
||||
scene.Data.Fill(0.4f);
|
||||
var spec = new DngSpec { Cfa = null, ColorMatrix1 = Matrix3.XyzToRec709, ForwardMatrix1 = fm };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
for (var c = 0; c < 3; c++) Assert.Approximately(0.4, result.Image[c, 16, 16], 2e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BaselineExposureScalesOutput()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var plain = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null }));
|
||||
using var bright = Decode(SyntheticDng.Write(scene, new DngSpec { Cfa = null, BaselineExposure = 1 }));
|
||||
Assert.Approximately(2 * plain.Image[1, 40, 30], bright.Image[1, 40, 30], 1e-4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case((ushort)6)]
|
||||
[Case((ushort)3)]
|
||||
public void OrientationIsApplied(ushort orientation)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var dng = SyntheticDng.Write(scene, new DngSpec { Cfa = null, Orientation = orientation });
|
||||
using var oriented = Decode(dng);
|
||||
using var stored = Decode(dng, new RawDecodeOptions { ApplyOrientation = false });
|
||||
using var expected = PixelConvert.ApplyOrientation(stored.Image, orientation);
|
||||
Assert.Equal(expected.Width, oriented.Image.Width);
|
||||
Assert.Equal(expected.Width, oriented.Info.Width);
|
||||
Assert.SequenceEqual(expected.Data.ToArray(), oriented.Image.Data.ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(DemosaicQuality.Best)]
|
||||
[Case(DemosaicQuality.Draft)]
|
||||
public void BinningHalvesTheSize(DemosaicQuality quality)
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec()), new RawDecodeOptions { Binning = true, Quality = quality });
|
||||
Assert.Equal(W / 2, result.Image.Width);
|
||||
Assert.Equal(H / 2, result.Image.Height);
|
||||
using var expected = Resampler.Resize(scene, W / 2, H / 2, ResampleFilter.Box);
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 1), 34);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProbeDescribesWithoutDecoding()
|
||||
{
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var dng = SyntheticDng.Write(scene, new DngSpec { Orientation = 6, Crop = new RawRect(2, 2, 66, 50) });
|
||||
var probe = RawDecoder.Probe(new MemoryStream(dng), "x.dng");
|
||||
Assert.True(probe.IsSupported);
|
||||
Assert.Equal(48, probe.Info!.Width);
|
||||
Assert.Equal(64, probe.Info.Height);
|
||||
Assert.Equal("managed-dng", probe.Info.Decoder);
|
||||
Assert.Equal("Synthetic", probe.Info.Model);
|
||||
}
|
||||
|
||||
internal static ImageBuffer Crop(ImageBuffer source, int x0, int y0, int w, int h)
|
||||
{
|
||||
var result = new ImageBuffer(w, h, source.Channels);
|
||||
for (var c = 0; c < source.Channels; c++)
|
||||
{
|
||||
for (var y = 0; y < h; y++) source.Row(c, y0 + y).Slice(x0, w).CopyTo(result.Row(c, y));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Chromaticity ColorTemperatureXy(double kelvin) => Titano.Core.Analysis.ColorTemperature.PlanckianChromaticity(kelvin);
|
||||
|
||||
private static void AssertMatrix(Matrix3 expected, Matrix3 actual, double tolerance)
|
||||
{
|
||||
double[] e = [expected.M11, expected.M12, expected.M13, expected.M21, expected.M22, expected.M23, expected.M31, expected.M32, expected.M33];
|
||||
double[] a = [actual.M11, actual.M12, actual.M13, actual.M21, actual.M22, actual.M23, actual.M31, actual.M32, actual.M33];
|
||||
for (var i = 0; i < 9; i++) Assert.Approximately(e[i], a[i], tolerance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>DNG opcode lists: raw data is distorted by the inverse of an opcode, the decoder must undo it.</summary>
|
||||
public sealed class DngOpcodeTests(TestContext context)
|
||||
{
|
||||
private const int W = 96, H = 72;
|
||||
|
||||
private static RawDecodeResult Decode(byte[] dng) => RawDecoder.Decode(new MemoryStream(dng), "op.dng");
|
||||
|
||||
/// <summary>Bilinear grid interpolation as DNG §7 GainMap defines it (independent of the decoder's implementation).</summary>
|
||||
private static double GainAt(double[,] grid, double spacingV, double spacingH, int x, int y)
|
||||
{
|
||||
int rows = grid.GetLength(0), cols = grid.GetLength(1);
|
||||
double fr = double.Clamp(y / (double)H / spacingV, 0, rows - 1), fc = double.Clamp(x / (double)W / spacingH, 0, cols - 1);
|
||||
int r0 = (int)fr, c0 = (int)fc, r1 = int.Min(r0 + 1, rows - 1), c1 = int.Min(c0 + 1, cols - 1);
|
||||
double a = fr - r0, b = fc - c0;
|
||||
return (grid[r0, c0] * (1 - b) + grid[r0, c1] * b) * (1 - a) + (grid[r1, c0] * (1 - b) + grid[r1, c1] * b) * a;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GainMapRestoresShading()
|
||||
{
|
||||
double[,] grid = { { 1.6, 1.3, 1.6 }, { 1.2, 1.0, 1.25 }, { 1.7, 1.35, 1.5 } };
|
||||
var ops = new OpcodeListBuilder().Add(9, 0, p =>
|
||||
{
|
||||
OpcodeListBuilder.Area(p, 0, 0, H, W);
|
||||
p.U32(3).U32(3).F64(0.5).F64(0.5).F64(0).F64(0).U32(1);
|
||||
for (var r = 0; r < 3; r++)
|
||||
{
|
||||
for (var c = 0; c < 3; c++) p.F32((float)grid[r, c]);
|
||||
}
|
||||
}).Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => (float)(v / GainAt(grid, 0.5, 0.5, x, y)) };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.Empty(result.Warnings);
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GainMapWithPitchTargetsOneCfaColour()
|
||||
{
|
||||
// Red sites of RGGB (even rows and columns) were attenuated by 1/1.5.
|
||||
var ops = new OpcodeListBuilder().Add(9, 0, p =>
|
||||
{
|
||||
OpcodeListBuilder.Area(p, 0, 0, H, W, rowPitch: 2, colPitch: 2);
|
||||
p.U32(1).U32(1).F64(1).F64(1).F64(0).F64(0).U32(1).F32(1.5f);
|
||||
}).Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec { OpcodeList2 = ops, RawTransform = (x, y, v) => x % 2 == 0 && y % 2 == 0 ? v / 1.5f : v };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FixVignetteRadialRestoresFalloff()
|
||||
{
|
||||
double k0 = 0.4, k1 = 0.2;
|
||||
var ops = new OpcodeListBuilder().Add(3, 0, p => p.F64(k0).F64(k1).F64(0).F64(0).F64(0).F64(0.5).F64(0.5)).Build();
|
||||
var m = double.Hypot(W / 2.0, H / 2.0);
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec
|
||||
{
|
||||
OpcodeList2 = ops,
|
||||
RawTransform = (x, y, v) =>
|
||||
{
|
||||
var r2 = ((x - W / 2.0) * (x - W / 2.0) + (y - H / 2.0) * (y - H / 2.0)) / (m * m);
|
||||
return (float)(v / (1 + k0 * r2 + k1 * r2 * r2));
|
||||
},
|
||||
};
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(false)]
|
||||
[Case(true)]
|
||||
public void WarpRectilinearMovesPointsToTheirCorrectedPositions(bool mosaic)
|
||||
{
|
||||
// Corrected position p maps to source position f(p) (radial + tangential model, DNG §7 WarpRectilinear).
|
||||
const int w = 160, h = 120;
|
||||
double[] k = [1.0, 0.06, -0.01, 0.0, 0.002, -0.0015];
|
||||
double cx = 0.48, cy = 0.53;
|
||||
var ops = new OpcodeListBuilder().Add(1, 0, p =>
|
||||
{
|
||||
p.U32(1);
|
||||
foreach (var v in k) p.F64(v);
|
||||
p.F64(cx).F64(cy);
|
||||
}).Build();
|
||||
double ox = cx * w, oy = cy * h;
|
||||
var m = new[] { (0.0, 0.0), (w, 0.0), (0.0, h), (w, h) }.Max(c => double.Hypot(c.Item1 - ox, c.Item2 - oy));
|
||||
(double X, double Y) Source(double x, double y)
|
||||
{
|
||||
double dx = (x - ox) / m, dy = (y - oy) / m, r2 = dx * dx + dy * dy;
|
||||
var f = k[0] + r2 * (k[1] + r2 * (k[2] + r2 * k[3]));
|
||||
return (ox + m * (f * dx + k[4] * 2 * dx * dy + k[5] * (r2 + 2 * dx * dx)), oy + m * (f * dy + k[5] * 2 * dx * dy + k[4] * (r2 + 2 * dy * dy)));
|
||||
}
|
||||
(double X, double Y)[] targets = [(20, 18), (130, 25), (80, 60), (30, 100), (140, 104), (60, 40)];
|
||||
using var distorted = new ImageBuffer(w, h);
|
||||
foreach (var (tx, ty) in targets)
|
||||
{
|
||||
var (sx, sy) = Source(tx, ty);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var g = (float)(0.6 * double.Exp(-((x - sx) * (x - sx) + (y - sy) * (y - sy)) / (2 * 2.0 * 2.0)));
|
||||
for (var c = 0; c < 3; c++) distorted[c, x, y] += g;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < distorted.Data.Length; i++) distorted.Data[i] += 0.02f;
|
||||
var spec = new DngSpec { Cfa = mosaic ? CfaPattern.Bayer("RGGB") : null, OpcodeList3 = ops };
|
||||
using var result = Decode(SyntheticDng.Write(distorted, spec));
|
||||
Assert.Empty(result.Warnings);
|
||||
foreach (var (tx, ty) in targets)
|
||||
{
|
||||
var (x, y) = Centroid(result.Image, (int)tx, (int)ty, 6);
|
||||
context.Log($"target ({tx}, {ty}) → ({x:F3}, {y:F3})");
|
||||
Assert.Within(tx, ty, x, y, mosaic ? 0.2 : 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrimBoundsAndDefaultCropCompose()
|
||||
{
|
||||
var ops = new OpcodeListBuilder().Add(6, 0, p => p.U32(4).U32(10).U32(60).U32(90)).Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops, Crop = new RawRect(0, 0, 80, 64) }));
|
||||
Assert.Equal(70, result.Image.Width);
|
||||
Assert.Equal(56, result.Image.Height);
|
||||
using var expected = DngDecoderTests.Crop(scene, 10, 4, 70, 56);
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(expected, result.Image, 2), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FixBadPixelsConstantAndListRepairMosaic()
|
||||
{
|
||||
(int X, int Y)[] dead = [(10, 10), (41, 20), (70, 33)];
|
||||
(int X, int Y)[] hot = [(30, 50), (55, 12)];
|
||||
var list1 = new OpcodeListBuilder().Add(4, 0, p => p.U32(0).U32(0)).Build();
|
||||
var list2 = new OpcodeListBuilder().Add(5, 0, p =>
|
||||
{
|
||||
p.U32(0).U32((uint)hot.Length).U32(1);
|
||||
foreach (var (x, y) in hot) p.U32((uint)y).U32((uint)x);
|
||||
p.U32(60).U32(80).U32(62).U32(83);
|
||||
}).Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec
|
||||
{
|
||||
OpcodeList1 = list1,
|
||||
OpcodeList2 = list2,
|
||||
RawTransform = (x, y, v) => dead.Contains((x, y)) ? -1f : hot.Contains((x, y)) || (y is >= 60 and < 62 && x is >= 80 and < 83) ? 1f : v,
|
||||
};
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 38);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MapTableAndMapPolynomialInvertEncodings()
|
||||
{
|
||||
// Raw stored as v² is mapped back by a square-root table; then halved values are doubled by a polynomial.
|
||||
var table = Enumerable.Range(0, 65536).Select(i => (ushort)double.Round(double.Sqrt(i / 65535.0) * 65535)).ToArray();
|
||||
var ops = new OpcodeListBuilder()
|
||||
.Add(7, 0, p =>
|
||||
{
|
||||
OpcodeListBuilder.Area(p, 0, 0, H, W);
|
||||
p.U32((uint)table.Length);
|
||||
foreach (var t in table) p.U16(t);
|
||||
})
|
||||
.Add(8, 0, p =>
|
||||
{
|
||||
OpcodeListBuilder.Area(p, 0, 0, H, W);
|
||||
p.U32(1).F64(0).F64(2);
|
||||
})
|
||||
.Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
var spec = new DngSpec { Black = [0], OpcodeList2 = ops, RawTransform = (_, _, v) => float.Max(0, v / 2) * float.Max(0, v / 2) };
|
||||
using var result = Decode(SyntheticDng.Write(scene, spec));
|
||||
var psnr = SyntheticRaw.Psnr(scene, result.Image, 4);
|
||||
context.Log($"MapTable+MapPolynomial PSNR {psnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, 36);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownAndMalformedOpcodesWarnAndContinue()
|
||||
{
|
||||
var ops = new OpcodeListBuilder()
|
||||
.Add(99, 1, p => p.U32(1))
|
||||
.Add(98, 0, p => p.U32(1))
|
||||
.Add(9, 0, p => p.U32(1))
|
||||
.Build();
|
||||
using var scene = SyntheticRaw.Smooth(W, H);
|
||||
using var result = Decode(SyntheticDng.Write(scene, new DngSpec { OpcodeList3 = ops }));
|
||||
Assert.Contains(result.Warnings, w => w.Contains("optional opcode 99"));
|
||||
Assert.Contains(result.Warnings, w => w.Contains("required opcode 98"));
|
||||
Assert.Contains(result.Warnings, w => w.Contains("GainMap") && w.Contains("malformed"));
|
||||
Assert.GreaterOrEqual(SyntheticRaw.Psnr(scene, result.Image, 4), 40);
|
||||
}
|
||||
|
||||
/// <summary>Intensity-weighted centroid above the background in a window around (x, y).</summary>
|
||||
private static (double X, double Y) Centroid(ImageBuffer image, int cx, int cy, int radius)
|
||||
{
|
||||
double sum = 0, sx = 0, sy = 0;
|
||||
for (var y = cy - radius; y <= cy + radius; y++)
|
||||
{
|
||||
for (var x = cx - radius; x <= cx + radius; x++)
|
||||
{
|
||||
var v = double.Max(0, image[1, x, y] - 0.05);
|
||||
sum += v;
|
||||
sx += v * x;
|
||||
sy += v * y;
|
||||
}
|
||||
}
|
||||
return (sx / sum, sy / sum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>Clip-aware highlight reconstruction on decoded DNGs.</summary>
|
||||
public sealed class HighlightTests(TestContext context)
|
||||
{
|
||||
private const int W = 96, H = 64;
|
||||
|
||||
/// <summary>Scene with three gray patches: unclipped (0.4), green clipped only (1.3) and fully clipped (3.0).</summary>
|
||||
private static ImageBuffer Patches()
|
||||
{
|
||||
var scene = new ImageBuffer(W, H);
|
||||
for (var y = 0; y < H; y++)
|
||||
{
|
||||
for (var x = 0; x < W; x++)
|
||||
{
|
||||
var v = x < 32 ? 0.4f : x < 64 ? 1.3f : 3.0f;
|
||||
for (var c = 0; c < 3; c++) scene[c, x, y] = v;
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(DemosaicQuality.Best, false)]
|
||||
[Case(DemosaicQuality.Draft, true)]
|
||||
public void ClippedGrayStaysNeutral(DemosaicQuality quality, bool binning)
|
||||
{
|
||||
using var scene = Patches();
|
||||
var dng = SyntheticDng.Write(scene, new DngSpec());
|
||||
using var result = RawDecoder.Decode(new MemoryStream(dng), "h.dng", new RawDecodeOptions { Quality = quality, Binning = binning });
|
||||
var s = binning ? 2 : 1;
|
||||
var (r0, g0, b0) = Pixel(result.Image, 16 / s, 32 / s);
|
||||
var (r1, g1, b1) = Pixel(result.Image, 48 / s, 32 / s);
|
||||
var (r2, g2, b2) = Pixel(result.Image, 80 / s, 32 / s);
|
||||
context.Log($"0.4 → ({r0:F3}, {g0:F3}, {b0:F3}); 1.3 → ({r1:F3}, {g1:F3}, {b1:F3}); 3.0 → ({r2:F3}, {g2:F3}, {b2:F3})");
|
||||
|
||||
// Unclipped: exact.
|
||||
Assert.Approximately(0.4, g0, 0.01);
|
||||
Assert.Approximately(r0, b0, 0.01);
|
||||
|
||||
// Only green clipped: rebuilt from red and blue, neutral and at its true level (no magenta cast).
|
||||
Assert.Approximately(1.3, g1, 0.03);
|
||||
Assert.Approximately(1.3, r1, 0.03);
|
||||
Assert.Approximately(1.3, b1, 0.03);
|
||||
|
||||
// Everything clipped: neutral, at least as bright as the partially clipped patch.
|
||||
Assert.Approximately(r2, g2, 1e-3);
|
||||
Assert.Approximately(b2, g2, 1e-3);
|
||||
Assert.GreaterOrEqual(g2, g1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaturatedColourKeepsItsHue()
|
||||
{
|
||||
// A red highlight clips the red channel while green and blue stay low: it must stay red, not turn white.
|
||||
using var scene = new ImageBuffer(W, H);
|
||||
for (var i = 0; i < scene.PlaneLength; i++)
|
||||
{
|
||||
scene.Plane(0)[i] = 5f;
|
||||
scene.Plane(1)[i] = 0.15f;
|
||||
scene.Plane(2)[i] = 0.1f;
|
||||
}
|
||||
using var result = RawDecoder.Decode(new MemoryStream(SyntheticDng.Write(scene, new DngSpec())), "red.dng");
|
||||
var (r, g, b) = Pixel(result.Image, W / 2, H / 2);
|
||||
context.Log($"red highlight → ({r:F3}, {g:F3}, {b:F3})");
|
||||
Assert.Greater(r, 4 * g);
|
||||
Assert.Greater(r, 4 * b);
|
||||
}
|
||||
|
||||
private static (float R, float G, float B) Pixel(ImageBuffer image, int x, int y) => (image[0, x, y], image[1, x, y], image[2, x, y]);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Titano.Core.Codecs.Raw;
|
||||
using Titano.Core.Codecs.Tiff;
|
||||
using Titano.Core.Metadata.Tiff;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Raw;
|
||||
|
||||
/// <summary>24-megapixel Bayer DNG development timing: AHD at full size and binned Draft at half size, all cores.</summary>
|
||||
[Serial]
|
||||
[Category("Performance")]
|
||||
public sealed class RawPerformanceTests(TestContext context)
|
||||
{
|
||||
private const int W = 6000, H = 4000;
|
||||
|
||||
[Test]
|
||||
[Timeout(60_000)]
|
||||
public void Develops24MegapixelDngWithinBudget()
|
||||
{
|
||||
// A Debug build disables the JIT optimiser in Titano.Core: timings would measure the build, not the pipeline.
|
||||
if (typeof(RawDecoder).Assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITOptimizerDisabled == true)
|
||||
TestContext.Skip("timing gate needs an optimised build (dotnet run -c Release)");
|
||||
var dng = Mosaic();
|
||||
var ahd = Best(dng, RawDecodeOptions.Default, out var size);
|
||||
Assert.Equal(W, size.Width);
|
||||
var half = Best(dng, new RawDecodeOptions { Quality = DemosaicQuality.Draft, Binning = true }, out var halfSize);
|
||||
Assert.Equal(W / 2, halfSize.Width);
|
||||
context.Log($"24 MP DNG: AHD full size {ahd.TotalMilliseconds:F0} ms, binned half size {half.TotalMilliseconds:F0} ms ({Environment.ProcessorCount} cores)");
|
||||
Console.WriteLine($"[perf] {context.LogText.Trim()}");
|
||||
Assert.Less(ahd.TotalSeconds, 4.0);
|
||||
Assert.Less(half.TotalSeconds, 1.0);
|
||||
}
|
||||
|
||||
/// <summary>Best of two runs (the machine is shared; the first run also pays JIT warm-up).</summary>
|
||||
private static TimeSpan Best(byte[] dng, RawDecodeOptions options, out (int Width, int Height) size)
|
||||
{
|
||||
var best = TimeSpan.MaxValue;
|
||||
size = default;
|
||||
for (var run = 0; run < 2; run++)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
using var result = RawDecoder.Decode(new MemoryStream(dng, writable: false), "perf.dng", options);
|
||||
best = sw.Elapsed < best ? sw.Elapsed : best;
|
||||
size = (result.Image.Width, result.Image.Height);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Uncompressed 14-bit RGGB DNG with photo-like texture (smooth illumination plus detail and noise).</summary>
|
||||
private static byte[] Mosaic()
|
||||
{
|
||||
var data = new byte[W * H * 2];
|
||||
Parallel.For(0, H, y =>
|
||||
{
|
||||
var state = (uint)(y * 2654435761u + 7);
|
||||
for (var x = 0; x < W; x++)
|
||||
{
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
var colour = (y & 1) * 2 + (x & 1);
|
||||
var level = 1500 + 5000 * (0.5 + 0.5 * double.Sin(x * 0.01) * double.Cos(y * 0.013)) * (colour is 1 or 2 ? 1.0 : 0.6)
|
||||
+ 800 * double.Sin(x * 0.4 + y * 0.3) + (state & 127);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan((y * W + x) * 2), (ushort)double.Clamp(level, 0, 16383));
|
||||
}
|
||||
});
|
||||
using var output = new MemoryStream();
|
||||
output.Write("II*\0\0\0\0\0"u8);
|
||||
var ifd = new TiffDirectory();
|
||||
ifd.Long(TiffTags.NewSubfileType, 0);
|
||||
ifd.Long(TiffTags.ImageWidth, W);
|
||||
ifd.Long(TiffTags.ImageLength, H);
|
||||
ifd.Short(TiffTags.BitsPerSample, 16);
|
||||
ifd.Short(TiffTags.Compression, 1);
|
||||
ifd.Short(TiffTags.PhotometricInterpretation, 32803);
|
||||
ifd.Short(TiffTags.SamplesPerPixel, 1);
|
||||
ifd.Long(TiffTags.StripOffsets, 8);
|
||||
ifd.Long(TiffTags.StripByteCounts, (uint)data.Length);
|
||||
ifd.Long(TiffTags.RowsPerStrip, H);
|
||||
ifd.Short(TiffTags.CfaRepeatPatternDim, 2, 2);
|
||||
ifd.Bytes(TiffTags.CfaPattern, 0, 1, 1, 2);
|
||||
ifd.Bytes(TiffTags.DngVersion, 1, 4, 0, 0);
|
||||
ifd.Short(TiffTags.BlackLevel, 1024);
|
||||
ifd.Short(TiffTags.WhiteLevel, 16383);
|
||||
ifd.SRational(TiffTags.ColorMatrix1, (6722, 10000), (-635, 10000), (-963, 10000), (-4287, 10000), (12460, 10000), (2028, 10000), (-908, 10000), (2162, 10000), (5668, 10000));
|
||||
ifd.Short(TiffTags.CalibrationIlluminant1, 21);
|
||||
ifd.Rational(TiffTags.AsShotNeutral, (500u, 1000u), (1000u, 1000u), (700u, 1000u));
|
||||
output.Write(data);
|
||||
TiffWriter.WriteDirectory(output, 0, ifd);
|
||||
return output.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user