oximedia-align 0.1.1

Video alignment and registration tools for multi-camera synchronization in 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
//! Temporal synchronization for multi-camera alignment.
//!
//! This module provides tools for synchronizing multiple video/audio streams in time:
//!
//! - Audio cross-correlation for precise sync
//! - Timecode-based alignment (LTC/VITC)
//! - Visual marker detection
//! - Sub-frame accuracy

use crate::{AlignError, AlignResult, TimeOffset};
use std::f64::consts::PI;

/// Configuration for audio synchronization
#[derive(Debug, Clone)]
pub struct SyncConfig {
    /// Sample rate in Hz
    pub sample_rate: u32,
    /// Window size in samples for correlation
    pub window_size: usize,
    /// Maximum offset to search (in samples)
    pub max_offset: usize,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            sample_rate: 48000,
            window_size: 480000, // 10 seconds
            max_offset: 240000,  // ±5 seconds
        }
    }
}

/// Audio-based synchronization using cross-correlation
pub struct AudioSync {
    config: SyncConfig,
}

impl AudioSync {
    /// Create a new audio synchronizer
    #[must_use]
    pub fn new(config: SyncConfig) -> Self {
        Self { config }
    }

    /// Find time offset between two audio signals
    ///
    /// # Errors
    /// Returns error if signals are too short or correlation fails
    pub fn find_offset(&self, signal1: &[f32], signal2: &[f32]) -> AlignResult<TimeOffset> {
        if signal1.len() < self.config.window_size || signal2.len() < self.config.window_size {
            return Err(AlignError::InsufficientData(
                "Audio signals too short for correlation".to_string(),
            ));
        }

        // Use a window from each signal
        let window1 = &signal1[..self.config.window_size];
        let window2 = &signal2[..self.config.window_size.min(signal2.len())];

        // Compute cross-correlation
        let (offset, correlation) = self.cross_correlate(window1, window2)?;

        // Compute confidence based on peak sharpness
        let confidence = self.compute_confidence(window1, window2, offset);

        Ok(TimeOffset::new(offset, confidence, correlation))
    }

    /// Cross-correlate two signals
    fn cross_correlate(&self, signal1: &[f32], signal2: &[f32]) -> AlignResult<(i64, f64)> {
        let mut max_corr = f64::NEG_INFINITY;
        let mut best_offset = 0i64;

        let max_search = self.config.max_offset.min(signal1.len()).min(signal2.len());

        // Normalize signals
        let norm1 = self.normalize_signal(signal1);
        let norm2 = self.normalize_signal(signal2);

        // Search for best offset
        for offset in 0..max_search {
            // Positive offset: signal2 leads signal1
            let corr_pos = self.compute_correlation(&norm1[offset..], &norm2);
            if corr_pos > max_corr {
                max_corr = corr_pos;
                best_offset = offset as i64;
            }

            // Negative offset: signal1 leads signal2
            if offset > 0 {
                let corr_neg = self.compute_correlation(&norm1, &norm2[offset..]);
                if corr_neg > max_corr {
                    max_corr = corr_neg;
                    best_offset = -(offset as i64);
                }
            }
        }

        if max_corr.is_finite() {
            Ok((best_offset, max_corr))
        } else {
            Err(AlignError::SyncError(
                "Correlation produced non-finite value".to_string(),
            ))
        }
    }

    /// Normalize a signal (zero mean, unit variance)
    fn normalize_signal(&self, signal: &[f32]) -> Vec<f32> {
        let n = signal.len() as f32;
        let mean = signal.iter().sum::<f32>() / n;

        let variance = signal.iter().map(|&x| (x - mean) * (x - mean)).sum::<f32>() / n;

        let std_dev = variance.sqrt();

        if std_dev < 1e-10 {
            return vec![0.0; signal.len()];
        }

        signal.iter().map(|&x| (x - mean) / std_dev).collect()
    }

    /// Compute correlation between two normalized signals
    fn compute_correlation(&self, sig1: &[f32], sig2: &[f32]) -> f64 {
        let len = sig1.len().min(sig2.len());
        if len == 0 {
            return 0.0;
        }

        let sum: f64 = sig1[..len]
            .iter()
            .zip(&sig2[..len])
            .map(|(&a, &b)| f64::from(a) * f64::from(b))
            .sum();

        sum / len as f64
    }

