Skip to main content

qualia_audio/features/spectral/
rolloff.rs

1//! Spectral rolloff frequency of a magnitude spectrum.
2
3use crate::types::AudioError;
4
5/// Spectral rolloff frequency of a one-sided magnitude spectrum `mag`.
6///
7/// The rolloff is the frequency below which a fraction `threshold` (e.g. `0.85`)
8/// of the total spectral energy `Σ |X[k]|^2` is contained. The returned value
9/// is the centre frequency of the first bin at which the running cumulative
10/// energy reaches `threshold · total`.
11///
12/// `mag` spans DC..Nyquist inclusive (an `N`-bin spectrum came from an FFT of
13/// size `2·(N-1)`), so the bin spacing is `sample_rate / (2·(N-1))` Hz.
14///
15/// A spectrum whose energy sits low returns a low frequency; energy sitting
16/// high returns a high frequency. A silent spectrum returns `0.0` Hz.
17///
18/// Zero-heap: two passes, scalar result.
19///
20/// # Errors
21/// - [`AudioError::InvalidParameter`] if `sample_rate` is not a positive finite,
22///   if `threshold` is not in `(0, 1]`, or if `mag` has fewer than 2 bins.
23pub fn spectral_rolloff(mag: &[f32], sample_rate: f32, threshold: f32) -> Result<f32, AudioError> {
24    if sample_rate <= 0.0 || !sample_rate.is_finite() {
25        return Err(AudioError::InvalidParameter);
26    }
27    if !(threshold > 0.0 && threshold <= 1.0) {
28        return Err(AudioError::InvalidParameter);
29    }
30    if mag.len() < 2 {
31        return Err(AudioError::InvalidParameter);
32    }
33
34    let mut total = 0.0f64;
35    for m in mag {
36        total += (*m as f64) * (*m as f64);
37    }
38    if total == 0.0 {
39        return Ok(0.0);
40    }
41
42    let bin_hz = sample_rate as f64 / (2.0 * (mag.len() - 1) as f64);
43    let target = threshold as f64 * total;
44    let mut cum = 0.0f64;
45    for (k, m) in mag.iter().enumerate() {
46        cum += (*m as f64) * (*m as f64);
47        if cum >= target {
48            return Ok((k as f64 * bin_hz) as f32);
49        }
50    }
51    // Numerical fall-through: all energy accounted for at the last bin.
52    Ok(((mag.len() - 1) as f64 * bin_hz) as f32)
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn low_energy_low_rolloff_high_energy_high_rolloff() {
61        let sr = 44_100.0f32;
62        let n = 513usize; // fft 1024, bin_hz = 44100/1024 ~= 43.07 Hz
63        let bin_hz = sr / 1024.0;
64
65        // Energy concentrated in the low bins.
66        let mut low = vec![0.0f32; n];
67        for m in low.iter_mut().take(10) {
68            *m = 1.0;
69        }
70        let r_low = spectral_rolloff(&low, sr, 0.85).expect("rolloff");
71
72        // Energy concentrated in the high bins.
73        let mut high = vec![0.0f32; n];
74        for m in high.iter_mut().skip(n - 10) {
75            *m = 1.0;
76        }
77        let r_high = spectral_rolloff(&high, sr, 0.85).expect("rolloff");
78
79        assert!(r_low < r_high, "low={r_low} high={r_high}");
80        // Low spectrum rolls off within its first ~10 bins.
81        assert!(r_low <= 10.0 * bin_hz, "r_low={r_low}");
82        // High spectrum rolls off up in the last decile of the band.
83        assert!(r_high > 400.0 * bin_hz, "r_high={r_high}");
84    }
85
86    #[test]
87    fn full_threshold_reaches_last_energetic_bin() {
88        let sr = 8000.0f32;
89        let mag = [0.0f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
90        let bin_hz = sr / (2.0 * 8.0); // 500 Hz
91                                       // threshold 1.0 -> must include the last non-zero bin (index 8).
92        let r = spectral_rolloff(&mag, sr, 1.0).expect("rolloff");
93        assert!((r - 8.0 * bin_hz).abs() < 1e-3, "r={r}");
94    }
95
96    #[test]
97    fn silent_spectrum_is_zero() {
98        let mag = [0.0f32; 8];
99        assert_eq!(spectral_rolloff(&mag, 8000.0, 0.85), Ok(0.0));
100    }
101
102    #[test]
103    fn rejects_bad_params() {
104        let mag = [0.0f32, 1.0, 0.0];
105        assert_eq!(
106            spectral_rolloff(&mag, 0.0, 0.85),
107            Err(AudioError::InvalidParameter)
108        );
109        assert_eq!(
110            spectral_rolloff(&mag, 8000.0, 0.0),
111            Err(AudioError::InvalidParameter)
112        );
113        assert_eq!(
114            spectral_rolloff(&mag, 8000.0, 1.5),
115            Err(AudioError::InvalidParameter)
116        );
117        assert_eq!(
118            spectral_rolloff(&[1.0], 8000.0, 0.85),
119            Err(AudioError::InvalidParameter)
120        );
121    }
122}