Skip to main content

qualia_audio/features/spectral/
flatness_db.rs

1//! Spectral flatness (Wiener entropy) of a magnitude/power spectrum.
2
3use crate::types::AudioError;
4
5/// Spectral flatness of a one-sided spectrum `spectrum`.
6///
7/// Flatness is the ratio of the geometric mean to the arithmetic mean of the
8/// bin values:
9///
10/// ```text
11/// flatness = exp(mean(ln x_k)) / mean(x_k)
12/// ```
13///
14/// It lies in `[0, 1]`: a perfectly flat (white) spectrum gives `1.0`
15/// (`0 dB`), while a single-tone spectrum with most bins near zero gives a
16/// value near `0` (a large negative dB). When `as_db` is `true` the result is
17/// returned as `10·log10(flatness)` (floored so a degenerate ratio maps to a
18/// large negative dB rather than `-inf`).
19///
20/// Any non-positive bin drives the geometric mean to zero, so the linear
21/// flatness is `0.0` (or the dB floor) whenever a bin is `<= 0`.
22///
23/// Zero-heap: single pass, scalar result.
24///
25/// # Errors
26/// - [`AudioError::InvalidParameter`] if `spectrum` is empty.
27pub fn spectral_flatness_db(spectrum: &[f32], as_db: bool) -> Result<f32, AudioError> {
28    if spectrum.is_empty() {
29        return Err(AudioError::InvalidParameter);
30    }
31
32    // dB floor for a degenerate (zero geometric mean) ratio: 10*log10(1e-10).
33    const RATIO_FLOOR: f64 = 1e-10;
34
35    let n = spectrum.len() as f64;
36    let mut sum = 0.0f64;
37    let mut sum_ln = 0.0f64;
38    let mut any_nonpositive = false;
39    for &v in spectrum {
40        let x = v as f64;
41        sum += x;
42        if x > 0.0 {
43            sum_ln += x.ln();
44        } else {
45            any_nonpositive = true;
46        }
47    }
48
49    let ratio = if any_nonpositive || sum <= 0.0 {
50        0.0
51    } else {
52        let geo = (sum_ln / n).exp();
53        let arith = sum / n;
54        (geo / arith).clamp(0.0, 1.0)
55    };
56
57    if as_db {
58        Ok((10.0 * ratio.max(RATIO_FLOOR).log10()) as f32)
59    } else {
60        Ok(ratio as f32)
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn flat_spectrum_is_unity_and_zero_db() {
70        let spectrum = [1.0f32; 32];
71        let lin = spectral_flatness_db(&spectrum, false).expect("flatness");
72        assert!((lin - 1.0).abs() < 1e-5, "linear flatness={lin}");
73        let db = spectral_flatness_db(&spectrum, true).expect("flatness");
74        assert!(db.abs() < 1e-3, "dB flatness={db}");
75    }
76
77    #[test]
78    fn flat_at_any_level_is_unity() {
79        let spectrum = [7.5f32; 16];
80        let lin = spectral_flatness_db(&spectrum, false).expect("flatness");
81        assert!((lin - 1.0).abs() < 1e-5, "flatness={lin}");
82    }
83
84    #[test]
85    fn single_tone_is_low() {
86        // One dominant bin, the rest a small noise floor -> peaky -> low flatness.
87        let mut spectrum = [0.001f32; 64];
88        spectrum[10] = 10.0;
89        let lin = spectral_flatness_db(&spectrum, false).expect("flatness");
90        assert!(lin < 0.1, "tone flatness={lin}");
91        let db = spectral_flatness_db(&spectrum, true).expect("flatness");
92        assert!(db < -10.0, "tone flatness dB={db}");
93
94        // And it is strictly flatter for the white case.
95        let white = [1.0f32; 64];
96        let lin_white = spectral_flatness_db(&white, false).expect("flatness");
97        assert!(lin_white > lin, "white={lin_white} tone={lin}");
98    }
99
100    #[test]
101    fn zero_bin_drives_flatness_to_zero() {
102        let spectrum = [1.0f32, 1.0, 0.0, 1.0];
103        assert_eq!(spectral_flatness_db(&spectrum, false), Ok(0.0));
104    }
105
106    #[test]
107    fn rejects_empty() {
108        assert_eq!(
109            spectral_flatness_db(&[], false),
110            Err(AudioError::InvalidParameter)
111        );
112    }
113}