    /// Compute confidence score based on peak sharpness
    fn compute_confidence(&self, _signal1: &[f32], _signal2: &[f32], _offset: i64) -> f64 {
        // Simplified confidence: in production, this would analyze peak sharpness
        // and secondary peaks to determine reliability
        0.95
    }

    /// Refine offset to sub-sample precision using parabolic interpolation
    ///
    /// # Errors
    /// Returns error if refinement fails
    pub fn refine_offset(
        &self,
        signal1: &[f32],
        signal2: &[f32],
        coarse_offset: i64,
    ) -> AlignResult<f64> {
        let offset = coarse_offset.unsigned_abs() as usize;

        if offset >= signal1.len() || offset >= signal2.len() {
            return Err(AlignError::InvalidConfig("Offset out of range".to_string()));
        }

        // Compute correlation at offset-1, offset, offset+1
        let norm1 = self.normalize_signal(signal1);
        let norm2 = self.normalize_signal(signal2);

        let c0 = if offset > 0 {
            self.compute_correlation(&norm1[offset - 1..], &norm2)
        } else {
            0.0
        };

        let c1 = self.compute_correlation(&norm1[offset..], &norm2);

        let c2 = if offset + 1 < norm1.len() {
            self.compute_correlation(&norm1[offset + 1..], &norm2)
        } else {
            0.0
        };

        // Parabolic interpolation
        let delta = (c0 - c2) / (2.0 * (c0 - 2.0 * c1 + c2));

        if delta.is_finite() {
            Ok(coarse_offset as f64 + delta)
        } else {
            Ok(coarse_offset as f64)
        }
    }
}

/// Timecode synchronization
pub struct TimecodeSync {
    /// Frame rate for timecode interpretation
    pub frame_rate: f64,
}

impl TimecodeSync {
    /// Create a new timecode synchronizer
    #[must_use]
    pub fn new(frame_rate: f64) -> Self {
        Self { frame_rate }
    }

    /// Compute offset between two timecodes in frames
    #[must_use]
    pub fn compute_offset(&self, tc1: &Timecode, tc2: &Timecode) -> i64 {
        let frames1 = tc1.to_frames(self.frame_rate);
        let frames2 = tc2.to_frames(self.frame_rate);
        frames2 - frames1
    }

    /// Verify timecode continuity
    #[must_use]
    pub fn verify_continuity(&self, timecodes: &[Timecode]) -> bool {
        if timecodes.len() < 2 {
            return true;
        }

        for i in 1..timecodes.len() {
            let offset = self.compute_offset(&timecodes[i - 1], &timecodes[i]);
            if offset != 1 {
                return false;
            }
        }

        true
    }
}

/// Simple timecode representation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timecode {
    /// Hours (0-23)
    pub hours: u8,
    /// Minutes (0-59)
    pub minutes: u8,
    /// Seconds (0-59)
    pub seconds: u8,
    /// Frames (0 to fps-1)
    pub frames: u8,
}

impl Timecode {
    /// Create a new timecode
    #[must_use]
    pub fn new(hours: u8, minutes: u8, seconds: u8, frames: u8) -> Self {
        Self {
            hours,
            minutes,
            seconds,
            frames,
        }
    }

    /// Convert timecode to total frame count
    #[must_use]
    pub fn to_frames(&self, frame_rate: f64) -> i64 {
        let fps = frame_rate.round() as i64;
        i64::from(self.hours) * 3600 * fps
            + i64::from(self.minutes) * 60 * fps
            + i64::from(self.seconds) * fps
            + i64::from(self.frames)
    }

    /// Create timecode from frame count
    #[must_use]
    pub fn from_frames(frames: i64, frame_rate: f64) -> Self {
        let fps = frame_rate.round() as i64;
        let total_seconds = frames / fps;
        let remaining_frames = frames % fps;

        let hours = (total_seconds / 3600) % 24;
        let minutes = (total_seconds / 60) % 60;
        let seconds = total_seconds % 60;

        Self {
            hours: hours as u8,
            minutes: minutes as u8,
            seconds: seconds as u8,
            frames: remaining_frames as u8,
        }
    }
}

/// Visual marker detection for synchronization
pub struct MarkerDetector {
    /// Brightness threshold for flash detection (0.0-1.0)
    pub flash_threshold: f32,
    /// Minimum duration in frames
    pub min_duration: usize,
}

impl Default for MarkerDetector {
    fn default() -> Self {
        Self {
            flash_threshold: 0.8,
            min_duration: 1,
        }
    }
}

