oximedia-dedup 0.1.5

Media deduplication and duplicate detection for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Content-signature types for robust media identification.
//!
//! Provides `SignatureType`, `ContentSignature`, and `SignatureDatabase`
//! for storing and matching content signatures across a media library.
//!
//! # Robust Signatures
//!
//! The [`RobustSignature`] type combines multiple format-agnostic signals
//! into a single composite fingerprint that survives common transformations:
//!
//! - **Transcoding** (codec/container changes)
//! - **Cropping** (letterboxing, aspect ratio changes)
//! - **Watermarking** (overlaid logos, text)
//! - **Colour grading** (brightness, contrast, saturation shifts)
//! - **Scaling** (resolution changes)
//!
//! This is achieved by fusing perceptual hashes (rotation-invariant DCT
//! domain), radial variance profiles, temporal rhythm signatures, and
//! audio spectral peaks into a single matchable descriptor.

#![allow(dead_code)]
#![allow(clippy::cast_precision_loss)]

use std::collections::HashMap;

/// The type of content signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SignatureType {
    /// Perceptual hash derived from visual content.
    PerceptualVisual,
    /// Perceptual hash derived from audio content.
    PerceptualAudio,
    /// Cryptographic (exact) hash of raw bytes.
    Cryptographic,
    /// Fingerprint generated by a machine-learning model.
    NeuralEmbedding,
    /// Lightweight thumbnail-based signature.
    Thumbnail,
}

impl SignatureType {
    /// Return `true` if this signature type is perceptual (approximate matching).
    #[must_use]
    pub const fn is_perceptual(self) -> bool {
        matches!(
            self,
            Self::PerceptualVisual | Self::PerceptualAudio | Self::NeuralEmbedding
        )
    }

    /// Return `true` if this signature supports exact equality matching.
    #[must_use]
    pub const fn supports_exact_match(self) -> bool {
        matches!(self, Self::Cryptographic)
    }

    /// Return a short label for this type.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::PerceptualVisual => "perceptual-visual",
            Self::PerceptualAudio => "perceptual-audio",
            Self::Cryptographic => "cryptographic",
            Self::NeuralEmbedding => "neural-embedding",
            Self::Thumbnail => "thumbnail",
        }
    }
}

/// A content signature for a single piece of media.
#[derive(Debug, Clone)]
pub struct ContentSignature {
    /// Unique identifier of the media asset.
    pub asset_id: String,
    /// Type of signature.
    pub sig_type: SignatureType,
    /// Raw signature bytes.
    pub data: Vec<u8>,
    /// Optional confidence score (0.0–1.0).
    pub confidence: f64,
}

impl ContentSignature {
    /// Create a new `ContentSignature`.
    #[must_use]
    pub fn new(
        asset_id: impl Into<String>,
        sig_type: SignatureType,
        data: Vec<u8>,
        confidence: f64,
    ) -> Self {
        Self {
            asset_id: asset_id.into(),
            sig_type,
            data,
            confidence,
        }
    }

    /// Return `true` if this signature matches `other` within `tolerance` bytes differing.
    ///
    /// For exact (cryptographic) signatures `tolerance` is ignored and byte-equality is required.
    #[must_use]
    pub fn matches(&self, other: &Self, tolerance: u32) -> bool {
        if self.sig_type != other.sig_type {
            return false;
        }
        if self.data.len() != other.data.len() {
            return false;
        }
        if self.sig_type.supports_exact_match() {
            return self.data == other.data;
        }
        // Perceptual: count differing bytes and compare against tolerance.
        let diff: u32 = self
            .data
            .iter()
            .zip(&other.data)
            .map(|(a, b)| u32::from(*a != *b))
            .sum();
        diff <= tolerance
    }

    /// Return the length of the signature data in bytes.
    #[must_use]
    pub fn data_len(&self) -> usize {
        self.data.len()
    }
}

/// An in-memory database of `ContentSignature` values.
#[derive(Debug, Default)]
pub struct SignatureDatabase {
    entries: HashMap<String, Vec<ContentSignature>>,
}

