using Chronos.Core.Codecs.Raw;
using Chronos.Core.Imaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Raw;
/// Clip-aware highlight reconstruction on decoded DNGs.
public sealed class HighlightTests(TestContext context)
{
private const int W = 96, H = 64;
/// Scene with three gray patches: unclipped (0.4), green clipped only (1.3) and fully clipped (3.0).
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, MaxLongEdge = binning ? 1 : 0 });
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]);
}