Skip to main content

sva_samples/measure/
periodicity.rs

1// Concern: how strongly onset strength repeats per sliding window: broadband, low, rest | Non-concern: the band filters (bands.rs), any verdict | IO: (&[f64], rate, start, hop, window) -> Periodicity
2
3use super::bands::{self, Bands, Smoothing};
4use super::onsets::spectral_flux;
5use super::sliding::{self, Stats, Unread, stats};
6use crate::fft::{fft, ifft};
7use crate::stft::hann_periodic;
8
9/// A band belongs to `low` where its centre is under this; kick and sub sit there.
10pub const SPLIT_HZ: f64 = 150.0;
11/// 600 bpm, a sixteenth at 150 bpm.
12pub const MIN_PERIOD_SECS: f64 = 0.1;
13/// 30 bpm.
14pub const MAX_PERIOD_SECS: f64 = 2.0;
15pub const PEAKS: usize = 3;
16/// Each band's energy through two one-poles at 10 Hz before it is decimated: a sustained
17/// tone's ripple at twice its frequency, which would alias into the envelope, falls 12 dB an
18/// octave and no longer outweighs a slow swell's rise.
19pub const SMOOTHING: Smoothing = Smoothing {
20    hz: Some(10.0),
21    poles: 2,
22};
23
24pub const MODEL: &str = "onset strength: the spectral flux `onsets` takes, sum over a group's \
25                         bands of max(0, e[n] - e[n-1]), run over the ERB bands of `bands` \
26                         (Glasberg and Moore's filter widths), e each band's RMS envelope at \
27                         `envelope_hz`, its energy smoothed before decimation by \
28                         `smoothing.poles` one-pole lowpasses at `smoothing.hz` in place of the \
29                         one at the band's own width `bands` reads through, so an onset is \
30                         spread over some 30 ms; linear amplitude so a loud band outweighs a quiet one, \
31                         from the filters' silent start; the first component alone. A band is \
32                         `low` where its centre is under `split_hz` and `rest` otherwise; \
33                         `broadband` sums every band. The filters' skirts overlap, so a kick \
34                         leaks into `rest` and a hat's attack into `low`, attenuated. That \
35                         filterbank, smoothed envelope and rectified difference is Scheirer, E. D. \
36                         (1998), Tempo and beat analysis of acoustic musical signals, J. Acoust. \
37                         Soc. Am. 103(1) 588-601. Each window is `window_secs` of that envelope \
38                         centred on t, t stepping by `hop_secs` from the target's start as \
39                         every framed reading steps, clipped to the target at its ends, \
40                         `from`/`to` its span; its mean is subtracted, y. height(tau) = sum over \
41                         n < W - tau of y[n] y[n + tau] over sum of y[n]^2, the autocorrelation \
42                         of the onset envelope Ellis, D. P. W. (2007), Beat tracking by dynamic \
43                         programming, J. New Music Res. 36(1) 51-60, reads tempo from, \
44                         normalized at lag 0 and biased: |height| <= 1 by Cauchy-Schwarz, \
45                         taken by FFT and exact up to its rounding, and an envelope repeating \
46                         exactly every tau peaks near 1 - tau/W, so of two periods that repeat \
47                         equally the shorter reads higher, and heights at different periods or \
48                         spans are not on one scale. place(tau): the same y under a periodic \
49                         Hann taper w, sum of y[n] w[n] y[n + tau] w[n + tau] over sum of w[n] \
50                         w[n + tau], the taper's own autocorrelation divided out: the window's \
51                         ends no longer cut an onset abruptly, which in the plain sum skews a \
52                         peak by up to a quarter lag, and the bias toward short lags is gone \
53                         (Harris, F. J. (1978), On the use of windows for harmonic analysis \
54                         with the discrete Fourier transform, Proc. IEEE 66(1) 51-83). peaks: \
55                         lags L from `min_period_secs` to `max_period_secs` whose height is \
56                         positive and whose place is over the lag before's and no lower than \
57                         the lag after's, the highest three by height, highest first, each \
58                         with the plain curve's height at L. period: L + d lags of \
59                         `lag_step_secs`, d the vertex of the parabola through place at L - 1, \
60                         L and L + 1 (Smith, J. O. and Serra, X. (1987), PARSHL, Proc. ICMC), \
61                         |d| <= 1/2; bpm = 60 / period. Bounds: under the model that place is \
62                         symmetric about the true period P and falls strictly away from it, L \
63                         reading at least its neighbours puts P within half a lag of L, and \
64                         the higher neighbour names the half: P lies in [L, L + 1/2] where \
65                         place at L + 1 is over place at L - 1, in [L - 1/2, L] otherwise; d \
66                         lies in that half too, so P is within r of the period, r the farther \
67                         end of that half from it, r <= 1/2 lag. `period_bounds_secs` is \
68                         period -+ r and `bpm_bounds` 60 over those. They cover the lag grid \
69                         and the interpolation alone, under that model, which no window can \
70                         confirm: an envelope not periodic across the window (a tempo moving, \
71                         onsets jittered) is outside it, and its place need not peak at any \
72                         one period. Both are null where the window refutes the model, place \
73                         not falling strictly from L - 1 to L - 2 and from L + 1 to L + 2, or \
74                         leaves the stated span, clipped at the target's ends. No tempo prior \
75                         (Ellis weights by a log-Gaussian) and no octave choice: a beat, its \
76                         half and its double may each lead, and each is reported; no inter-onset \
77                         clustering or beat tracking (Dixon, S. (2001), Automatic extraction \
78                         of tempo and beat from expressive performances, J. New Music Res. \
79                         30(1) 39-58) is done. drift_bpm: the leading peak's bpm less the \
80                         previous window's, null where either has none, so a lead jumping \
81                         between a beat and its double reads as a large drift. curve, where \
82                         asked: the height at every lag from `min_period_secs` by \
83                         `lag_step_secs` to the window's longest; heights and curves are null \
84                         where the window's envelope is constant. summary: over the windows \
85                         with a peak, the leading peak's bpm and height and the drift, their \
86                         mean, min and max with the t each stands at. Exact path: none; a \
87                         closed form, its onsets placed exactly or not, is read off its \
88                         rendered samples like any other, because the onset strength is the \
89                         band envelopes' rise, which no closed form states";
90
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum Group {
93    Broadband,
94    Low,
95    Rest,
96}
97
98impl Group {
99    pub const ALL: [Group; 3] = [Group::Broadband, Group::Low, Group::Rest];
100
101    pub fn key(self) -> &'static str {
102        match self {
103            Group::Broadband => "broadband",
104            Group::Low => "low",
105            Group::Rest => "rest",
106        }
107    }
108}
109
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct Peak {
112    pub period_secs: f64,
113    /// Where MODEL's symmetric peak puts the true period; `None` where the window refutes or
114    /// leaves that model.
115    pub period_bounds_secs: Option<(f64, f64)>,
116    pub bpm: f64,
117    /// 60 over `period_bounds_secs`.
118    pub bpm_bounds: Option<(f64, f64)>,
119    /// The plain curve's height at the peak's lag.
120    pub height: f64,
121}
122
123#[derive(Clone, Debug, PartialEq)]
124pub struct Window {
125    pub t_secs: f64,
126    pub from_secs: f64,
127    pub to_secs: f64,
128    /// Highest first.
129    pub peaks: Vec<Peak>,
130    pub drift_bpm: Option<f64>,
131    /// `None` where not asked; NaN at each lag where the envelope is constant.
132    pub curve: Option<Vec<f64>>,
133}
134
135#[derive(Clone, Copy, Debug, PartialEq)]
136pub struct Summary {
137    pub windows_with_peak: usize,
138    pub bpm: Option<Stats>,
139    pub height: Option<Stats>,
140    pub drift_bpm: Option<Stats>,
141}
142
143#[derive(Clone, Debug, PartialEq)]
144pub struct Track {
145    pub group: Group,
146    pub centres_hz: Vec<f64>,
147    pub windows: Vec<Window>,
148    pub summary: Summary,
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub struct Periodicity {
153    pub hop_secs: f64,
154    pub window_secs: f64,
155    pub envelope_hz: f64,
156    pub lag_step_secs: f64,
157    pub min_period_secs: f64,
158    pub max_period_secs: f64,
159    pub tracks: Vec<Track>,
160}
161
162pub fn measure(
163    samples: &[f64],
164    sample_rate: f64,
165    start_secs: f64,
166    hop_secs: f64,
167    window_secs: f64,
168    curve: bool,
169) -> Result<Periodicity, Unread> {
170    sliding::fits(samples.len(), sample_rate, window_secs, MAX_PERIOD_SECS)?;
171    let split = bands::smoothed(samples, sample_rate, start_secs, SMOOTHING);
172    let rate = split.rate_hz;
173    let lags = Lags {
174        min: (MIN_PERIOD_SECS * rate).ceil() as usize,
175        max: (MAX_PERIOD_SECS * rate).floor() as usize,
176        rate,
177    };
178    let len = split.bands.first().map_or(0, |b| b.rms.len());
179    let grid = sliding::spans(
180        samples.len(),
181        sample_rate,
182        start_secs,
183        hop_secs,
184        rate,
185        window_secs,
186        len,
187    );
188    let size = (grid.window_secs * rate).round() as usize;
189    let tracks = Group::ALL
190        .into_iter()
191        .zip(envelopes(&split))
192        .map(|(group, (centres_hz, envelope))| {
193            let mut windows: Vec<Window> = grid
194                .spans
195                .iter()
196                .map(|s| {
197                    let (heights, place) = heights(&envelope[s.from..s.to], lags.max + 1);
198                    Window {
199                        t_secs: s.t_secs,
200                        from_secs: s.from_secs,
201                        to_secs: s.to_secs,
202                        peaks: lags.peaks(&heights, &place, s.to - s.from == size),
203                        drift_bpm: None,
204                        curve: curve.then(|| {
205                            heights[..heights.len().min(lags.max + 1)]
206                                .iter()
207                                .skip(lags.min)
208                                .copied()
209                                .collect()
210                        }),
211                    }
212                })
213                .collect();
214            for i in 1..windows.len() {
215                let lead = |w: &Window| w.peaks.first().map(|p| p.bpm);
216                windows[i].drift_bpm = lead(&windows[i])
217                    .zip(lead(&windows[i - 1]))
218                    .map(|(a, b)| a - b);
219            }
220            Track {
221                group,
222                centres_hz,
223                summary: summary(&windows),
224                windows,
225            }
226        })
227        .collect();
228    Ok(Periodicity {
229        hop_secs: grid.hop_secs,
230        window_secs: grid.window_secs,
231        envelope_hz: rate,
232        lag_step_secs: 1.0 / rate,
233        min_period_secs: lags.min as f64 / rate,
234        max_period_secs: lags.max as f64 / rate,
235        tracks,
236    })
237}
238
239/// Each group's band centres and onset-strength envelope, in `Group::ALL`'s order.
240fn envelopes(split: &Bands) -> Vec<(Vec<f64>, Vec<f64>)> {
241    let tracks = &split.bands;
242    let low = tracks
243        .iter()
244        .position(|b| b.centre_hz >= SPLIT_HZ)
245        .unwrap_or(tracks.len());
246    let ranges = [0..tracks.len(), 0..low, low..tracks.len()];
247    let len = tracks.first().map_or(0, |b| b.rms.len());
248    let mut flux: Vec<Vec<f64>> = ranges.iter().map(|_| vec![0.0; len]).collect();
249    let (mut prev, mut curr) = (vec![0.0; tracks.len()], vec![0.0; tracks.len()]);
250    for n in 0..len {
251        for (held, band) in curr.iter_mut().zip(tracks) {
252            *held = band.rms[n];
253        }
254        if n > 0 {
255            for (out, range) in flux.iter_mut().zip(&ranges) {
256                out[n] = spectral_flux(&prev[range.clone()], &curr[range.clone()]);
257            }
258        }
259        std::mem::swap(&mut prev, &mut curr);
260    }
261    ranges
262        .into_iter()
263        .zip(flux)
264        .map(|(range, envelope)| {
265            let centres = tracks[range].iter().map(|b| b.centre_hz).collect();
266            (centres, envelope)
267        })
268        .collect()
269}
270
271/// At lags `0..=top` the segment holds: the mean-removed segment's autocorrelation over its
272/// value at lag 0, and MODEL's place, the curve a peak is located on.
273fn heights(segment: &[f64], top: usize) -> (Vec<f64>, Vec<f64>) {
274    let top = top.min(segment.len().saturating_sub(1));
275    let mean = segment.iter().sum::<f64>() / segment.len() as f64;
276    let y: Vec<f64> = segment.iter().map(|x| x - mean).collect();
277    let taper = hann_periodic(segment.len());
278    let tapered: Vec<f64> = y.iter().zip(&taper).map(|(y, w)| y * w).collect();
279    let plain = correlated(&y, top);
280    let (curve, own) = (correlated(&tapered, top), correlated(&taper, top));
281    (
282        plain.iter().map(|r| r / plain[0]).collect(),
283        curve.iter().zip(&own).map(|(c, w)| c / w).collect(),
284    )
285}
286
287/// sum over n of x[n] x[n + tau] at lags `0..=top`, zero-padded past `len + top` so no lag wraps.
288fn correlated(x: &[f64], top: usize) -> Vec<f64> {
289    let n = (x.len() + top + 1).next_power_of_two();
290    let mut re = vec![0.0; n];
291    re[..x.len()].copy_from_slice(x);
292    let mut im = vec![0.0; n];
293    fft(&mut re, &mut im);
294    for (r, i) in re.iter_mut().zip(im.iter_mut()) {
295        *r = *r * *r + *i * *i;
296        *i = 0.0;
297    }
298    ifft(&mut re, &mut im);
299    re.truncate(top + 1);
300    re
301}
302
303struct Lags {
304    min: usize,
305    max: usize,
306    rate: f64,
307}
308
309impl Lags {
310    /// Local maxima of `place`, ranked by `heights`, each located and bounded as MODEL states;
311    /// `whole` where the window holds its full span.
312    fn peaks(&self, heights: &[f64], place: &[f64], whole: bool) -> Vec<Peak> {
313        let last = self.max.min(heights.len().saturating_sub(2));
314        let mut found: Vec<(usize, f64)> = (self.min.max(1)..=last)
315            .filter(|&l| heights[l] > 0.0 && place[l] > place[l - 1] && place[l] >= place[l + 1])
316            .map(|l| (l, heights[l]))
317            .collect();
318        found.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
319        found
320            .into_iter()
321            .take(PEAKS)
322            .map(|(lag, height)| {
323                let (before, at, after) = (place[lag - 1], place[lag], place[lag + 1]);
324                let shift = 0.5 * (before - after) / (before - 2.0 * at + after);
325                let half = match after > before {
326                    true => (0.0, 0.5),
327                    false => (-0.5, 0.0),
328                };
329                let reach = (shift - half.0).max(half.1 - shift);
330                let secs = |l: f64| (lag as f64 + l) / self.rate;
331                let period_secs = secs(shift);
332                let falls = place[lag - 2] < before
333                    && place.get(lag + 2).is_some_and(|&beyond| beyond < after);
334                let bounds = (whole && falls).then(|| (secs(shift - reach), secs(shift + reach)));
335                Peak {
336                    period_secs,
337                    period_bounds_secs: bounds,
338                    bpm: 60.0 / period_secs,
339                    bpm_bounds: bounds.map(|(lo, hi)| (60.0 / hi, 60.0 / lo)),
340                    height,
341                }
342            })
343            .collect()
344    }
345}
346
347fn summary(windows: &[Window]) -> Summary {
348    let leads = || {
349        windows
350            .iter()
351            .filter_map(|w| w.peaks.first().map(|p| (w.t_secs, *p)))
352    };
353    Summary {
354        windows_with_peak: leads().count(),
355        bpm: stats(leads().map(|(t, p)| (t, p.bpm))),
356        height: stats(leads().map(|(t, p)| (t, p.height))),
357        drift_bpm: stats(
358            windows
359                .iter()
360                .filter_map(|w| w.drift_bpm.map(|d| (w.t_secs, d))),
361        ),
362    }
363}