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