Skip to main content

qualia_audio/features/envelope/
flatness_sfx.rs

1//! FlatnessSFX — flatness of the envelope (geometric / arithmetic mean).
2
3use crate::types::AudioError;
4
5/// FlatnessSFX of an amplitude `envelope`: the ratio of its geometric mean to
6/// its arithmetic mean, computed over the rectified (absolute) values. The
7/// result lies in `[0, 1]`: a perfectly flat envelope returns ≈ 1, while a
8/// spiky, impulsive envelope returns a value near 0.
9///
10/// A tiny floor is added before the log to keep the geometric mean finite for
11/// envelopes that contain exact zeros.
12///
13/// # Errors
14/// - [`AudioError::InvalidParameter`] if the envelope is empty or its
15///   arithmetic mean is zero.
16pub fn flatness_sfx(envelope: &[f32]) -> Result<f32, AudioError> {
17    if envelope.is_empty() {
18        return Err(AudioError::InvalidParameter);
19    }
20    const FLOOR: f64 = 1e-12;
21    let n = envelope.len() as f64;
22    let mut sum = 0.0f64;
23    let mut log_sum = 0.0f64;
24    for &v in envelope {
25        let a = v.abs() as f64 + FLOOR;
26        sum += a;
27        log_sum += a.ln();
28    }
29    let arithmetic = sum / n;
30    if arithmetic <= 0.0 {
31        return Err(AudioError::InvalidParameter);
32    }
33    let geometric = (log_sum / n).exp();
34    Ok((geometric / arithmetic).clamp(0.0, 1.0) as f32)
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn rejects_empty() {
43        assert_eq!(flatness_sfx(&[]), Err(AudioError::InvalidParameter));
44    }
45
46    /// Golden: a constant (perfectly flat) envelope has flatness ≈ 1.
47    #[test]
48    fn flat_envelope_is_one() {
49        let env = vec![0.7f32; 256];
50        let f = flatness_sfx(&env).expect("f");
51        assert!((f - 1.0).abs() < 1e-4, "flatness={f}");
52    }
53
54    /// A single spike among near-zeros is far from flat (≈ 0).
55    #[test]
56    fn spiky_envelope_is_small() {
57        let mut env = vec![0.0f32; 256];
58        env[10] = 1.0;
59        let f = flatness_sfx(&env).expect("f");
60        assert!(f < 0.01, "flatness={f} should be near 0");
61    }
62
63    /// Flatness is bounded and a flat signal exceeds a spiky one.
64    #[test]
65    fn flat_exceeds_spiky() {
66        let flat = vec![0.5f32; 128];
67        let mut spiky = vec![0.01f32; 128];
68        spiky[0] = 5.0;
69        let ff = flatness_sfx(&flat).expect("ff");
70        let fs = flatness_sfx(&spiky).expect("fs");
71        assert!(ff > fs);
72        assert!((0.0..=1.0).contains(&ff) && (0.0..=1.0).contains(&fs));
73    }
74}