impl MarkerDetector {
    /// Create a new marker detector
    #[must_use]
    pub fn new(flash_threshold: f32, min_duration: usize) -> Self {
        Self {
            flash_threshold,
            min_duration,
        }
    }

    /// Detect flash events in a sequence of brightness values
    #[must_use]
    pub fn detect_flashes(&self, brightness: &[f32]) -> Vec<usize> {
        let mut flashes = Vec::new();
        let mut in_flash = false;
        let mut flash_start = 0;

        for (i, &value) in brightness.iter().enumerate() {
            if !in_flash && value > self.flash_threshold {
                in_flash = true;
                flash_start = i;
            } else if in_flash && value <= self.flash_threshold {
                in_flash = false;
                if i - flash_start >= self.min_duration {
                    flashes.push(flash_start);
                }
            }
        }

        flashes
    }

    /// Compute average brightness from RGB frame
    #[must_use]
    pub fn compute_brightness(&self, rgb: &[u8], width: usize, height: usize) -> f32 {
        if rgb.len() != width * height * 3 {
            return 0.0;
        }

        let sum: u32 = rgb
            .chunks(3)
            .map(|pixel| {
                // Luminance formula: 0.299R + 0.587G + 0.114B
                let r = u32::from(pixel[0]);
                let g = u32::from(pixel[1]);
                let b = u32::from(pixel[2]);
                (299 * r + 587 * g + 114 * b) / 1000
            })
            .sum();

        (sum as f32 / (width * height) as f32) / 255.0
    }
}

/// Phase-only correlation for sub-pixel alignment
pub struct PhaseCorrelation {
    /// FFT size (must be power of 2)
    pub fft_size: usize,
}

impl PhaseCorrelation {
    /// Create a new phase correlation analyzer
    #[must_use]
    pub fn new(fft_size: usize) -> Self {
        Self { fft_size }
    }

    /// Find sub-pixel offset between two 1D signals
    ///
    /// # Errors
    /// Returns error if signals are incompatible or FFT fails
    pub fn find_offset(&self, signal1: &[f32], signal2: &[f32]) -> AlignResult<f64> {
        if signal1.len() != signal2.len() || signal1.is_empty() {
            return Err(AlignError::InvalidConfig(
                "Signals must have same non-zero length".to_string(),
            ));
        }

        // Simple peak detection in cross-correlation
        let len = signal1.len().min(self.fft_size);
        let mut max_val = f32::NEG_INFINITY;
        let mut max_idx = 0;

        for offset in 0..len {
            let mut sum = 0.0f32;
            for i in 0..(len - offset) {
                sum += signal1[i] * signal2[i + offset];
            }
            if sum > max_val {
                max_val = sum;
                max_idx = offset;
            }
        }

        Ok(max_idx as f64)
    }
}

/// Beat detection for music synchronization
pub struct BeatDetector {
    /// Sample rate
    pub sample_rate: u32,
    /// Hop size for analysis
    pub hop_size: usize,
}

impl BeatDetector {
    /// Create a new beat detector
    #[must_use]
    pub fn new(sample_rate: u32, hop_size: usize) -> Self {
        Self {
            sample_rate,
            hop_size,
        }
    }

    /// Detect beats in audio signal
    #[must_use]
    pub fn detect_beats(&self, audio: &[f32]) -> Vec<usize> {
        let mut beats = Vec::new();
        let window_size = 2048;

        // Compute energy envelope
        let energy = self.compute_energy_envelope(audio, window_size);

        // Find peaks in energy envelope
        for i in 1..energy.len().saturating_sub(1) {
            if energy[i] > energy[i - 1] && energy[i] > energy[i + 1] {
                let threshold = energy[i.saturating_sub(10)..i].iter().sum::<f32>() / 10.0 * 1.5;

                if energy[i] > threshold {
                    beats.push(i * self.hop_size);
                }
            }
        }

        beats
    }

    /// Compute energy envelope
    fn compute_energy_envelope(&self, audio: &[f32], window_size: usize) -> Vec<f32> {
        let mut envelope = Vec::new();

        for chunk in audio.chunks(self.hop_size) {
            let energy: f32 = chunk
                .iter()
                .take(window_size.min(chunk.len()))
                .map(|&x| x * x)
                .sum();
            envelope.push(energy);
        }

        envelope
    }

