forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

multisync.rs141 lines, 5.4 KiBHistoryRawDownload
1//! Syncing the cameras of a multicam clip by their sound.
2//!
3//! Every camera hears the same room, so the loudness curves of their tracks have the same shape,
4//! shifted by the distance between the moments the cameras started rolling. [`best_lag`] finds
5//! that shift by normalised cross-correlation of the two curves (the dB levels of
6//! [`crate::silence::levels`], 50 a second, with the slow trend taken out), which is accurate to
7//! one 20 ms window and needs no more than a clap, a voice or a song both cameras heard.
8
9use crate::silence::WINDOWS_PER_SEC;
10
11/// How much of each track's start is listened to, in seconds.
12pub const SYNC_SECS: f64 = 240.0;
13
14/// The furthest apart two cameras' starts may be, in seconds.
15pub const MAX_LAG_SECS: f64 = 120.0;
16
17/// A match weaker than this normalised correlation is not believed.
18pub const MIN_SCORE: f32 = 0.2;
19
20/// The shortest overlap, in seconds, a lag is judged on.
21const MIN_OVERLAP_SECS: f64 = 3.0;
22
23/// The lowest level that counts, in dB: below it a track is silence.
24const FLOOR_DB: f32 = -70.0;
25
26/// Where `other` sits against `reference`.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct Lag {
29 /// Seconds later than in the reference that the same sound happens in the other track: the
30 /// other camera started this much earlier when it is positive.
31 pub secs: f64,
32 /// The normalised correlation at that lag, 0 to 1.
33 pub score: f32,
34}
35
36/// The loudness curve with its trend (a one-second running mean) removed and silence clamped, so
37/// that only the events are left to match.
38fn events(levels: &[f32]) -> Vec<f32> {
39 let v: Vec<f32> = levels.iter().map(|l| l.clamp(FLOOR_DB, 0.0)).collect();
40 let half = (WINDOWS_PER_SEC / 2) as usize;
41 let mut prefix = vec![0.0f64; v.len() + 1];
42 for (i, x) in v.iter().enumerate() {
43 prefix[i + 1] = prefix[i] + f64::from(*x);
44 }
45 (0..v.len())
46 .map(|i| {
47 let (a, b) = (i.saturating_sub(half), (i + half + 1).min(v.len()));
48 v[i] - ((prefix[b] - prefix[a]) / (b - a) as f64) as f32
49 })
50 .collect()
51}
52
53/// The lag of `other` against `reference`, both loudness curves in dB at [`WINDOWS_PER_SEC`], within
54/// `max_lag_secs`. `None` when either is too short or silent to judge.
55pub fn best_lag(reference: &[f32], other: &[f32], max_lag_secs: f64) -> Option<Lag> {
56 let (x, y) = (events(reference), events(other));
57 let rate = f64::from(WINDOWS_PER_SEC);
58 let min_overlap = ((MIN_OVERLAP_SECS * rate) as usize).min(x.len().min(y.len()) / 2).max(1);
59 if x.len().min(y.len()) < 10 {
60 return None;
61 }
62 let sq = |v: &[f32]| {
63 let mut p = vec![0.0f64; v.len() + 1];
64 for (i, a) in v.iter().enumerate() {
65 p[i + 1] = p[i] + f64::from(*a) * f64::from(*a);
66 }
67 p
68 };
69 let (px, py) = (sq(&x), sq(&y));
70 let max_lag = (max_lag_secs * rate) as i64;
71 let mut best: Option<(i64, f64)> = None;
72 for lag in -max_lag.min(x.len() as i64)..=max_lag.min(y.len() as i64) {
73 // x[i] pairs with y[i + lag].
74 let lo = (-lag).max(0) as usize;
75 let hi = (x.len() as i64).min(y.len() as i64 - lag);
76 if hi <= lo as i64 {
77 continue;
78 }
79 let hi = hi as usize;
80 if hi - lo < min_overlap {
81 continue;
82 }
83 let dot: f64 = x[lo..hi].iter().zip(&y[(lo as i64 + lag) as usize..]).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();
84 let ex = px[hi] - px[lo];
85 let ey = py[(hi as i64 + lag) as usize] - py[(lo as i64 + lag) as usize];
86 if ex <= 1e-9 || ey <= 1e-9 {
87 continue;
88 }
89 let score = dot / (ex * ey).sqrt();
90 if best.is_none_or(|(_, s)| score > s) {
91 best = Some((lag, score));
92 }
93 }
94 best.map(|(lag, score)| Lag { secs: lag as f64 / rate, score: score.clamp(0.0, 1.0) as f32 })
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 /// A track of `secs` seconds: a quiet room and a burst of `len` seconds from `at` (dB levels).
102 fn burst(secs: f64, at: f64, len: f64) -> Vec<f32> {
103 let rate = f64::from(WINDOWS_PER_SEC);
104 (0..(secs * rate) as usize)
105 .map(|i| {
106 let t = i as f64 / rate;
107 match t >= at && t < at + len {
108 true => -12.0,
109 false => -65.0 - ((i * 7) % 5) as f32,
110 }
111 })
112 .collect()
113 }
114
115 #[test]
116 fn a_burst_delayed_by_one_point_three_seconds_is_found() {
117 let a = burst(30.0, 4.0, 0.6);
118 let b = burst(30.0, 5.3, 0.6);
119 let lag = best_lag(&a, &b, 20.0).expect("a lag");
120 assert!((lag.secs - 1.3).abs() < 0.021, "{lag:?}");
121 assert!(lag.score > 0.9, "{lag:?}");
122 let back = best_lag(&b, &a, 20.0).expect("a lag");
123 assert!((back.secs + 1.3).abs() < 0.021, "{back:?}");
124 }
125
126 #[test]
127 fn a_louder_or_noisier_copy_still_lines_up() {
128 let a = burst(40.0, 6.0, 0.4);
129 let mut b: Vec<f32> = burst(40.0, 3.0, 0.4).iter().map(|l| l + 9.0).collect();
130 b.truncate(30 * WINDOWS_PER_SEC as usize);
131 let lag = best_lag(&a, &b, 30.0).expect("a lag");
132 assert!((lag.secs + 3.0).abs() < 0.021, "{lag:?}");
133 }
134
135 #[test]
136 fn silence_and_stubs_are_not_matched() {
137 let quiet = vec![-120.0; 3000];
138 assert!(best_lag(&quiet, &quiet, 10.0).is_none());
139 assert!(best_lag(&[0.0; 4], &[0.0; 4], 10.0).is_none());
140 }
141}