using System.Numerics; using Febe.Core.Codecs.Images; namespace Febe.Core.Library; /// /// 64-bit perceptual hash of photos (spec §8.4, «impronta visiva»): the classic DCT pHash. /// /// the image is decoded upright and reduced to 32×32 grey levels by area averaging (aspect ratio is not kept: /// resizing does not change the hash); /// a 2-D DCT-II is computed and the 8×8 lowest frequencies are kept; /// each of the 64 coefficients gives a bit: 1 when above the median of the 64. /// /// Two photos are probable duplicates when the Hamming distance of their hashes is at most /// . Videos have no perceptual hash: for them only SHA-256 counts (spec §9.3). /// public static class PerceptualHash { /// /// Maximum Hamming distance (out of 64 bits) for two photos to be probable duplicates. /// /// Calibrated on 2026-10-13 by Febe.Tests.Library.PerceptualHashTests on 24 generated scenes (gradients, /// shapes, lines and grain; 1200×900 and 900×1200), each compared with its variants: /// /// resized to 50%, 25%, 8% (96 px) and 150%, recompressed as JPEG at quality 95, 70, 40 and 20, resized to a /// third and recompressed twice, saved as PNG: largest distance 4 (only the 96-px reduction; all others ≤ 2); /// cropped — central 80%, 75% and 60% of each side, one side cut by 10% or 25%, top third removed, square and /// 4:5 crops, a corner quarter: smallest distance 8; /// different scenes: smallest distance 20 (average 31). /// /// Every hash has exactly 32 bits set (median split), so distances are always even: 6 sits in the middle of the /// gap between 4 and 8. A very light crop (5% on every side) measured 6–18 and may be proposed as a duplicate: /// the pair is only shown to Alberto, never resolved automatically (rule 12). /// /// public const int DuplicateThreshold = 6; private const int Size = 32; private const int Low = 8; /// A JPEG is decoded reduced, but never below this long side. private const int MinDecodedSide = 256; private static readonly double[,] Cosines = BuildCosines(); /// Hamming distance between two hashes (0–64). public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b); /// True when two hashes are within . public static bool AreSimilar(ulong a, ulong b, int threshold = DuplicateThreshold) => Distance(a, b) <= threshold; /// Hash of an encoded image; null when the content is not a decodable image. public static ulong? Compute(Stream encodedImage) { ArgumentNullException.ThrowIfNull(encodedImage); using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide); return image is null ? null : Compute(image); } /// Hash of an image file; null when it is not a decodable image. public static ulong? ComputeFromFile(string path) { using var stream = File.OpenRead(path); return Compute(stream); } /// /// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had /// (a damaged file may still give its size). /// internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory encodedImage) { using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size); return (image is null ? null : Compute(image), size); } /// Like for a file, read once. internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path) { byte[]? data; using (var stream = File.OpenRead(path)) { data = ImageDecoding.ReadAll(stream); } return data is null ? (null, null) : ComputeWithSize(data); } /// Hash of a decoded image (any size), upright as it is shown. internal static ulong Compute(RgbaImage image) { ArgumentNullException.ThrowIfNull(image); return HashOf(AreaResample(image, Size, Size)); } /// The hash of a 32×32 grey image (row-major). internal static ulong HashOf(double[] pixels) { // Separable DCT-II, only the 8 lowest frequencies in each direction. var rows = new double[Size * Low]; for (var y = 0; y < Size; y++) { for (var u = 0; u < Low; u++) { double sum = 0; for (var x = 0; x < Size; x++) { sum += pixels[(y * Size) + x] * Cosines[u, x]; } rows[(y * Low) + u] = sum; } } var coefficients = new double[Low * Low]; for (var v = 0; v < Low; v++) { for (var u = 0; u < Low; u++) { double sum = 0; for (var y = 0; y < Size; y++) { sum += rows[(y * Low) + u] * Cosines[v, y]; } coefficients[(v * Low) + u] = sum; } } var sorted = (double[])coefficients.Clone(); Array.Sort(sorted); var median = (sorted[31] + sorted[32]) / 2; ulong hash = 0; for (var i = 0; i < coefficients.Length; i++) { if (coefficients[i] > median) { hash |= 1UL << i; } } return hash; } /// /// The grey levels (0–255, over white: ) of an image reduced to dw × dh by area /// averaging, one source row at a time (memory: one row and dw × source height values). /// internal static double[] AreaResample(RgbaImage image, int dw, int dh) { var sw = image.Width; var sh = image.Height; var xs = Weights(sw, dw); var horizontal = new double[dw * sh]; var grey = new double[sw]; for (var y = 0; y < sh; y++) { ImageGray.LumaOverWhite(image.GetRow(y), grey); for (var dx = 0; dx < dw; dx++) { double sum = 0; foreach (var (index, weight) in xs[dx]) { sum += grey[index] * weight; } horizontal[(y * dw) + dx] = sum; } } return Vertical(horizontal, sh, dw, dh); } private static double[] Vertical(double[] horizontal, int sh, int dw, int dh) { var result = new double[dw * dh]; var ys = Weights(sh, dh); for (var dy = 0; dy < dh; dy++) { for (var dx = 0; dx < dw; dx++) { double sum = 0; foreach (var (index, weight) in ys[dy]) { sum += horizontal[(index * dw) + dx] * weight; } result[(dy * dw) + dx] = sum; } } return result; } /// For each target cell, the source cells it covers and their normalized weights. private static List<(int Index, double Weight)>[] Weights(int sourceLength, int targetLength) { var scale = (double)sourceLength / targetLength; var weights = new List<(int, double)>[targetLength]; for (var t = 0; t < targetLength; t++) { var start = t * scale; var end = start + scale; var list = new List<(int, double)>(); if (scale <= 1) { // Enlarging: nearest source cell by centre. list.Add((Math.Min(sourceLength - 1, (int)((t + 0.5) * scale)), 1.0)); } else { for (var s = (int)Math.Floor(start); s < Math.Ceiling(end) && s < sourceLength; s++) { var overlap = Math.Min(end, s + 1) - Math.Max(start, s); if (overlap > 0) { list.Add((s, overlap / scale)); } } } weights[t] = list; } return weights; } private static double[,] BuildCosines() { var table = new double[Low, Size]; for (var u = 0; u < Low; u++) { for (var x = 0; x < Size; x++) { table[u, x] = Math.Cos(((2 * x) + 1) * u * Math.PI / (2 * Size)); } } return table; } }