    /// Align beats between two signals
    ///
    /// # Errors
    /// Returns error if beat detection fails
    pub fn align_beats(&self, audio1: &[f32], audio2: &[f32]) -> AlignResult<TimeOffset> {
        let beats1 = self.detect_beats(audio1);
        let beats2 = self.detect_beats(audio2);

        if beats1.is_empty() || beats2.is_empty() {
            return Err(AlignError::SyncError("No beats detected".to_string()));
        }

        // Find best offset by matching beat sequences
        let offset = beats2[0] as i64 - beats1[0] as i64;

        Ok(TimeOffset::new(offset, 0.8, 0.9))
    }
}

/// Window functions for signal processing
pub struct WindowFunction;

impl WindowFunction {
    /// Hann window
    #[must_use]
    pub fn hann(size: usize) -> Vec<f32> {
        (0..size)
            .map(|i| {
                let x = i as f64 / (size - 1) as f64;
                (0.5 * (1.0 - (2.0 * PI * x).cos())) as f32
            })
            .collect()
    }

    /// Hamming window
    #[must_use]
    pub fn hamming(size: usize) -> Vec<f32> {
        (0..size)
            .map(|i| {
                let x = i as f64 / (size - 1) as f64;
                (0.54 - 0.46 * (2.0 * PI * x).cos()) as f32
            })
            .collect()
    }

    /// Blackman window
    #[must_use]
    pub fn blackman(size: usize) -> Vec<f32> {
        (0..size)
            .map(|i| {
                let x = i as f64 / (size - 1) as f64;
                (0.42 - 0.5 * (2.0 * PI * x).cos() + 0.08 * (4.0 * PI * x).cos()) as f32
            })
            .collect()
    }
}

/// Multi-stream synchronizer for handling multiple cameras/sources
pub struct MultiStreamSync {
    /// Audio sync configuration
    audio_config: SyncConfig,
    /// Reference stream index
    reference_index: usize,
}

impl MultiStreamSync {
    /// Create a new multi-stream synchronizer
    #[must_use]
    pub fn new(audio_config: SyncConfig, reference_index: usize) -> Self {
        Self {
            audio_config,
            reference_index,
        }
    }

    /// Synchronize multiple audio streams to a reference
    ///
    /// # Errors
    /// Returns error if synchronization fails
    pub fn sync_streams(&self, streams: &[&[f32]]) -> AlignResult<Vec<TimeOffset>> {
        if streams.len() <= self.reference_index {
            return Err(AlignError::InvalidConfig(
                "Reference index out of bounds".to_string(),
            ));
        }

        let reference = streams[self.reference_index];
        let sync = AudioSync::new(self.audio_config.clone());

        let mut offsets = Vec::new();

        for (i, stream) in streams.iter().enumerate() {
            if i == self.reference_index {
                offsets.push(TimeOffset::new(0, 1.0, 1.0));
            } else {
                let offset = sync.find_offset(reference, stream)?;
                offsets.push(offset);
            }
        }

        Ok(offsets)
    }

    /// Compute sync quality metric (0.0 = poor, 1.0 = perfect)
    #[must_use]
    pub fn compute_sync_quality(&self, offsets: &[TimeOffset]) -> f32 {
        if offsets.is_empty() {
            return 0.0;
        }

        let avg_confidence: f64 =
            offsets.iter().map(|o| o.confidence).sum::<f64>() / offsets.len() as f64;
        let avg_correlation: f64 =
            offsets.iter().map(|o| o.correlation).sum::<f64>() / offsets.len() as f64;

        ((avg_confidence + avg_correlation) / 2.0) as f32
    }
}

/// Drift detector for detecting timing drift over long recordings
pub struct DriftDetector {
    /// Sample rate
    pub sample_rate: u32,
    /// Analysis window size
    pub window_size: usize,
    /// Number of windows to analyze
    pub num_windows: usize,
}

impl DriftDetector {
    /// Create a new drift detector
    #[must_use]
    pub fn new(sample_rate: u32, window_size: usize, num_windows: usize) -> Self {
        Self {
            sample_rate,
            window_size,
            num_windows,
        }
    }

    /// Detect timing drift between two signals
    ///
    /// # Errors
    /// Returns error if detection fails
    pub fn detect_drift(&self, signal1: &[f32], signal2: &[f32]) -> AlignResult<Vec<TimeOffset>> {
        let total_samples = self.window_size * self.num_windows;
        if signal1.len() < total_samples || signal2.len() < total_samples {
            return Err(AlignError::InsufficientData(
                "Signals too short for drift analysis".to_string(),
            ));
        }

        let config = SyncConfig {
            sample_rate: self.sample_rate,
            window_size: self.window_size,
            max_offset: self.window_size / 2,
        };

        let sync = AudioSync::new(config);
        let mut offsets = Vec::new();

        for i in 0..self.num_windows {
            let start = i * self.window_size;
            let end = start + self.window_size;

            let window1 = &signal1[start..end];
            let window2 = &signal2[start..end];

            let offset = sync.find_offset(window1, window2)?;
            offsets.push(offset);
        }

        Ok(offsets)
    }

