Skip to main content

sva_samples/measure/
onsets.rs

1// Concern: spectral flux onset detection, each onset placed at the sample its strike rises | Non-concern: a tempo grid, what an onset means musically | IO: (planes, rate, start) -> Onsets
2
3use crate::measure::spectrum::{MAX_PINNED_FRAME, magnitudes, pinned_frame};
4
5/// ~23ms: short enough to localize a transient, long enough for low percussion.
6const FRAME_SECS: f64 = 0.023;
7/// Strikes 25 ms apart peak a few hops from each other.
8const HOP_SECS: f64 = FRAME_SECS / 8.0;
9/// Below this two novelty peaks are one transient's attack and decay.
10const MIN_ONSET_GAP_SECS: f64 = 0.02;
11const ADAPTIVE_WINDOW_SECS: f64 = 0.115;
12/// A roll's flux peaks barely over its mean; the strike tells it from a swell.
13const THRESHOLD_MULTIPLIER: f64 = 1.0;
14const THRESHOLD_DELTA: f64 = 1e-6;
15const IOI_BUCKET_SECS: f64 = 0.025;
16const IOI_MAX_SECS: f64 = 2.0;
17/// Under this share of the loudest frame a rise is leakage.
18const LEVEL_FRACTION: f64 = 0.03;
19const STRIKE_SPAN_SECS: f64 = 0.012;
20/// ~5 dB over the span before, carried on as it moved: a strike jumps off a ring's fall.
21const JUMP_ENERGY_RATIO: f64 = 3.0;
22
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct Onset {
25    pub t_secs: f64,
26    pub strength: f64,
27}
28
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct IoiBucket {
31    pub lo_secs: f64,
32    pub hi_secs: f64,
33    pub count: usize,
34}
35
36#[derive(Clone, Debug, PartialEq)]
37pub struct Onsets {
38    pub onsets: Vec<Onset>,
39    pub ioi_histogram: Vec<IoiBucket>,
40    pub resolution_secs: f64,
41}
42
43struct SpectralFrame {
44    t_secs: f64,
45    mags: Vec<Vec<f64>>,
46    span_secs: f64,
47}
48
49fn spectral_frames(planes: &[&[f64]], sample_rate: f64, start_secs: f64) -> Vec<SpectralFrame> {
50    let frame_len = pinned_frame(FRAME_SECS, sample_rate).min(MAX_PINNED_FRAME);
51    let hop = ((HOP_SECS * sample_rate).round() as usize).max(1);
52    let len = planes.iter().map(|p| p.len()).min().unwrap_or(0);
53    (0..len)
54        .step_by(hop)
55        .map(|start| {
56            let end = (start + frame_len).min(len);
57            let mags = planes
58                .iter()
59                .map(|p| magnitudes(&p[start..end], sample_rate, Some(FRAME_SECS)).0)
60                .collect();
61            SpectralFrame {
62                t_secs: start_secs + start as f64 / sample_rate,
63                mags,
64                span_secs: frame_len as f64 / sample_rate,
65            }
66        })
67        .collect()
68}
69
70/// Every channel, so opposite phases cancel nothing.
71pub fn detect(planes: &[&[f64]], sample_rate: f64, start_secs: f64) -> Onsets {
72    let frames = spectral_frames(planes, sample_rate, start_secs);
73    let floor = LEVEL_FRACTION * frames.iter().map(|f| total(&f.mags)).fold(0.0, f64::max);
74    let flux = flux_of(&frames, floor);
75    let onsets = pick_peaks(
76        &flux,
77        &frames,
78        &Energy::of(planes, sample_rate, start_secs),
79        floor,
80    );
81    Onsets {
82        ioi_histogram: ioi_histogram(&onsets),
83        onsets,
84        resolution_secs: HOP_SECS,
85    }
86}
87
88fn total(mags: &[Vec<f64>]) -> f64 {
89    mags.iter().flatten().sum()
90}
91
92/// The rise into each frame; nothing precedes the buffer, so one opening above the floor
93/// opens on a rise from silence.
94fn flux_of(frames: &[SpectralFrame], floor: f64) -> Vec<f64> {
95    let opens_on_sound = frames
96        .first()
97        .is_some_and(|f| floor > 0.0 && total(&f.mags) > floor);
98    (0..frames.len())
99        .map(|i| match i {
100            0 => match opens_on_sound {
101                true => total(&frames[0].mags),
102                false => 0.0,
103            },
104            _ => frames[i - 1]
105                .mags
106                .iter()
107                .zip(&frames[i].mags)
108                .map(|(prev, curr)| spectral_flux(prev, curr))
109                .sum(),
110        })
111        .collect()
112}
113
114pub(crate) fn spectral_flux(prev: &[f64], curr: &[f64]) -> f64 {
115    prev.iter().zip(curr).map(|(&p, &c)| (c - p).max(0.0)).sum()
116}
117
118/// A candidate clears the threshold and the floor, peaks over the gap, and holds a strike;
119/// a frame past the buffer's end reads silence.
120fn pick_peaks(flux: &[f64], frames: &[SpectralFrame], energy: &Energy, floor: f64) -> Vec<Onset> {
121    let mut onsets: Vec<Onset> = Vec::new();
122    let window = (ADAPTIVE_WINDOW_SECS / HOP_SECS).round() as usize;
123    let reach = (MIN_ONSET_GAP_SECS / 2.0 / HOP_SECS).round().max(1.0) as usize;
124    for i in 0..flux.len() {
125        let lo = i.saturating_sub(window);
126        let hi = (i + window + 1).min(flux.len());
127        let local = &flux[lo..hi];
128        let mean = local.iter().sum::<f64>() / local.len() as f64;
129        let threshold = THRESHOLD_DELTA + THRESHOLD_MULTIPLIER * mean;
130        let near = &flux[i.saturating_sub(reach)..(i + reach + 1).min(flux.len())];
131        if flux[i] <= threshold || flux[i] < floor || near.iter().any(|&v| v > flux[i]) {
132            continue;
133        }
134        let Some(t) = energy.strike(frames[i].t_secs, frames[i].span_secs) else {
135            continue;
136        };
137        if onsets
138            .last()
139            .is_some_and(|o| t - o.t_secs < MIN_ONSET_GAP_SECS)
140        {
141            continue;
142        }
143        onsets.push(Onset {
144            t_secs: t,
145            strength: flux[i],
146        });
147    }
148    onsets
149}
150
151struct Energy {
152    running: Vec<f64>,
153    sample_rate: f64,
154    start_secs: f64,
155    reach: usize,
156    floor: f64,
157}
158
159impl Energy {
160    fn of(planes: &[&[f64]], sample_rate: f64, start_secs: f64) -> Energy {
161        let len = planes.iter().map(|p| p.len()).min().unwrap_or(0);
162        let mut running = Vec::with_capacity(len + 1);
163        running.push(0.0);
164        for n in 0..len {
165            let held = running[running.len() - 1];
166            running.push(held + planes.iter().map(|p| p[n] * p[n]).sum::<f64>());
167        }
168        let reach = (STRIKE_SPAN_SECS * sample_rate).round().max(1.0) as usize;
169        let loudest = (0..len)
170            .map(|n| running[(n + reach).min(len)] - running[n])
171            .fold(0.0, f64::max);
172        Energy {
173            running,
174            sample_rate,
175            start_secs,
176            reach,
177            floor: LEVEL_FRACTION * LEVEL_FRACTION * loudest,
178        }
179    }
180
181    /// The energy of `[from, to)`, silence outside the buffer.
182    fn over(&self, from: usize, to: usize) -> f64 {
183        let last = self.running.len() - 1;
184        self.running[to.min(last)] - self.running[from.min(last)]
185    }
186
187    /// The sample whose energy after most outweighs the energy before it and the floor, if
188    /// by a strike's jump over that energy carried on as it moved.
189    fn strike(&self, from_secs: f64, span_secs: f64) -> Option<f64> {
190        let at = |secs: f64| {
191            ((secs - self.start_secs) * self.sample_rate)
192                .round()
193                .max(0.0) as usize
194        };
195        let (from, to) = (at(from_secs), at(from_secs + span_secs));
196        let before = |n: usize| self.over(n.saturating_sub(self.reach), n) + self.floor;
197        let mut best: Option<(f64, usize)> = None;
198        for n in from..to.min(self.running.len() - 1) {
199            let after = self.over(n, n + self.reach);
200            if before(n) == 0.0 {
201                continue;
202            }
203            let ratio = after / before(n);
204            if best.is_none_or(|(r, _)| ratio >= r) {
205                best = Some((ratio, n));
206            }
207        }
208        let (ratio, n) = best?;
209        let carried = before(n) / before(n.saturating_sub(self.reach));
210        (ratio / carried >= JUMP_ENERGY_RATIO)
211            .then(|| self.start_secs + n as f64 / self.sample_rate)
212    }
213}
214
215fn ioi_histogram(onsets: &[Onset]) -> Vec<IoiBucket> {
216    let n = (IOI_MAX_SECS / IOI_BUCKET_SECS).ceil() as usize + 1;
217    let mut counts = vec![0usize; n];
218    for w in onsets.windows(2) {
219        let ioi = w[1].t_secs - w[0].t_secs;
220        counts[((ioi / IOI_BUCKET_SECS) as usize).min(n - 1)] += 1;
221    }
222    counts
223        .into_iter()
224        .enumerate()
225        .map(|(i, count)| IoiBucket {
226            lo_secs: i as f64 * IOI_BUCKET_SECS,
227            hi_secs: if i + 1 == n {
228                f64::INFINITY
229            } else {
230                (i + 1) as f64 * IOI_BUCKET_SECS
231            },
232            count,
233        })
234        .collect()
235}