Skip to main content

sva_samples/measure/
bands.rs

1// Concern: traces one envelope per ERB band, beside that band's own impulse floor | Non-concern: the discrete spectrum (spectrum.rs), what a band means to a listener | IO: (&[f64], sample rate) -> bands
2
3use sva_formula::filter::Shape;
4
5use crate::biquad::{Coeffs, State, design};
6
7/// Glasberg and Moore's auditory filter width in Hz.
8pub fn erb_hz(hz: f64) -> f64 {
9    24.7 * (4.37 * hz / 1000.0 + 1.0)
10}
11
12/// One Cam is one filter width along the cochlea.
13pub fn cam(hz: f64) -> f64 {
14    21.4 * (1.0 + 4.37 * hz / 1000.0).log10()
15}
16
17pub fn hz_at_cam(cam: f64) -> f64 {
18    (10f64.powf(cam / 21.4) - 1.0) * 1000.0 / 4.37
19}
20
21/// 1 to 40 Cam is 51 Hz to 16.4 kHz.
22pub const FIRST_CAM: f64 = 1.0;
23pub const BAND_COUNT: usize = 40;
24
25/// Under the 2-3 ms gap-detection limit, a hundredth of the samples it came from.
26pub const DECIMATED_HZ: f64 = 2000.0;
27
28/// Sixteen time constants is past every band's peak.
29fn floor_secs(erb: f64) -> f64 {
30    (16.0 / erb).clamp(0.02, 2.0)
31}
32
33/// A filter cannot report an onset faster than its own, so a caller subtracts this.
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct BandFloor {
36    pub peak: f64,
37    pub time_to_peak_secs: f64,
38    pub rise_10_90_secs: Option<f64>,
39}
40
41#[derive(Clone, Debug, PartialEq)]
42pub struct BandTrack {
43    pub centre_hz: f64,
44    pub cam: f64,
45    pub erb_hz: f64,
46    pub q: f64,
47    pub peak: f64,
48    pub time_to_peak_secs: Option<f64>,
49    pub rise_10_90_secs: Option<f64>,
50    pub floor: BandFloor,
51    pub rms: Vec<f64>,
52}
53
54#[derive(Clone, Debug, PartialEq)]
55pub struct Bands {
56    pub rate_hz: f64,
57    pub start_secs: f64,
58    pub bands: Vec<BandTrack>,
59}
60
61/// Squaring rectifies; the root at decimation makes the track an RMS.
62struct Chain {
63    pass: Coeffs,
64    smooth: Coeffs,
65    a: State,
66    b: State,
67    energy: State,
68}
69
70impl Chain {
71    fn new(centre_hz: f64, sr: f64) -> Chain {
72        let erb = erb_hz(centre_hz);
73        Chain {
74            pass: design(Shape::Bandpass, centre_hz, centre_hz / erb, 0.0, sr),
75            smooth: design(Shape::OnePole, erb.min(DECIMATED_HZ / 4.0), 0.0, 0.0, sr),
76            a: State::default(),
77            b: State::default(),
78            energy: State::default(),
79        }
80    }
81
82    #[inline]
83    fn step(&mut self, x: f64) -> f64 {
84        let banded = self.b.step(&self.pass, self.a.step(&self.pass, x));
85        self.energy.step(&self.smooth, banded * banded)
86    }
87}
88
89fn trace(centre_hz: f64, sr: f64, hop: usize, n: usize, at: impl Fn(usize) -> f64) -> Vec<f64> {
90    let mut chain = Chain::new(centre_hz, sr);
91    let mut out = Vec::with_capacity(n / hop + 1);
92    for i in 0..n {
93        let energy = chain.step(at(i));
94        if i % hop == 0 {
95            out.push(energy.max(0.0).sqrt());
96        }
97    }
98    out
99}
100
101/// Interpolated between the frames straddling it.
102fn crossing(track: &[f64], until: usize, level: f64, rate: f64) -> Option<f64> {
103    let hit = track[..=until].iter().position(|&v| v >= level)?;
104    if hit == 0 {
105        return Some(0.0);
106    }
107    let (lo, hi) = (track[hit - 1], track[hit]);
108    let frac = match hi > lo {
109        true => (level - lo) / (hi - lo),
110        false => 0.0,
111    };
112    Some((hit as f64 - 1.0 + frac) / rate)
113}
114
115fn stats(track: &[f64], rate: f64) -> (f64, Option<f64>, Option<f64>) {
116    let peak = track.iter().copied().fold(0.0, f64::max);
117    if peak <= 0.0 {
118        return (peak, None, None);
119    }
120    let at = track
121        .iter()
122        .position(|&v| v == peak)
123        .expect("the peak is one of the frames");
124    let t10 = crossing(track, at, 0.1 * peak, rate);
125    let t90 = crossing(track, at, 0.9 * peak, rate);
126    let rise = t10.zip(t90).map(|(a, b)| (b - a).max(0.0));
127    (peak, Some(at as f64 / rate), rise)
128}
129
130fn floor_of(centre_hz: f64, sr: f64, hop: usize, rate: f64) -> BandFloor {
131    let n = (floor_secs(erb_hz(centre_hz)) * sr).round().max(4.0) as usize;
132    let track = trace(centre_hz, sr, hop, n, |i| f64::from(u8::from(i == 0)));
133    let (peak, at, rise) = stats(&track, rate);
134    BandFloor {
135        peak,
136        time_to_peak_secs: at.unwrap_or(0.0),
137        rise_10_90_secs: rise,
138    }
139}
140
141/// A centre the design cannot place is left out, never clamped onto the last it could.
142fn centres(sr: f64) -> Vec<f64> {
143    (0..BAND_COUNT)
144        .map(|k| hz_at_cam(FIRST_CAM + k as f64))
145        .filter(|hz| *hz < 0.45 * sr)
146        .collect()
147}
148
149pub fn analyze(samples: &[f64], sr: f64, start_secs: f64) -> Bands {
150    let hop = (sr / DECIMATED_HZ).round().max(1.0) as usize;
151    let rate = sr / hop as f64;
152    Bands {
153        rate_hz: rate,
154        start_secs,
155        bands: centres(sr)
156            .into_iter()
157            .map(|centre_hz| {
158                let track = trace(centre_hz, sr, hop, samples.len(), |i| samples[i]);
159                let (peak, at, rise) = stats(&track, rate);
160                let erb = erb_hz(centre_hz);
161                BandTrack {
162                    centre_hz,
163                    cam: cam(centre_hz),
164                    erb_hz: erb,
165                    q: centre_hz / erb,
166                    peak,
167                    time_to_peak_secs: at,
168                    rise_10_90_secs: rise,
169                    floor: floor_of(centre_hz, sr, hop, rate),
170                    rms: track,
171                }
172            })
173            .collect(),
174    }
175}