forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

beats.rs456 lines, 16.6 KiBHistoryRawDownload
1//! Where a sound's beat falls, so a cut can land on the music.
2//!
3//! Three steps, the same shape as [`crate::silence`]: [`analyse`] decodes a
4//! stretch of a file once and turns it into an onset-strength envelope (spectral
5//! flux over 1024-sample Hann frames, 512 hop, at the file's own rate, streamed
6//! so a long take never sits in memory whole); [`find`] reads that envelope for
7//! a tempo and a grid of beats along it; [`timeline_beats`] puts those beats on
8//! the timeline through one clip's own range and rate, the way
9//! [`crate::silence::timeline_regions`] does for silences.
10//!
11//! The tempo is the autocorrelation peak between 60 and 200 BPM, with a mild
12//! preference for the octave near 120 so a click at 120 is not read as 60 or
13//! 240 by a hair. The beats are a fixed-period grid, and the phase of that grid
14//! is the one whose grid points sit on the most onset energy. It is not a
15//! tracker for music whose tempo drifts: a grid is what a cut needs, and a drift
16//! shows as beats that slide off the hits after a while.
17
18use std::path::Path;
19use std::sync::Arc;
20
21use rustfft::num_complex::Complex;
22use rustfft::{Fft, FftPlanner};
23
24use crate::AudioSession;
25use crate::project::{Clip, Marker, MarkerColor};
26
27/// Samples per analysis frame.
28pub const FRAME: usize = 1024;
29/// Samples between the starts of two frames: 512, so each frame overlaps the last by half.
30pub const HOP: usize = 512;
31/// The slowest tempo looked for, in beats per minute.
32pub const MIN_BPM: f64 = 60.;
33/// The fastest tempo looked for, in beats per minute.
34pub const MAX_BPM: f64 = 200.;
35
36/// The envelope's peak, below which the sound is silence to the detector.
37const SILENT_PEAK: f32 = 1e-3;
38/// The best periodicity a sound may show and still have a beat, as a fraction of its own energy.
39const MIN_PULSE: f64 = 0.1;
40
41/// What a beat search came back with. The beats are seconds **from where the read
42/// began**, in order, one per beat of the grid; the caller maps them.
43#[derive(Clone, Debug, PartialEq)]
44pub enum Found {
45 /// The file has no audio track, so there is no music to listen to.
46 NoAudio,
47 /// The sound is silent, so no beat can be heard in it.
48 Silent,
49 /// The sound has no steady pulse one could keep time to.
50 NoPulse,
51 /// A steady pulse: its tempo and every beat along it.
52 Beats { bpm: f64, times: Vec<f64> },
53}
54
55/// The onset-strength envelope of a stretch of `stream` of `path` over the
56/// half-open `range` of source seconds, and the rate its frames come at. Frame
57/// `i` covers samples `i*HOP .. i*HOP + FRAME`, and its centre is the beat time
58/// the grid is built on.
59pub fn analyse(
60 path: impl AsRef<Path>,
61 stream: usize,
62 range: (f64, f64),
63) -> crate::Result<Option<(Vec<f32>, f64)>> {
64 let from = range.0.max(0.);
65 let sources = [(path.as_ref().to_path_buf(), stream)];
66 let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), from, range.1)])?
67 else {
68 return Ok(None);
69 };
70 let rate = f64::from(meta.sample_rate).max(1.);
71 let channels = (meta.channels as usize).max(1);
72 let mut onsets = Onsets::new();
73 let mut mono: Vec<f32> = Vec::new();
74 for chunk in rx {
75 mono.clear();
76 // Folded to one channel: a beat is a beat in either ear.
77 mono.extend(
78 chunk
79 .samples
80 .chunks(channels)
81 .map(|f| f.iter().sum::<f32>() / channels as f32),
82 );
83 onsets.push(&mono);
84 }
85 Ok(Some((onsets.finish(), rate)))
86}
87
88/// Streams mono samples into the onset envelope: Hann-windowed frames, log-compressed
89/// magnitudes, and the positive change in every bin since the frame before.
90struct Onsets {
91 fft: Arc<dyn Fft<f32>>,
92 window: Vec<f32>,
93 /// Samples not yet consumed by a whole frame.
94 pending: Vec<f32>,
95 /// Log magnitudes of the previous frame, one per bin up to Nyquist.
96 prev: Vec<f32>,
97 buf: Vec<Complex<f32>>,
98 env: Vec<f32>,
99}
100
101impl Onsets {
102 fn new() -> Self {
103 let fft = FftPlanner::<f32>::new().plan_fft_forward(FRAME);
104 let window = (0..FRAME)
105 .map(|i| {
106 let x = std::f32::consts::PI * 2. * i as f32 / FRAME as f32;
107 0.5 - 0.5 * x.cos()
108 })
109 .collect();
110 Self {
111 fft,
112 window,
113 pending: Vec::new(),
114 prev: vec![0.; FRAME / 2 + 1],
115 buf: vec![Complex::new(0., 0.); FRAME],
116 env: Vec::new(),
117 }
118 }
119
120 fn push(&mut self, mono: &[f32]) {
121 self.pending.extend_from_slice(mono);
122 let mut at = 0;
123 while self.pending.len() - at >= FRAME {
124 for (i, slot) in self.buf.iter_mut().enumerate() {
125 *slot = Complex::new(self.pending[at + i] * self.window[i], 0.);
126 }
127 self.fft.process(&mut self.buf);
128 let mut flux = 0f32;
129 for k in 0..=FRAME / 2 {
130 let mag = self.buf[k].norm() / FRAME as f32;
131 let db = (1. + 100. * mag).ln();
132 flux += (db - self.prev[k]).max(0.);
133 self.prev[k] = db;
134 }
135 self.env.push(flux);
136 at += HOP;
137 }
138 self.pending.drain(..at);
139 }
140
141 fn finish(self) -> Vec<f32> {
142 self.env
143 }
144}
145
146/// The beats in an envelope read at `frame_rate` frames a second (the rate
147/// [`analyse`] gives back over [`HOP`]).
148pub fn find(env: &[f32], frame_rate: f64) -> Found {
149 let peak = env.iter().copied().fold(0f32, f32::max);
150 if peak <= SILENT_PEAK {
151 return Found::Silent;
152 }
153 let n = env.len();
154 if n < 4 || frame_rate <= 0. {
155 return Found::NoPulse;
156 }
157 let mean = env.iter().map(|&v| f64::from(v)).sum::<f64>() / n as f64;
158 let x: Vec<f64> = env.iter().map(|&v| f64::from(v) - mean).collect();
159 // Autocorrelation at every whole lag up to the slowest beat, each divided by its
160 // overlap so a long lag is not penalised for being short of data.
161 let lag_max = (frame_rate * 60. / MIN_BPM).ceil() as usize + 1;
162 let lag_max = lag_max.min(n - 1);
163 let ac: Vec<f64> = (0..=lag_max)
164 .map(|lag| {
165 let s: f64 = x[..n - lag].iter().zip(&x[lag..]).map(|(a, b)| a * b).sum();
166 s / (n - lag) as f64
167 })
168 .collect();
169 let energy = ac[0];
170 if energy <= 0. {
171 return Found::NoPulse;
172 }
173 // Best tempo on a 0.1 BPM grid, the autocorrelation read between whole lags. The
174 // log-octave prior is mild (one octave is a factor of e^-0.5) and only breaks a tie
175 // between a tempo and its double or half.
176 let mut best = (f64::NEG_INFINITY, MIN_BPM);
177 let mut bpm = MIN_BPM;
178 while bpm <= MAX_BPM + 1e-9 {
179 let lag = frame_rate * 60. / bpm;
180 let (lo, frac) = (lag.floor() as usize, lag - lag.floor());
181 if lo < lag_max {
182 let at = ac[lo] * (1. - frac) + ac[lo + 1] * frac;
183 let prior = (-0.5 * ((bpm / 120.).log2()).powi(2)).exp();
184 let score = at * prior;
185 if score > best.0 {
186 best = (score, bpm);
187 }
188 }
189 bpm += 0.1;
190 }
191 let (_, bpm) = best;
192 let period = frame_rate * 60. / bpm;
193 // The pulse has to show in the sound itself, not only in the prior's favourite tempo.
194 if ac_at(&ac, period) / energy < MIN_PULSE {
195 return Found::NoPulse;
196 }
197 // Phase: the grid point offset whose beats sit on the most onset energy. Searched in
198 // quarter frames, over one period.
199 let mut best_phase = (f64::NEG_INFINITY, 0.);
200 let mut phase = 0.;
201 while phase < period {
202 let mut sum = 0f64;
203 let mut p = phase;
204 while p < n as f64 {
205 sum += f64::from(x_at(&x, p));
206 p += period;
207 }
208 if sum > best_phase.0 {
209 best_phase = (sum, phase);
210 }
211 phase += 0.25;
212 }
213 let mut times = Vec::new();
214 let mut p = best_phase.1;
215 while p < n as f64 {
216 // Snapped to the strongest frame within two of the grid point, so a beat that sits a
217 // hair off the grid lands on its hit.
218 let centre = p.round() as usize;
219 let lo = centre.saturating_sub(2);
220 let hi = (centre + 2).min(n - 1);
221 let mut at = centre.min(n - 1);
222 for i in lo..=hi {
223 if env[i] > env[at] {
224 at = i;
225 }
226 }
227 times.push((at * HOP + FRAME / 2) as f64 / (frame_rate * HOP as f64));
228 p += period;
229 }
230 Found::Beats { bpm, times }
231}
232
233fn ac_at(ac: &[f64], lag: f64) -> f64 {
234 let lo = lag.floor() as usize;
235 let frac = lag - lag.floor();
236 if lo + 1 >= ac.len() {
237 return 0.;
238 }
239 ac[lo] * (1. - frac) + ac[lo + 1] * frac
240}
241
242fn x_at(x: &[f64], at: f64) -> f32 {
243 let i = (at.round() as usize).min(x.len() - 1);
244 x[i] as f32
245}
246
247/// [`analyse`] and [`find`] in one, for a stretch of a file: what a card or a tool asks.
248/// `Found::NoAudio` for a file with no audio track.
249pub fn detect(path: impl AsRef<Path>, stream: usize, range: (f64, f64)) -> crate::Result<Found> {
250 let Some((env, rate)) = analyse(path, stream, range)? else {
251 return Ok(Found::NoAudio);
252 };
253 Ok(find(&env, rate / HOP as f64))
254}
255
256/// Every `every`th beat, starting with the first: `every` 1 is every beat, 4 is one per bar of
257/// four. A value of 0 is treated as 1.
258pub fn every_nth(times: &[f64], every: usize) -> Vec<f64> {
259 times.iter().copied().step_by(every.max(1)).collect()
260}
261
262/// The note a beat marker carries, and the one that tells a beat marker from any other.
263pub const BEAT_NOTE: &str = "Beat";
264/// The colour beat markers are drawn in: apart from the blue a marker gets by default.
265pub const BEAT_COLOR: MarkerColor = MarkerColor::Yellow;
266
267/// A beat marker on `frame`: a point, named and noted "Beat", in [`BEAT_COLOR`].
268pub fn beat_marker(frame: u32) -> Marker {
269 Marker {
270 frame,
271 length: 0,
272 name: BEAT_NOTE.to_string(),
273 note: BEAT_NOTE.to_string(),
274 color: BEAT_COLOR,
275 }
276}
277
278/// The indices, in order, of the beat markers that start inside `from..to` frames: the ones a
279/// new set of beats for that clip replaces. Remove them highest index first.
280pub fn beat_marker_indices(markers: &[Marker], from: u32, to: u32) -> Vec<usize> {
281 markers
282 .iter()
283 .enumerate()
284 .filter(|(_, m)| m.note == BEAT_NOTE && m.frame >= from && m.frame < to)
285 .map(|(i, _)| i)
286 .collect()
287}
288
289/// Where those beat times sit on the timeline, as frames of the lane `clip` is on: `times` are
290/// seconds from the clip's in point, which is where [`analyse`] began reading, so they land at
291/// `in_frame` plus that. Positions go through the clip's own rate, and a beat outside the part
292/// of the source the clip plays is dropped. Frames come back in order with no repeats.
293pub fn timeline_beats(clip: &Clip, fps: f64, times: &[f64]) -> Vec<u32> {
294 if !(fps.is_finite() && fps > 0.) {
295 return Vec::new();
296 }
297 let mut out: Vec<u32> = Vec::with_capacity(times.len());
298 for &t in times {
299 let src = (t * fps).round();
300 if src.is_nan() || src < 0. {
301 continue;
302 }
303 let src = clip.in_frame.saturating_add(src.min(f64::from(u32::MAX)) as u32);
304 if src < clip.in_frame || src >= clip.out_frame {
305 continue;
306 }
307 let at = clip.start + clip.timeline_offset(src - clip.in_frame);
308 if out.last() != Some(&at) {
309 out.push(at);
310 }
311 }
312 out
313}
314
315#[cfg(test)]
316mod tests {
317 use std::path::{Path, PathBuf};
318 use std::process::Command;
319
320 use super::{Found, HOP, detect, find, timeline_beats};
321 use crate::project::{Clip, Speed};
322 use crate::scale::FitPolicy;
323
324 /// An onset envelope of pulses every `period` frames, with a little noise of
325 /// the sort a real mix leaves, so the test is not a pure comb.
326 fn comb(n: usize, period: f64, phase: f64) -> Vec<f32> {
327 let mut env = vec![0.02f32; n];
328 let mut p = phase;
329 while p < n as f64 {
330 env[p as usize] = 1.;
331 env[(p as usize + 1).min(n - 1)] = 0.4;
332 p += period;
333 }
334 for (i, v) in env.iter_mut().enumerate() {
335 *v += 0.01 * ((i * 7919) % 13) as f32 / 13.;
336 }
337 env
338 }
339
340 #[test]
341 fn a_steady_comb_gives_its_tempo_and_its_beats() {
342 // 86.13 frames a second at 44.1 kHz and HOP 512; 120 BPM is a beat every 43.07 frames.
343 let rate = 44_100. / HOP as f64;
344 let period = rate * 60. / 120.;
345 let env = comb(4000, period, 10.);
346 let Found::Beats { bpm, times } = find(&env, rate) else {
347 panic!("a steady pulse is a beat");
348 };
349 assert!((bpm - 120.).abs() <= 2., "bpm {bpm}");
350 assert!(times.len() > 80, "{} beats", times.len());
351 }
352
353 #[test]
354 fn silence_is_silent_and_noise_has_no_pulse() {
355 let rate = 86.13;
356 assert_eq!(find(&vec![0.; 500], rate), Found::Silent);
357 // Noise has energy but no periodicity at any tempo in range.
358 let mut seed = 12_345u64;
359 let noise: Vec<f32> = (0..2000)
360 .map(|_| {
361 seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
362 (seed >> 40) as f32 / (1u64 << 24) as f32
363 })
364 .collect();
365 assert_eq!(find(&noise, rate), Found::NoPulse);
366 }
367
368 /// A scratch directory for one test's ffmpeg output, emptied and made again.
369 fn scratch(tag: &str) -> PathBuf {
370 let dir = std::env::temp_dir().join(format!("edith-beats-{tag}-{}", std::process::id()));
371 let _ = std::fs::remove_dir_all(&dir);
372 std::fs::create_dir_all(&dir).expect("scratch dir");
373 dir
374 }
375
376 /// Renders `expr` (an aevalsrc expression of `t`) as ten seconds of 44.1 kHz mono WAV.
377 fn render(dir: &Path, name: &str, expr: &str) -> PathBuf {
378 let out = dir.join(name);
379 let status = Command::new("ffmpeg")
380 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
381 .arg(format!("aevalsrc='{expr}':d=10:s=44100:c=mono"))
382 .args(["-c:a", "pcm_s16le"])
383 .arg(&out)
384 .status()
385 .expect("ffmpeg runs");
386 assert!(status.success(), "ffmpeg made {name}");
387 out
388 }
389
390 /// Two beats per second is 120 BPM: a 20 ms 1 kHz burst on every half second.
391 #[test]
392 fn a_click_track_at_120_bpm_gives_120_and_every_half_second() {
393 let dir = scratch("click");
394 let wav = render(&dir, "click120.wav", "0.8*sin(2*PI*1000*t)*lt(mod(t,0.5),0.02)");
395 let found = detect(&wav, 0, (0., f64::INFINITY)).expect("analyse");
396 let _ = std::fs::remove_dir_all(&dir);
397 let Found::Beats { bpm, times } = found else {
398 panic!("a click track has beats: {found:?}");
399 };
400 assert!((bpm - 120.).abs() <= 2., "bpm {bpm}");
401 // Within one frame at 25 fps of a multiple of 0.5 s, every beat in the ten seconds.
402 assert!((18..=21).contains(&times.len()), "{} beats", times.len());
403 for &t in &times {
404 let off = (t - (t / 0.5).round() * 0.5).abs();
405 assert!(off < 1. / 25., "beat at {t} is {off} s off the grid");
406 }
407 }
408
409 #[test]
410 fn a_silent_clip_has_no_beats() {
411 let dir = scratch("silent");
412 let wav = render(&dir, "silent.wav", "0");
413 let found = detect(&wav, 0, (0., f64::INFINITY)).expect("analyse");
414 let _ = std::fs::remove_dir_all(&dir);
415 assert_eq!(found, Found::Silent);
416 }
417
418 #[test]
419 fn beats_land_on_the_timeline_through_the_clip() {
420 // 25 fps; a clip at frame 100 that plays source frames 50..300 at normal speed.
421 let clip = Clip {
422 speed_keys: Vec::new(),
423 reversed: false,
424 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
425 angle: Default::default(),
426 fade_in: 0,
427 fade_out: 0,
428 transition_out: 0,
429 transition_kind: Default::default(),
430 visualizer: 0,
431 viz_paint: 0,
432 gain_db: 0.0,
433 gain_keys: Vec::new(),
434 pan: 0,
435 transform_keys: Vec::new(),
436 opacity_keys: Vec::new(),
437 color_keys: Vec::new(),
438 effects: Vec::new(),
439 start: 100,
440 in_frame: 50,
441 out_frame: 300,
442 source: 0,
443 link: None,
444 eq: None,
445 color: None,
446 transform: None,
447 fit: FitPolicy::default(),
448 speed: Speed::default(),
449 pitch: 0.0,
450 };
451 // 0.5 s is source frame 62.5, rounded to 63 -> timeline 113; 1.0 s is 75 -> 125.
452 // 20 s is past the clip's end and is dropped.
453 assert_eq!(timeline_beats(&clip, 25., &[0.5, 1.0, 20.]), vec![113, 125]);
454 assert!(timeline_beats(&clip, 0., &[0.5]).is_empty());
455 }
456}