Skip to main content

qualia_audio/features/envelope/
strong_decay.rs

1//! StrongDecay — non-linear combination of energy and temporal centroid.
2
3use crate::types::AudioError;
4
5/// StrongDecay of an amplitude `envelope`.
6///
7/// Built from the non-linear combination of the envelope energy and its
8/// temporal centroid (in seconds): `sqrt(energy * centroid_seconds)`. A signal
9/// with both high energy and a centroid pushed later in time yields a larger
10/// value; the measure discriminates envelopes with a pronounced decay tail.
11///
12/// # Errors
13/// - [`AudioError::InvalidParameter`] if `sample_rate <= 0`, the envelope is
14///   empty, or its total weight is zero (undefined centroid).
15pub fn strong_decay(envelope: &[f32], sample_rate: f32) -> Result<f32, AudioError> {
16    if sample_rate <= 0.0 || !sample_rate.is_finite() || envelope.is_empty() {
17        return Err(AudioError::InvalidParameter);
18    }
19    let mut energy = 0.0f64;
20    let mut weighted = 0.0f64;
21    let mut total = 0.0f64;
22    for (i, &v) in envelope.iter().enumerate() {
23        let a = v.abs() as f64;
24        energy += a * a;
25        weighted += i as f64 * a;
26        total += a;
27    }
28    if total == 0.0 {
29        return Err(AudioError::InvalidParameter);
30    }
31    let centroid_seconds = (weighted / total) / sample_rate as f64;
32    Ok((energy * centroid_seconds).sqrt() as f32)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn rejects_degenerate() {
41        assert_eq!(
42            strong_decay(&[1.0, 2.0], 0.0),
43            Err(AudioError::InvalidParameter)
44        );
45        assert_eq!(strong_decay(&[], 8000.0), Err(AudioError::InvalidParameter));
46        assert_eq!(
47            strong_decay(&[0.0, 0.0], 8000.0),
48            Err(AudioError::InvalidParameter)
49        );
50    }
51
52    /// Golden: a rectangular envelope of unit amplitude has a known StrongDecay.
53    /// energy = N, centroid_seconds = ((N-1)/2)/sr; result = sqrt(N * that).
54    #[test]
55    fn rectangular_envelope_matches_closed_form() {
56        let sr = 1000.0f32;
57        let n = 100usize;
58        let env = vec![1.0f32; n];
59        let got = strong_decay(&env, sr).expect("sd");
60        let centroid_s = ((n - 1) as f64 / 2.0) / sr as f64;
61        let expected = ((n as f64) * centroid_s).sqrt() as f32;
62        assert!(
63            (got - expected).abs() < 1e-3,
64            "got={got} expected={expected}"
65        );
66    }
67
68    /// A later-decaying envelope has a larger StrongDecay than an early one
69    /// of equal energy.
70    #[test]
71    fn later_centroid_gives_larger_value() {
72        let sr = 1000.0f32;
73        let mut early = vec![0.0f32; 200];
74        let mut late = vec![0.0f32; 200];
75        for i in 0..50 {
76            early[i] = 1.0; // energy concentrated at the start
77            late[150 + i] = 1.0; // same energy, concentrated at the end
78        }
79        let se = strong_decay(&early, sr).expect("e");
80        let sl = strong_decay(&late, sr).expect("l");
81        assert!(sl > se, "late={sl} should exceed early={se}");
82    }
83}