using System.Diagnostics;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Library;
[TestClass]
public sealed class PerceptualHashTests
{
private const int Scenes = 24;
public TestContext TestContext { get; set; } = null!;
private static ulong Hash(byte[] encoded) => PerceptualHash.Compute(new MemoryStream(encoded)) ?? throw new AssertFailedException("Immagine non decodificata.");
private static ulong Hash(SKBitmap bitmap) => Hash(TestImages.Png(bitmap));
///
/// Calibration of (spec §9.3, §14.1): resized and recompressed
/// variants must be duplicates, cropped variants must not, different scenes must not.
///
[TestMethod]
public void ResizedAndRecompressedAreDuplicatesCroppedAreNot()
{
var variantMax = 0;
var cropMin = 64;
var originals = new List();
for (var seed = 1; seed <= Scenes; seed++)
{
var (width, height) = seed % 3 == 0 ? (900, 1200) : (1200, 900);
using var scene = TestImages.Scene(seed, width, height);
var original = Hash(TestImages.Jpeg(scene, 92));
originals.Add(original);
var variants = new List<(string Name, ulong Hash)>();
foreach (var scale in new[] { 0.5, 0.25, 0.08, 1.5 })
{
using var resized = TestImages.Resize(scene, (int)(width * scale), (int)(height * scale));
variants.Add(($"ridimensionata {scale:P0}", Hash(TestImages.Jpeg(resized, 90))));
}
foreach (var quality in new[] { 95, 70, 40, 20 })
{
variants.Add(($"ricompressa q{quality}", Hash(TestImages.Jpeg(scene, quality))));
}
using (var small = TestImages.Resize(scene, width / 3, height / 3))
{
// Resized, then recompressed twice: what a re-shared photo looks like.
var twice = TestImages.Jpeg(TestImages.Decode(TestImages.Jpeg(small, 60)), 45);
variants.Add(("ridimensionata e ricompressa", Hash(twice)));
}
variants.Add(("PNG", Hash(TestImages.Png(scene))));
foreach (var (name, hash) in variants)
{
var distance = PerceptualHash.Distance(original, hash);
variantMax = Math.Max(variantMax, distance);
Assert.IsLessThanOrEqualTo(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, {name}: distanza {distance}");
}
var side = Math.Min(width, height);
var crops = new (string Name, SKRectI Area)[]
{
("centrale 80%", SKRectI.Create(width / 10, height / 10, width * 8 / 10, height * 8 / 10)),
("centrale 75%", SKRectI.Create(width / 8, height / 8, width * 3 / 4, height * 3 / 4)),
("centrale 60%", SKRectI.Create(width / 5, height / 5, width * 3 / 5, height * 3 / 5)),
("lato sinistro tolto 10%", SKRectI.Create(width / 10, 0, width * 9 / 10, height)),
("lato sinistro tolto 25%", SKRectI.Create(width / 4, 0, width * 3 / 4, height)),
("in alto tolto 33%", SKRectI.Create(0, height / 3, width, height * 2 / 3)),
("quadrato", SKRectI.Create((width - side) / 2, (height - side) / 2, side, side)),
("quarto in basso a destra", SKRectI.Create(width / 2, height / 2, width / 2, height / 2)),
};
foreach (var (name, area) in crops)
{
using var cropped = TestImages.Crop(scene, area);
var distance = PerceptualHash.Distance(original, Hash(TestImages.Jpeg(cropped, 90)));
cropMin = Math.Min(cropMin, distance);
Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, ritaglio {name}: distanza {distance}");
}
}
var distinctMin = 64;
for (var i = 0; i < originals.Count; i++)
{
for (var j = i + 1; j < originals.Count; j++)
{
distinctMin = Math.Min(distinctMin, PerceptualHash.Distance(originals[i], originals[j]));
}
}
TestContext.WriteLine($"Taratura: varianti fino a {variantMax}, ritagli da {cropMin}, scene diverse da {distinctMin}; soglia {PerceptualHash.DuplicateThreshold}.");
Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distinctMin);
}
[TestMethod]
public void OrientationIsAppliedBeforeHashing()
{
using var scene = TestImages.Scene(7, 1200, 900);
var upright = Hash(TestImages.Jpeg(scene, 92));
// A camera stores the pixels sideways and tags orientation 6 («rotate 90° clockwise to display»).
using var stored = TestImages.RotateCounterClockwise(scene);
var tagged = TestImages.WithExifOrientation(TestImages.Jpeg(stored, 92), 6);
var untagged = TestImages.Jpeg(stored, 92);
Assert.IsLessThanOrEqualTo(PerceptualHash.DuplicateThreshold, PerceptualHash.Distance(upright, Hash(tagged)));
Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, PerceptualHash.Distance(upright, Hash(untagged)));
}
[TestMethod]
public void NonImagesHaveNoHash()
{
Assert.IsNull(PerceptualHash.Compute(new MemoryStream([1, 2, 3, 4, 5])));
Assert.IsNull(PerceptualHash.Compute(new MemoryStream([])));
}
[TestMethod]
public void HashIsStableAcrossRuns()
{
using var scene = TestImages.Scene(3);
var jpeg = TestImages.Jpeg(scene);
Assert.AreEqual(Hash(jpeg), Hash(jpeg));
Assert.AreEqual(0, PerceptualHash.Distance(5, 5));
Assert.AreEqual(64, PerceptualHash.Distance(0, ulong.MaxValue));
}
[TestMethod]
public void TheIndexComparesOnePhotoWith200000InMilliseconds()
{
var random = new Random(42);
var index = new PerceptualHashIndex();
var records = new List(200_000);
for (var i = 1; i <= 200_000; i++)
{
records.Add(new PerceptualHashRecord(i, i % 40, (ulong)random.NextInt64() ^ ((ulong)random.Next() << 63)));
}
index.Load(records);
Assert.AreEqual(200_000, index.Count);
var target = records[123_456].Hash;
var near = target ^ 0b1011UL; // 3 bits away
index.FindSimilar(near); // warm-up
var best = TimeSpan.MaxValue;
IReadOnlyList matches = [];
for (var run = 0; run < 5; run++)
{
var watch = Stopwatch.StartNew();
matches = index.FindSimilar(near);
watch.Stop();
best = watch.Elapsed < best ? watch.Elapsed : best;
}
TestContext.WriteLine($"Confronto con 200.000 impronte: {best.TotalMilliseconds:F2} ms");
Assert.IsLessThan(20.0, best.TotalMilliseconds);
Assert.AreEqual(records[123_456].MediaId, matches[0].MediaId);
Assert.AreEqual(3, matches[0].Distance);
}
[TestMethod]
public void TheIndexPrefersTheTargetAccountAndForgetsRemovedFiles()
{
var index = new PerceptualHashIndex();
index.Add(1, accountId: 10, hash: 0b0000);
index.Add(2, accountId: 20, hash: 0b0001);
index.Add(3, accountId: 20, hash: 0b0111);
index.Add(4, accountId: 30, hash: ulong.MaxValue);
var plain = index.FindSimilar(0, maxDistance: 3);
Assert.IsTrue(plain.Select(m => m.MediaId).SequenceEqual([1L, 2L, 3L]));
var preferred = index.FindSimilar(0, maxDistance: 3, preferAccountId: 20);
Assert.IsTrue(preferred.Select(m => m.MediaId).SequenceEqual([2L, 3L, 1L]));
Assert.IsTrue(index.Remove(2));
Assert.IsFalse(index.Remove(2));
Assert.IsTrue(index.FindSimilar(0, maxDistance: 3, excludeMediaId: 1).Select(m => m.MediaId).SequenceEqual([3L]));
index.Add(3, accountId: 20, hash: ulong.MaxValue); // replaced
Assert.AreEqual(3, index.Count);
Assert.IsTrue(index.FindSimilar(0, maxDistance: 3).Select(m => m.MediaId).SequenceEqual([1L]));
}
}