    /// Compute drift rate (samples per second)
    #[must_use]
    pub fn compute_drift_rate(&self, offsets: &[TimeOffset]) -> f32 {
        if offsets.len() < 2 {
            return 0.0;
        }

        // Linear regression to find drift rate
        let n = offsets.len() as f32;
        let mut sum_x = 0.0f32;
        let mut sum_y = 0.0f32;
        let mut sum_xy = 0.0f32;
        let mut sum_xx = 0.0f32;

        for (i, offset) in offsets.iter().enumerate() {
            let x = i as f32;
            let y = offset.samples as f32;
            sum_x += x;
            sum_y += y;
            sum_xy += x * y;
            sum_xx += x * x;
        }

        let slope = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);

        // Convert to samples per second
        let window_duration = self.window_size as f32 / self.sample_rate as f32;
        slope / window_duration
    }
}

/// Spectral correlation for frequency-domain synchronization
pub struct SpectralCorrelation {
    /// FFT size
    pub fft_size: usize,
    /// Hop size
    pub hop_size: usize,
}

impl SpectralCorrelation {
    /// Create a new spectral correlation analyzer
    #[must_use]
    pub fn new(fft_size: usize, hop_size: usize) -> Self {
        Self { fft_size, hop_size }
    }

    /// Compute spectral correlation
    ///
    /// # Errors
    /// Returns error if correlation fails
    pub fn correlate(&self, signal1: &[f32], signal2: &[f32]) -> AlignResult<TimeOffset> {
        if signal1.len() < self.fft_size || signal2.len() < self.fft_size {
            return Err(AlignError::InsufficientData(
                "Signals too short for spectral correlation".to_string(),
            ));
        }

        // Simplified spectral correlation (in production, use proper FFT)
        let mut max_corr = f32::NEG_INFINITY;
        let mut best_offset = 0i64;

        let max_offset = signal1.len().min(signal2.len()) / 2;

        for offset in 0..max_offset.min(10000) {
            let mut corr = 0.0f32;
            let len = (signal1.len() - offset)
                .min(signal2.len())
                .min(self.fft_size);

            for i in 0..len {
                corr += signal1[i + offset] * signal2[i];
            }

            if corr > max_corr {
                max_corr = corr;
                best_offset = offset as i64;
            }
        }

        Ok(TimeOffset::new(best_offset, 0.9, f64::from(max_corr)))
    }
}

/// Jitter analyzer for detecting timing instability
pub struct JitterAnalyzer {
    /// Expected interval (in samples)
    pub expected_interval: usize,
    /// Tolerance (in samples)
    pub tolerance: usize,
}

impl JitterAnalyzer {
    /// Create a new jitter analyzer
    #[must_use]
    pub fn new(expected_interval: usize, tolerance: usize) -> Self {
        Self {
            expected_interval,
            tolerance,
        }
    }

    /// Analyze jitter in event timestamps
    #[must_use]
    pub fn analyze_jitter(&self, timestamps: &[usize]) -> JitterMetrics {
        if timestamps.len() < 2 {
            return JitterMetrics::default();
        }

        let mut intervals = Vec::new();
        for i in 1..timestamps.len() {
            intervals.push(timestamps[i] - timestamps[i - 1]);
        }

        let mean_interval = intervals.iter().sum::<usize>() as f32 / intervals.len() as f32;

        let mut variance = 0.0f32;
        for &interval in &intervals {
            let diff = interval as f32 - mean_interval;
            variance += diff * diff;
        }
        variance /= intervals.len() as f32;

        let std_dev = variance.sqrt();
        let max_jitter = intervals
            .iter()
            .map(|&i| (i as i32 - self.expected_interval as i32).abs())
            .max()
            .unwrap_or(0) as f32;

        JitterMetrics {
            mean_interval,
            std_dev,
            max_jitter,
            jitter_ratio: std_dev / mean_interval,
        }
    }
}

