Skip to main content

qualia_audio/features/spectral/
frequency_bands.rs

1//! Sum spectral energy into arbitrary caller-supplied frequency bands.
2
3use crate::types::AudioError;
4
5/// Sum the energy of a one-sided magnitude spectrum `mag` into arbitrary
6/// frequency bands defined by ascending `band_edges_hz`.
7///
8/// `band_edges_hz` holds `B + 1` ascending edge frequencies (Hz) partitioning
9/// the spectrum into `B` bands. Band `b` covers `[edge[b], edge[b+1])`
10/// (half-open, so a bin lands in exactly one band). `out_energy[b]` receives
11/// `Σ |X[k]|^2` over the bins whose centre frequency falls in band `b`.
12///
13/// `mag` spans DC..Nyquist inclusive, so bin `k` sits at
14/// `k · sample_rate / (2·(N-1))` Hz for an `N`-bin spectrum.
15///
16/// Zero-heap: single pass, caller-supplied output.
17///
18/// # Errors
19/// - [`AudioError::InvalidParameter`] if `sample_rate` is not a positive finite,
20///   if `mag` has fewer than 2 bins, if there are fewer than 2 edges, or if the
21///   edges are not strictly ascending / not finite.
22/// - [`AudioError::OutputBufferTooSmall`] if `out_energy` is shorter than the
23///   number of bands.
24pub fn frequency_bands(
25    mag: &[f32],
26    sample_rate: f32,
27    band_edges_hz: &[f32],
28    out_energy: &mut [f32],
29) -> Result<usize, AudioError> {
30    if sample_rate <= 0.0 || !sample_rate.is_finite() {
31        return Err(AudioError::InvalidParameter);
32    }
33    if mag.len() < 2 || band_edges_hz.len() < 2 {
34        return Err(AudioError::InvalidParameter);
35    }
36    let bands = band_edges_hz.len() - 1;
37    if out_energy.len() < bands {
38        return Err(AudioError::OutputBufferTooSmall);
39    }
40    for w in band_edges_hz.windows(2) {
41        if !w[0].is_finite() || !w[1].is_finite() || w[0] >= w[1] {
42            return Err(AudioError::InvalidParameter);
43        }
44    }
45
46    for e in out_energy.iter_mut().take(bands) {
47        *e = 0.0;
48    }
49    let bin_hz = sample_rate as f64 / (2.0 * (mag.len() - 1) as f64);
50    for (k, m) in mag.iter().enumerate() {
51        let f = k as f64 * bin_hz;
52        // Locate the half-open band [edge[b], edge[b+1]) containing f.
53        for b in 0..bands {
54            if f >= band_edges_hz[b] as f64 && f < band_edges_hz[b + 1] as f64 {
55                out_energy[b] += (*m as f64 * *m as f64) as f32;
56                break;
57            }
58        }
59    }
60    Ok(bands)
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn partitions_energy_across_bands() {
69        let sr = 8000.0f32; // 9 bins, bin_hz = 500. Bins: 0,500,...,4000
70        let mut mag = [0.0f32; 9];
71        mag[1] = 2.0; // 500 Hz  -> band 0
72        mag[3] = 3.0; // 1500 Hz -> band 1
73        mag[7] = 1.0; // 3500 Hz -> band 2
74        let edges = [0.0f32, 1000.0, 2000.0, 4000.0];
75        let mut out = [0.0f32; 3];
76        let n = frequency_bands(&mag, sr, &edges, &mut out).expect("bands");
77        assert_eq!(n, 3);
78        assert!((out[0] - 4.0).abs() < 1e-4, "band0={}", out[0]); // 2^2
79        assert!((out[1] - 9.0).abs() < 1e-4, "band1={}", out[1]); // 3^2
80        assert!((out[2] - 1.0).abs() < 1e-4, "band2={}", out[2]); // 1^2, 4000 excluded (half-open)
81    }
82
83    #[test]
84    fn half_open_bins_land_once() {
85        let sr = 8000.0f32;
86        let mag = [1.0f32; 9]; // energy 1 at every bin
87                               // Two adjacent bands; the shared edge (1000 Hz) belongs to the upper band.
88        let edges = [0.0f32, 1000.0, 5000.0];
89        let mut out = [0.0f32; 2];
90        frequency_bands(&mag, sr, &edges, &mut out).expect("bands");
91        // Band 0: bins at 0,500 -> 2 bins. Band 1: 1000..4000 -> 7 bins.
92        assert!((out[0] - 2.0).abs() < 1e-4, "band0={}", out[0]);
93        assert!((out[1] - 7.0).abs() < 1e-4, "band1={}", out[1]);
94    }
95
96    #[test]
97    fn rejects_bad_edges() {
98        let mag = [1.0f32; 9];
99        let mut out = [0.0f32; 2];
100        assert_eq!(
101            frequency_bands(&mag, 8000.0, &[1000.0f32, 500.0], &mut out),
102            Err(AudioError::InvalidParameter)
103        );
104    }
105
106    #[test]
107    fn rejects_small_output() {
108        let mag = [1.0f32; 9];
109        let edges = [0.0f32, 1000.0, 2000.0];
110        let mut out = [0.0f32; 1];
111        assert_eq!(
112            frequency_bands(&mag, 8000.0, &edges, &mut out),
113            Err(AudioError::OutputBufferTooSmall)
114        );
115    }
116}