Skip to main content

qualia_audio/features/spectral/
contrast.rs

1//! Spectral contrast — peak-vs-valley level (dB) per sub-band.
2
3use crate::types::AudioError;
4
5/// Spectral contrast per sub-band of a one-sided magnitude spectrum `mag`.
6///
7/// `band_edges` is an ascending list of bin indices partitioning the spectrum
8/// into `band_edges.len() - 1` sub-bands `[edge[b], edge[b+1])`. For each band
9/// the contrast is the level difference between the band's spectral peak
10/// (maximum magnitude) and its valley (minimum magnitude), expressed in dB:
11///
12/// ```text
13/// contrast_dB[b] = 20·log10(peak_b) - 20·log10(valley_b)
14/// ```
15///
16/// A flat band gives ~`0 dB`; a band with a sharp peak over a quiet floor gives
17/// a large positive dB. Magnitudes are floored to a tiny epsilon so an all-zero
18/// band yields `0 dB` rather than a `NaN`. Results are written into
19/// `out_contrast` (one per band).
20///
21/// Zero-heap: single pass per band, caller-supplied output.
22///
23/// # Errors
24/// - [`AudioError::InvalidParameter`] if there are fewer than 2 edges, if the
25///   edges are not strictly ascending, or if any edge exceeds `mag.len()`.
26/// - [`AudioError::OutputBufferTooSmall`] if `out_contrast` is shorter than the
27///   number of bands.
28pub fn spectral_contrast(
29    mag: &[f32],
30    band_edges: &[usize],
31    out_contrast: &mut [f32],
32) -> Result<usize, AudioError> {
33    if band_edges.len() < 2 {
34        return Err(AudioError::InvalidParameter);
35    }
36    let bands = band_edges.len() - 1;
37    if out_contrast.len() < bands {
38        return Err(AudioError::OutputBufferTooSmall);
39    }
40    // Validate strictly ascending edges within bounds.
41    for w in band_edges.windows(2) {
42        if w[0] >= w[1] || w[1] > mag.len() {
43            return Err(AudioError::InvalidParameter);
44        }
45    }
46
47    const EPS: f32 = 1e-10;
48    for b in 0..bands {
49        let lo = band_edges[b];
50        let hi = band_edges[b + 1];
51        let mut peak = f32::MIN;
52        let mut valley = f32::MAX;
53        for &m in &mag[lo..hi] {
54            let v = m.abs();
55            if v > peak {
56                peak = v;
57            }
58            if v < valley {
59                valley = v;
60            }
61        }
62        let peak_db = 20.0 * peak.max(EPS).log10();
63        let valley_db = 20.0 * valley.max(EPS).log10();
64        out_contrast[b] = peak_db - valley_db;
65    }
66    Ok(bands)
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn flat_band_near_zero_contrast() {
75        let mag = [1.0f32; 8];
76        let edges = [0usize, 8];
77        let mut out = [0.0f32; 1];
78        let n = spectral_contrast(&mag, &edges, &mut out).expect("contrast");
79        assert_eq!(n, 1);
80        assert!(out[0].abs() < 1e-3, "contrast={}", out[0]);
81    }
82
83    #[test]
84    fn peaky_band_large_contrast() {
85        // Peak 1.0 over a 0.01 floor -> 20*log10(100) = 40 dB.
86        let mag = [0.01f32, 0.01, 1.0, 0.01, 0.01, 0.01, 0.01, 0.01];
87        let edges = [0usize, 8];
88        let mut out = [0.0f32; 1];
89        spectral_contrast(&mag, &edges, &mut out).expect("contrast");
90        assert!((out[0] - 40.0).abs() < 0.5, "contrast={}", out[0]);
91    }
92
93    #[test]
94    fn multiple_bands_independently() {
95        // Band 0 flat, band 1 peaky.
96        let mag = [1.0f32, 1.0, 1.0, 1.0, 0.01, 1.0, 0.01, 0.01];
97        let edges = [0usize, 4, 8];
98        let mut out = [0.0f32; 2];
99        let n = spectral_contrast(&mag, &edges, &mut out).expect("contrast");
100        assert_eq!(n, 2);
101        assert!(out[0].abs() < 1e-3, "band0={}", out[0]);
102        assert!(out[1] > 30.0, "band1={}", out[1]);
103    }
104
105    #[test]
106    fn rejects_bad_edges() {
107        let mag = [1.0f32; 8];
108        let mut out = [0.0f32; 2];
109        // Not ascending.
110        assert_eq!(
111            spectral_contrast(&mag, &[4usize, 2], &mut out),
112            Err(AudioError::InvalidParameter)
113        );
114        // Out of bounds.
115        assert_eq!(
116            spectral_contrast(&mag, &[0usize, 9], &mut out),
117            Err(AudioError::InvalidParameter)
118        );
119        // Too few edges.
120        assert_eq!(
121            spectral_contrast(&mag, &[0usize], &mut out),
122            Err(AudioError::InvalidParameter)
123        );
124    }
125
126    #[test]
127    fn rejects_small_output() {
128        let mag = [1.0f32; 8];
129        let edges = [0usize, 4, 8];
130        let mut out = [0.0f32; 1];
131        assert_eq!(
132            spectral_contrast(&mag, &edges, &mut out),
133            Err(AudioError::OutputBufferTooSmall)
134        );
135    }
136}