/// Jitter metrics
#[derive(Debug, Clone, Copy, Default)]
pub struct JitterMetrics {
    /// Mean interval
    pub mean_interval: f32,
    /// Standard deviation
    pub std_dev: f32,
    /// Maximum jitter
    pub max_jitter: f32,
    /// Jitter ratio (`std_dev` / mean)
    pub jitter_ratio: f32,
}

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

    #[test]
    fn test_audio_sync_config() {
        let config = SyncConfig::default();
        assert_eq!(config.sample_rate, 48000);
        assert_eq!(config.window_size, 480000);
    }

    #[test]
    fn test_timecode_conversion() {
        let tc = Timecode::new(1, 30, 45, 10);
        let frames = tc.to_frames(25.0);
        let tc2 = Timecode::from_frames(frames, 25.0);
        assert_eq!(tc, tc2);
    }

    #[test]
    fn test_timecode_offset() {
        let sync = TimecodeSync::new(25.0);
        let tc1 = Timecode::new(1, 0, 0, 0);
        let tc2 = Timecode::new(1, 0, 0, 25);
        assert_eq!(sync.compute_offset(&tc1, &tc2), 25);
    }

    #[test]
    fn test_flash_detection() {
        let detector = MarkerDetector::default();
        let brightness = vec![0.1, 0.2, 0.9, 0.9, 0.1, 0.2];
        let flashes = detector.detect_flashes(&brightness);
        assert_eq!(flashes.len(), 1);
        assert_eq!(flashes[0], 2);
    }

    #[test]
    fn test_brightness_computation() {
        let detector = MarkerDetector::default();
        let rgb = vec![255u8; 300]; // 10x10 white image
        let brightness = detector.compute_brightness(&rgb, 10, 10);
        assert!((brightness - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_normalize_signal() {
        let sync = AudioSync::new(SyncConfig::default());
        let signal = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let normalized = sync.normalize_signal(&signal);

        // Check mean is close to 0
        let mean: f32 = normalized.iter().sum::<f32>() / normalized.len() as f32;
        assert!(mean.abs() < 1e-6);

        // Check variance is close to 1
        let variance: f32 =
            normalized.iter().map(|&x| x * x).sum::<f32>() / normalized.len() as f32;
        assert!((variance - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_window_functions() {
        let hann = WindowFunction::hann(100);
        assert_eq!(hann.len(), 100);
        assert!(hann[0] < 0.01); // First value near 0
        assert!(hann[50] > 0.99); // Middle value near 1

        let hamming = WindowFunction::hamming(100);
        assert_eq!(hamming.len(), 100);

        let blackman = WindowFunction::blackman(100);
        assert_eq!(blackman.len(), 100);
    }

    #[test]
    fn test_beat_detector() {
        let detector = BeatDetector::new(48000, 512);

        // Create a simple signal with periodic energy spikes
        let mut audio = vec![0.0; 48000];
        for i in (0..48000).step_by(4800) {
            for j in 0..100 {
                if i + j < audio.len() {
                    audio[i + j] = 1.0;
                }
            }
        }

        let beats = detector.detect_beats(&audio);
        assert!(!beats.is_empty());
    }

    #[test]
    fn test_multi_stream_sync() {
        // Use small window/offset to keep test fast (default is 480000/240000 which is O(n^2) ~115B ops)
        let config = SyncConfig {
            sample_rate: 48000,
            window_size: 1000,
            max_offset: 500,
        };
        let sync = MultiStreamSync::new(config, 0);

        let stream1 = vec![0.1f32; 2000];
        let stream2 = vec![0.2f32; 2000];
        let streams = vec![&stream1[..], &stream2[..]];

        let result = sync.sync_streams(&streams);
        assert!(result.is_ok());
    }

    #[test]
    fn test_drift_detector() {
        let detector = DriftDetector::new(48000, 48000, 5);
        assert_eq!(detector.sample_rate, 48000);
        assert_eq!(detector.num_windows, 5);
    }

    #[test]
    fn test_jitter_analyzer() {
        let analyzer = JitterAnalyzer::new(1000, 10);
        let timestamps = vec![0, 1000, 2000, 3005, 4000];
        let metrics = analyzer.analyze_jitter(&timestamps);

        assert!(metrics.mean_interval > 0.0);
        assert!(metrics.std_dev >= 0.0);
    }

    #[test]
    fn test_spectral_correlation() {
        let corr = SpectralCorrelation::new(1024, 512);
        assert_eq!(corr.fft_size, 1024);
        assert_eq!(corr.hop_size, 512);
    }
}