impl SignatureDatabase {
    /// Create a new, empty database.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Store a signature, appending it to the list for its `asset_id`.
    pub fn store(&mut self, sig: ContentSignature) {
        self.entries
            .entry(sig.asset_id.clone())
            .or_default()
            .push(sig);
    }

    /// Look up all signatures associated with `asset_id`.
    #[must_use]
    pub fn lookup(&self, asset_id: &str) -> &[ContentSignature] {
        self.entries.get(asset_id).map(Vec::as_slice).unwrap_or(&[])
    }

    /// Return the total number of signatures stored across all assets.
    #[must_use]
    pub fn match_count(&self) -> usize {
        self.entries.values().map(Vec::len).sum()
    }

    /// Find all assets whose signatures match `query` within `tolerance`.
    ///
    /// Returns a list of `(asset_id, matching_signature_count)` pairs.
    #[must_use]
    pub fn find_matches(&self, query: &ContentSignature, tolerance: u32) -> Vec<(String, usize)> {
        self.entries
            .iter()
            .filter_map(|(id, sigs)| {
                let count = sigs.iter().filter(|s| query.matches(s, tolerance)).count();
                if count > 0 && id != &query.asset_id {
                    Some((id.clone(), count))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Remove all signatures for `asset_id`, returning the removed list.
    pub fn remove_asset(&mut self, asset_id: &str) -> Vec<ContentSignature> {
        self.entries.remove(asset_id).unwrap_or_default()
    }

    /// Return the number of distinct assets tracked.
    #[must_use]
    pub fn asset_count(&self) -> usize {
        self.entries.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_sig(asset_id: &str, sig_type: SignatureType, data: Vec<u8>) -> ContentSignature {
        ContentSignature::new(asset_id, sig_type, data, 1.0)
    }

    #[test]
    fn test_sig_type_is_perceptual_visual() {
        assert!(SignatureType::PerceptualVisual.is_perceptual());
    }

    #[test]
    fn test_sig_type_is_perceptual_audio() {
        assert!(SignatureType::PerceptualAudio.is_perceptual());
    }

    #[test]
    fn test_sig_type_not_perceptual_crypto() {
        assert!(!SignatureType::Cryptographic.is_perceptual());
    }

    #[test]
    fn test_sig_type_supports_exact_match() {
        assert!(SignatureType::Cryptographic.supports_exact_match());
        assert!(!SignatureType::PerceptualVisual.supports_exact_match());
    }

    #[test]
    fn test_sig_type_label_nonempty() {
        for t in [
            SignatureType::PerceptualVisual,
            SignatureType::PerceptualAudio,
            SignatureType::Cryptographic,
            SignatureType::NeuralEmbedding,
            SignatureType::Thumbnail,
        ] {
            assert!(!t.label().is_empty());
        }
    }

    #[test]
    fn test_signature_exact_match_identical() {
        let s1 = make_sig("a1", SignatureType::Cryptographic, vec![1, 2, 3, 4]);
        let s2 = make_sig("a2", SignatureType::Cryptographic, vec![1, 2, 3, 4]);
        assert!(s1.matches(&s2, 0));
    }

    #[test]
    fn test_signature_exact_match_different() {
        let s1 = make_sig("a1", SignatureType::Cryptographic, vec![1, 2, 3, 4]);
        let s2 = make_sig("a2", SignatureType::Cryptographic, vec![1, 2, 3, 5]);
        assert!(!s1.matches(&s2, 0));
    }

    #[test]
    fn test_signature_perceptual_within_tolerance() {
        let s1 = make_sig("a1", SignatureType::PerceptualVisual, vec![0, 0, 0, 0]);
        let s2 = make_sig("a2", SignatureType::PerceptualVisual, vec![1, 0, 0, 0]);
        assert!(s1.matches(&s2, 1));
    }

    #[test]
    fn test_signature_perceptual_exceeds_tolerance() {
        let s1 = make_sig("a1", SignatureType::PerceptualVisual, vec![0, 0, 0, 0]);
        let s2 = make_sig("a2", SignatureType::PerceptualVisual, vec![1, 1, 0, 0]);
        assert!(!s1.matches(&s2, 1));
    }

    #[test]
    fn test_signature_type_mismatch() {
        let s1 = make_sig("a1", SignatureType::PerceptualVisual, vec![0; 4]);
        let s2 = make_sig("a2", SignatureType::Cryptographic, vec![0; 4]);
        assert!(!s1.matches(&s2, 10));
    }

    #[test]
    fn test_database_store_and_lookup() {
        let mut db = SignatureDatabase::new();
        db.store(make_sig(
            "asset1",
            SignatureType::Cryptographic,
            vec![0xAB; 4],
        ));
        let sigs = db.lookup("asset1");
        assert_eq!(sigs.len(), 1);
    }

    #[test]
    fn test_database_lookup_missing() {
        let db = SignatureDatabase::new();
        assert!(db.lookup("nonexistent").is_empty());
    }

    #[test]
    fn test_database_match_count() {
        let mut db = SignatureDatabase::new();
        db.store(make_sig("a", SignatureType::Cryptographic, vec![1; 4]));
        db.store(make_sig("a", SignatureType::PerceptualVisual, vec![1; 4]));
        db.store(make_sig("b", SignatureType::Cryptographic, vec![1; 4]));
        assert_eq!(db.match_count(), 3);
    }

    #[test]
    fn test_database_find_matches() {
        let mut db = SignatureDatabase::new();
        db.store(make_sig(
            "other",
            SignatureType::PerceptualVisual,
            vec![0, 0, 0, 0],
        ));
        let query = make_sig("query", SignatureType::PerceptualVisual, vec![0, 0, 0, 1]);
        let matches = db.find_matches(&query, 1);
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].0, "other");
    }

    #[test]
    fn test_database_remove_asset() {
        let mut db = SignatureDatabase::new();
        db.store(make_sig("x", SignatureType::Cryptographic, vec![0; 4]));
        assert_eq!(db.asset_count(), 1);
        let removed = db.remove_asset("x");
        assert_eq!(removed.len(), 1);
        assert_eq!(db.asset_count(), 0);
    }
}

// ===========================================================================
// Robust Content Signatures
// ===========================================================================

/// Number of radial zones for the radial variance profile.
const RADIAL_ZONES: usize = 8;

/// Number of temporal bins for the rhythm signature.
const TEMPORAL_BINS: usize = 16;

/// Number of spectral peaks stored in the audio peak constellation.
const SPECTRAL_PEAKS: usize = 32;

// ---------------------------------------------------------------------------
// RadialVariance
// ---------------------------------------------------------------------------

/// Radial variance profile of an image — invariant to translation, robust to
/// cropping and scaling.
///
/// Divides a centred circle into concentric annular zones and computes the
/// variance of luminance within each zone.  Because the measurement is
/// relative to the image centre and averaged over angular position, mild
/// cropping or letterbox changes only affect the outermost zone.
#[derive(Debug, Clone)]
pub struct RadialVarianceProfile {
    /// Variance per zone (inner to outer).
    pub zones: [f64; RADIAL_ZONES],
}

impl RadialVarianceProfile {
    /// Compute from a grayscale image (flat row-major `u8` data).
    #[must_use]
    pub fn compute(width: usize, height: usize, data: &[u8]) -> Self {
        let cx = width as f64 / 2.0;
        let cy = height as f64 / 2.0;
        let max_r = cx.min(cy).max(1.0);

        let mut sums = [0.0f64; RADIAL_ZONES];
        let mut sq_sums = [0.0f64; RADIAL_ZONES];
        let mut counts = [0usize; RADIAL_ZONES];

        for y in 0..height {
            for x in 0..width {
                let dx = x as f64 - cx;
                let dy = y as f64 - cy;
                let r = (dx * dx + dy * dy).sqrt();
                let zone_idx = ((r / max_r) * RADIAL_ZONES as f64) as usize;
                let zone_idx = zone_idx.min(RADIAL_ZONES - 1);

                let idx = y * width + x;
                if idx < data.len() {
                    let val = f64::from(data[idx]);
                    sums[zone_idx] += val;
                    sq_sums[zone_idx] += val * val;
                    counts[zone_idx] += 1;
                }
            }
        }

        let mut zones = [0.0f64; RADIAL_ZONES];
        for i in 0..RADIAL_ZONES {
            if counts[i] > 1 {
                let mean = sums[i] / counts[i] as f64;
                let variance = sq_sums[i] / counts[i] as f64 - mean * mean;
                zones[i] = variance.max(0.0);
            }
        }

        Self { zones }
    }

    /// Cosine similarity to another profile (0.0 - 1.0).
    #[must_use]
    pub fn similarity(&self, other: &Self) -> f64 {
        let dot: f64 = self
            .zones
            .iter()
            .zip(other.zones.iter())
            .map(|(a, b)| a * b)
            .sum();
        let mag_a: f64 = self.zones.iter().map(|x| x * x).sum::<f64>().sqrt();
        let mag_b: f64 = other.zones.iter().map(|x| x * x).sum::<f64>().sqrt();
        if mag_a < f64::EPSILON || mag_b < f64::EPSILON {
            return 0.0;
        }
        (dot / (mag_a * mag_b)).clamp(0.0, 1.0)
    }
}

// ---------------------------------------------------------------------------
// TemporalRhythm
// ---------------------------------------------------------------------------

/// Temporal rhythm signature — captures the temporal structure of visual
/// changes across a video.
///
/// Computed by measuring the average frame-to-frame luminance change over
/// `TEMPORAL_BINS` equal time segments.  This signature is invariant to
/// codec and resolution, and robust to colour grading and watermarking.
#[derive(Debug, Clone)]
pub struct TemporalRhythm {
    /// Normalised change intensity per temporal bin (0.0 - 1.0).
    pub bins: [f64; TEMPORAL_BINS],
}

impl TemporalRhythm {
    /// Construct from a series of per-frame luminance change values.
    ///
    /// `frame_changes` should contain one value per inter-frame transition
    /// (i.e., `num_frames - 1` entries), each representing the mean absolute
    /// pixel difference between consecutive frames.
    #[must_use]
    pub fn from_frame_changes(frame_changes: &[f64]) -> Self {
        let mut bins = [0.0f64; TEMPORAL_BINS];
        if frame_changes.is_empty() {
            return Self { bins };
        }

        let n = frame_changes.len();
        let bin_size = (n as f64 / TEMPORAL_BINS as f64).max(1.0);

        for (i, &val) in frame_changes.iter().enumerate() {
            let bin_idx = (i as f64 / bin_size) as usize;
            let bin_idx = bin_idx.min(TEMPORAL_BINS - 1);
            bins[bin_idx] += val;
        }

        // Count entries per bin for averaging.
        let mut counts = [0usize; TEMPORAL_BINS];
        for i in 0..n {
            let bin_idx = ((i as f64 / bin_size) as usize).min(TEMPORAL_BINS - 1);
            counts[bin_idx] += 1;
        }
        for i in 0..TEMPORAL_BINS {
            if counts[i] > 0 {
                bins[i] /= counts[i] as f64;
            }
        }

        // Normalise to [0, 1].
        let max_val = bins.iter().cloned().fold(0.0f64, f64::max);
        if max_val > f64::EPSILON {
            for b in &mut bins {
                *b /= max_val;
            }
        }

        Self { bins }
    }

    /// Cosine similarity to another rhythm signature.
    #[must_use]
    pub fn similarity(&self, other: &Self) -> f64 {
        let dot: f64 = self
            .bins
            .iter()
            .zip(other.bins.iter())
            .map(|(a, b)| a * b)
            .sum();
        let mag_a: f64 = self.bins.iter().map(|x| x * x).sum::<f64>().sqrt();
        let mag_b: f64 = other.bins.iter().map(|x| x * x).sum::<f64>().sqrt();
        if mag_a < f64::EPSILON || mag_b < f64::EPSILON {
            return 0.0;
        }
        (dot / (mag_a * mag_b)).clamp(0.0, 1.0)
    }
}

// ---------------------------------------------------------------------------
// SpectralPeakConstellation
// ---------------------------------------------------------------------------

/// Audio spectral peak constellation — a set of (time_bin, freq_bin) pairs
/// representing the strongest spectral peaks in the audio.
///
/// This is the core primitive behind audio fingerprinting systems like
/// Shazam.  Because peaks are identified by relative position in the
/// time-frequency plane, the signature is robust to transcoding, volume
/// changes, and mild noise.
#[derive(Debug, Clone)]
pub struct SpectralPeakConstellation {
    /// Sorted list of (time_bin, frequency_bin) peak positions.
    pub peaks: Vec<(u32, u32)>,
}

impl SpectralPeakConstellation {
    /// Create from raw peak positions.
    #[must_use]
    pub fn new(mut peaks: Vec<(u32, u32)>) -> Self {
        peaks.sort();
        if peaks.len() > SPECTRAL_PEAKS {
            peaks.truncate(SPECTRAL_PEAKS);
        }
        Self { peaks }
    }

    /// Jaccard similarity to another constellation (0.0 - 1.0).
    #[must_use]
    pub fn similarity(&self, other: &Self) -> f64 {
        if self.peaks.is_empty() && other.peaks.is_empty() {
            return 1.0;
        }
        if self.peaks.is_empty() || other.peaks.is_empty() {
            return 0.0;
        }

        // Count matching peaks (allowing ±1 tolerance in each dimension).
        let mut matched = 0usize;
        for &(t1, f1) in &self.peaks {
            for &(t2, f2) in &other.peaks {
                let dt = (t1 as i64 - t2 as i64).unsigned_abs();
                let df = (f1 as i64 - f2 as i64).unsigned_abs();
                if dt <= 1 && df <= 1 {
                    matched += 1;
                    break;
                }
            }
        }

        let union = self.peaks.len() + other.peaks.len() - matched;
        if union == 0 {
            return 0.0;
        }
        matched as f64 / union as f64
    }
}

// ---------------------------------------------------------------------------
// RobustSignature
// ---------------------------------------------------------------------------

/// A robust multi-signal content signature that survives transcoding,
/// cropping, watermarking, colour grading, and resolution changes.
///
/// Combines:
/// - **Perceptual hash** (64-bit DCT pHash — invariant to scale/compression)
/// - **Radial variance profile** (robust to cropping/letterboxing)
/// - **Temporal rhythm** (robust to codec/colour grading)
/// - **Spectral peaks** (robust to audio transcoding/noise)
#[derive(Debug, Clone)]
pub struct RobustSignature {
    /// Asset identifier.
    pub asset_id: String,
    /// 64-bit perceptual hash (visual).
    pub phash: Option<u64>,
    /// Radial variance profile (visual).
    pub radial: Option<RadialVarianceProfile>,
    /// Temporal rhythm (video).
    pub temporal: Option<TemporalRhythm>,
    /// Spectral peak constellation (audio).
    pub spectral: Option<SpectralPeakConstellation>,
    /// Duration in seconds.
    pub duration_secs: Option<f64>,
}

impl RobustSignature {
    /// Create a new signature with only an asset ID.
    #[must_use]
    pub fn new(asset_id: impl Into<String>) -> Self {
        Self {
            asset_id: asset_id.into(),
            phash: None,
            radial: None,
            temporal: None,
            spectral: None,
            duration_secs: None,
        }
    }

    /// Builder: set perceptual hash.
    #[must_use]
    pub fn with_phash(mut self, hash: u64) -> Self {
        self.phash = Some(hash);
        self
    }

    /// Builder: set radial variance profile.
    #[must_use]
    pub fn with_radial(mut self, profile: RadialVarianceProfile) -> Self {
        self.radial = Some(profile);
        self
    }

    /// Builder: set temporal rhythm.
    #[must_use]
    pub fn with_temporal(mut self, rhythm: TemporalRhythm) -> Self {
        self.temporal = Some(rhythm);
        self
    }

    /// Builder: set spectral peaks.
    #[must_use]
    pub fn with_spectral(mut self, peaks: SpectralPeakConstellation) -> Self {
        self.spectral = Some(peaks);
        self
    }

    /// Builder: set duration.
    #[must_use]
    pub fn with_duration(mut self, secs: f64) -> Self {
        self.duration_secs = Some(secs);
        self
    }

    /// Number of signal components present.
    #[must_use]
    pub fn signal_count(&self) -> usize {
        let mut count = 0;
        if self.phash.is_some() {
            count += 1;
        }
        if self.radial.is_some() {
            count += 1;
        }
        if self.temporal.is_some() {
            count += 1;
        }
        if self.spectral.is_some() {
            count += 1;
        }
        count
    }

    /// Compute weighted similarity to another robust signature.
    ///
    /// Returns `(overall_score, RobustMatchDetail)`.
    #[must_use]
    pub fn compare(&self, other: &Self) -> RobustMatchResult {
        let mut total_weight = 0.0f64;
        let mut weighted_sum = 0.0f64;

        // Duration pre-check: if both have duration and they differ by more
        // than 2 seconds, early-reject.
        let duration_ok = match (self.duration_secs, other.duration_secs) {
            (Some(a), Some(b)) => (a - b).abs() <= 2.0,
            _ => true,
        };

        if !duration_ok {
            return RobustMatchResult {
                overall_score: 0.0,
                phash_score: None,
                radial_score: None,
                temporal_score: None,
                spectral_score: None,
            };
        }

        // pHash comparison (weight = 0.35)
        let phash_score = match (self.phash, other.phash) {
            (Some(a), Some(b)) => {
                let dist = (a ^ b).count_ones();
                let sim = 1.0 - dist as f64 / 64.0;
                total_weight += 0.35;
                weighted_sum += sim * 0.35;
                Some(sim)
            }
            _ => None,
        };

        // Radial variance (weight = 0.20)
        let radial_score = match (&self.radial, &other.radial) {
            (Some(a), Some(b)) => {
                let sim = a.similarity(b);
                total_weight += 0.20;
                weighted_sum += sim * 0.20;
                Some(sim)
            }
            _ => None,
        };

        // Temporal rhythm (weight = 0.25)
        let temporal_score = match (&self.temporal, &other.temporal) {
            (Some(a), Some(b)) => {
                let sim = a.similarity(b);
                total_weight += 0.25;
                weighted_sum += sim * 0.25;
                Some(sim)
            }
            _ => None,
        };

        // Spectral peaks (weight = 0.20)
        let spectral_score = match (&self.spectral, &other.spectral) {
            (Some(a), Some(b)) => {
                let sim = a.similarity(b);
                total_weight += 0.20;
                weighted_sum += sim * 0.20;
                Some(sim)
            }
            _ => None,
        };

        let overall = if total_weight > f64::EPSILON {
            weighted_sum / total_weight
        } else {
            0.0
        };

        RobustMatchResult {
            overall_score: overall,
            phash_score,
            radial_score,
            temporal_score,
            spectral_score,
        }
    }
}

/// Result of comparing two `RobustSignature` instances.
#[derive(Debug, Clone)]
pub struct RobustMatchResult {
    /// Weighted overall score (0.0 - 1.0).
    pub overall_score: f64,
    /// Per-signal scores.
    pub phash_score: Option<f64>,
    /// Radial variance similarity.
    pub radial_score: Option<f64>,
    /// Temporal rhythm similarity.
    pub temporal_score: Option<f64>,
    /// Spectral peak similarity.
    pub spectral_score: Option<f64>,
}

impl RobustMatchResult {
    /// Returns `true` if the overall score is above `threshold`.
    #[must_use]
    pub fn is_match(&self, threshold: f64) -> bool {
        self.overall_score >= threshold
    }

    /// Number of signals that contributed to the score.
    #[must_use]
    pub fn contributing_signals(&self) -> usize {
        let mut count = 0;
        if self.phash_score.is_some() {
            count += 1;
        }
        if self.radial_score.is_some() {
            count += 1;
        }
        if self.temporal_score.is_some() {
            count += 1;
        }
        if self.spectral_score.is_some() {
            count += 1;
        }
        count
    }
}

// ---------------------------------------------------------------------------
// RobustSignature tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod robust_tests {
    use super::*;

    #[test]
    fn test_radial_variance_uniform_image() {
        // Uniform image: all pixels = 128, variance should be ~0.
        let data = vec![128u8; 64 * 64];
        let profile = RadialVarianceProfile::compute(64, 64, &data);
        for &v in &profile.zones {
            assert!(
                v < 1e-6,
                "uniform image should have near-zero variance: {v}"
            );
        }
    }

    #[test]
    fn test_radial_variance_self_similarity() {
        let data: Vec<u8> = (0..64 * 64).map(|i| (i % 256) as u8).collect();
        let profile = RadialVarianceProfile::compute(64, 64, &data);
        let sim = profile.similarity(&profile);
        assert!((sim - 1.0).abs() < 1e-10, "self-similarity should be 1.0");
    }

    #[test]
    fn test_radial_variance_different_images() {
        let data_a = vec![100u8; 64 * 64];
        let data_b: Vec<u8> = (0..64 * 64).map(|i| ((i * 7) % 256) as u8).collect();
        let pa = RadialVarianceProfile::compute(64, 64, &data_a);
        let pb = RadialVarianceProfile::compute(64, 64, &data_b);
        let sim = pa.similarity(&pb);
        // Uniform vs noisy: should be low similarity.
        assert!(
            sim < 0.5,
            "different images should have low radial similarity: {sim}"
        );
    }

    #[test]
    fn test_temporal_rhythm_constant() {
        let changes = vec![5.0; 100];
        let rhythm = TemporalRhythm::from_frame_changes(&changes);
        // All bins should be 1.0 (constant normalised to max).
        for &b in &rhythm.bins {
            assert!((b - 1.0).abs() < 1e-6, "constant changes -> all bins = 1.0");
        }
    }

    #[test]
    fn test_temporal_rhythm_empty() {
        let rhythm = TemporalRhythm::from_frame_changes(&[]);
        for &b in &rhythm.bins {
            assert_eq!(b, 0.0);
        }
    }

    #[test]
    fn test_temporal_rhythm_self_similarity() {
        let changes: Vec<f64> = (0..200)
            .map(|i| (i as f64 * 0.1).sin().abs() * 10.0)
            .collect();
        let rhythm = TemporalRhythm::from_frame_changes(&changes);
        let sim = rhythm.similarity(&rhythm);
        assert!((sim - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_spectral_peaks_identical() {
        let peaks = vec![(1, 10), (2, 20), (5, 50)];
        let a = SpectralPeakConstellation::new(peaks.clone());
        let b = SpectralPeakConstellation::new(peaks);
        let sim = a.similarity(&b);
        assert!((sim - 1.0).abs() < 1e-10, "identical peaks should be 1.0");
    }

    #[test]
    fn test_spectral_peaks_no_overlap() {
        let a = SpectralPeakConstellation::new(vec![(0, 0), (1, 1)]);
        let b = SpectralPeakConstellation::new(vec![(100, 100), (200, 200)]);
        let sim = a.similarity(&b);
        assert_eq!(sim, 0.0);
    }

    #[test]
    fn test_spectral_peaks_tolerance() {
        // Peaks differ by ±1 in each dimension — should still match.
        let a = SpectralPeakConstellation::new(vec![(10, 20)]);
        let b = SpectralPeakConstellation::new(vec![(11, 21)]);
        let sim = a.similarity(&b);
        assert!(sim > 0.0, "peaks within tolerance should match");
    }

    #[test]
    fn test_spectral_peaks_empty() {
        let a = SpectralPeakConstellation::new(vec![]);
        let b = SpectralPeakConstellation::new(vec![]);
        assert_eq!(a.similarity(&b), 1.0);
    }

    #[test]
    fn test_spectral_peaks_truncation() {
        let many: Vec<(u32, u32)> = (0..100).map(|i| (i, i * 2)).collect();
        let constellation = SpectralPeakConstellation::new(many);
        assert!(constellation.peaks.len() <= SPECTRAL_PEAKS);
    }

    #[test]
    fn test_robust_signature_identical() {
        let peaks = vec![(1, 10), (5, 50)];
        let radial_data: Vec<u8> = (0..32 * 32).map(|i| (i % 256) as u8).collect();
        let changes: Vec<f64> = (0..100).map(|i| (i as f64).sin().abs() * 20.0).collect();

        let sig_a = RobustSignature::new("asset_a")
            .with_phash(0xDEAD_BEEF_CAFE_BABE)
            .with_radial(RadialVarianceProfile::compute(32, 32, &radial_data))
            .with_temporal(TemporalRhythm::from_frame_changes(&changes))
            .with_spectral(SpectralPeakConstellation::new(peaks.clone()))
            .with_duration(120.0);

        let sig_b = RobustSignature::new("asset_b")
            .with_phash(0xDEAD_BEEF_CAFE_BABE)
            .with_radial(RadialVarianceProfile::compute(32, 32, &radial_data))
            .with_temporal(TemporalRhythm::from_frame_changes(&changes))
            .with_spectral(SpectralPeakConstellation::new(peaks))
            .with_duration(120.0);

        let result = sig_a.compare(&sig_b);
        assert!(
            result.overall_score > 0.99,
            "identical sigs should match: {}",
            result.overall_score
        );
        assert!(result.is_match(0.95));
        assert_eq!(result.contributing_signals(), 4);
    }

    #[test]
    fn test_robust_signature_different() {
        let sig_a = RobustSignature::new("a")
            .with_phash(0x0000_0000_0000_0000)
            .with_duration(120.0);
        let sig_b = RobustSignature::new("b")
            .with_phash(0xFFFF_FFFF_FFFF_FFFF)
            .with_duration(120.0);

        let result = sig_a.compare(&sig_b);
        assert!(
            result.overall_score < 0.1,
            "very different sigs: {}",
            result.overall_score
        );
    }

    #[test]
    fn test_robust_signature_duration_reject() {
        let sig_a = RobustSignature::new("a")
            .with_phash(0xDEAD_BEEF)
            .with_duration(60.0);
        let sig_b = RobustSignature::new("b")
            .with_phash(0xDEAD_BEEF)
            .with_duration(120.0);

        let result = sig_a.compare(&sig_b);
        assert_eq!(result.overall_score, 0.0, "duration mismatch should reject");
    }

    #[test]
    fn test_robust_signature_partial_signals() {
        // Only phash available on both.
        let sig_a = RobustSignature::new("a").with_phash(0xAAAA);
        let sig_b = RobustSignature::new("b").with_phash(0xAAAA);

        let result = sig_a.compare(&sig_b);
        assert!(result.overall_score > 0.99);
        assert_eq!(result.contributing_signals(), 1);
    }

    #[test]
    fn test_robust_signature_no_signals() {
        let sig_a = RobustSignature::new("a");
        let sig_b = RobustSignature::new("b");
        let result = sig_a.compare(&sig_b);
        assert_eq!(result.overall_score, 0.0);
        assert_eq!(result.contributing_signals(), 0);
    }

    #[test]
    fn test_robust_signature_signal_count() {
        let sig = RobustSignature::new("a")
            .with_phash(0x1234)
            .with_spectral(SpectralPeakConstellation::new(vec![(1, 2)]));
        assert_eq!(sig.signal_count(), 2);
    }

    #[test]
    fn test_robust_signature_watermark_resilience() {
        // Simulating watermark: same base image with a few pixel changes.
        // The radial variance should remain similar because the global
        // structure is unchanged.
        let base: Vec<u8> = (0..64 * 64).map(|i| (i % 256) as u8).collect();
        let mut watermarked = base.clone();
        // Add a "watermark" in the corner (change 100 pixels).
        for i in 0..100 {
            if i < watermarked.len() {
                watermarked[i] = 255;
            }
        }

        let pa = RadialVarianceProfile::compute(64, 64, &base);
        let pb = RadialVarianceProfile::compute(64, 64, &watermarked);
        let sim = pa.similarity(&pb);
        assert!(
            sim > 0.8,
            "watermarked image should still be similar: {sim}"
        );
    }
}