using System.Text.Json;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Metadata;
using Titano.Testing;
namespace Titano.Core.Tests.Decoding;
/// Real camera files from tests/fixtures/manifest.json (fetched by Titano.Tools fixtures); each test is
/// skipped when its file is absent. A native decode must reach the expected size and look like the camera's own
/// embedded preview (luminance correlation), which catches wrong byte orders, CFA phases or colour matrices.
public sealed class ExternalFixtureTests(TestContext context)
{
private const int Edge = 256;
private static JsonElement Entry(string name)
{
var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(TestContext.FixturesDirectory, "manifest.json")));
foreach (var f in manifest.RootElement.GetProperty("files").EnumerateArray())
{
if (f.GetProperty("name").GetString() == name) return f.Clone();
}
throw new InvalidOperationException("No manifest entry " + name);
}
[Theory]
[Case("google-pixel-4a.dng")]
[Case("canon-eos-5d-mark-iii.cr2")]
[Case("nikon-d850.nef")]
[Case("sony-ilce-7m3.arw")]
[Case("fujifilm-x-t2.raf")]
[Case("pentax-k-1.pef")]
[Timeout(20_000)]
public void DecodesNativelyAndMatchesThePreview(string name)
{
var path = Path.Combine(TestContext.FixturesDirectory, "external", name);
if (!File.Exists(path)) TestContext.Skip($"{name} not fetched (run Titano.Tools fixtures)");
var entry = Entry(name);
var metadata = MetadataReader.Read(path);
Assert.Equal(entry.GetProperty("format").GetString(), metadata.Format.ToString());
var probe = new ManagedDecoderProvider().Probe(path);
context.Log($"{name}: {probe}; {metadata.Make} {metadata.Model}, {metadata.Width}x{metadata.Height}, orientation {metadata.Orientation}");
Assert.Equal(DecodeTier.Native, probe.Tier);
var decoder = DecoderFactory.CreateServer();
using var native = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false));
Assert.Equal(DecodeTier.Native, native!.Tier);
var (w, h) = (entry.GetProperty("width").GetInt32(), entry.GetProperty("height").GetInt32());
Assert.InRange(native.SourceWidth, w * 0.98, w * 1.02);
Assert.InRange(native.SourceHeight, h * 0.98, h * 1.02);
foreach (var v in native.Pixels.Data)
{
if (!float.IsFinite(v)) Assert.Fail("non-finite pixel");
}
using var preview = decoder.Decode(new DecodeRequest(path, Edge, DecodePurpose.Render, ApplyOrientation: false, ForcePreview: true));
if (preview is null || preview.Tier != DecodeTier.EmbeddedPreview) TestContext.Skip("no embedded preview to compare with");
var correlation = Correlation(native.Pixels, preview.Pixels);
context.Log($"luminance correlation with the embedded preview: {correlation:F3}");
Assert.Greater(correlation, 0.8);
}
/// Pearson correlation of sRGB-encoded luminance after resizing both to a common 64-pixel-wide grid.
private static double Correlation(ImageBuffer a, ImageBuffer b)
{
var height = int.Max(1, (int)double.Round(64.0 * a.Height / a.Width));
using var ra = Resampler.Resize(a, 64, height, ResampleFilter.Box);
using var rb = Resampler.Resize(b, 64, height, ResampleFilter.Box);
var n = ra.PlaneLength;
double sa = 0, sb = 0, saa = 0, sbb = 0, sab = 0;
for (var i = 0; i < n; i++)
{
double la = ColorSpace.EncodeFast(ColorSpace.Luminance(ra.Plane(0)[i], ra.Plane(1)[i], ra.Plane(2)[i]));
double lb = ColorSpace.EncodeFast(ColorSpace.Luminance(rb.Plane(0)[i], rb.Plane(1)[i], rb.Plane(2)[i]));
sa += la;
sb += lb;
saa += la * la;
sbb += lb * lb;
sab += la * lb;
}
var cov = sab / n - sa / n * (sb / n);
return cov / double.Sqrt(double.Max(saa / n - sa / n * (sa / n), 1e-12) * double.Max(sbb / n - sb / n * (sb / n), 1e-12));
}
}