Skip to main content

qualia_audio/features/envelope/
follower.rs

1//! Asymmetric one-pole envelope follower (fast attack / slow release).
2
3use crate::types::AudioError;
4
5/// Track the amplitude envelope of `x` with an asymmetric one-pole filter.
6///
7/// `attack` and `release` are the smoothing **coefficients** in `[0, 1)` applied
8/// when the rectified input is, respectively, rising above or falling below the
9/// current envelope value. Small coefficient = fast response, large = slow.
10/// A "fast attack / slow release" follower uses a small `attack` and a large
11/// `release`. The per-sample recursion is:
12///
13/// ```text
14/// r = |x[n]|
15/// coeff = if r > env { attack } else { release }
16/// env = coeff * env + (1 - coeff) * r
17/// out[n] = env
18/// ```
19///
20/// Zero-heap: writes into caller-provided `out` (must be at least `x.len()`).
21///
22/// # Errors
23/// - [`AudioError::InvalidParameter`] if `attack`/`release` are non-finite or
24///   outside `[0, 1)`.
25/// - [`AudioError::OutputBufferTooSmall`] if `out.len() < x.len()`.
26pub fn envelope_follow(
27    x: &[f32],
28    attack: f32,
29    release: f32,
30    out: &mut [f32],
31) -> Result<(), AudioError> {
32    if !is_valid_coeff(attack) || !is_valid_coeff(release) {
33        return Err(AudioError::InvalidParameter);
34    }
35    if out.len() < x.len() {
36        return Err(AudioError::OutputBufferTooSmall);
37    }
38    let mut env = 0.0f32;
39    for (i, &sample) in x.iter().enumerate() {
40        let r = sample.abs();
41        let coeff = if r > env { attack } else { release };
42        env = coeff * env + (1.0 - coeff) * r;
43        out[i] = env;
44    }
45    Ok(())
46}
47
48#[inline]
49fn is_valid_coeff(c: f32) -> bool {
50    c.is_finite() && (0.0..1.0).contains(&c)
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn rejects_bad_coeffs() {
59        let x = [0.0f32; 4];
60        let mut out = [0.0f32; 4];
61        assert_eq!(
62            envelope_follow(&x, 1.0, 0.5, &mut out),
63            Err(AudioError::InvalidParameter)
64        );
65        assert_eq!(
66            envelope_follow(&x, -0.1, 0.5, &mut out),
67            Err(AudioError::InvalidParameter)
68        );
69        assert_eq!(
70            envelope_follow(&x, 0.5, f32::NAN, &mut out),
71            Err(AudioError::InvalidParameter)
72        );
73    }
74
75    #[test]
76    fn rejects_small_out() {
77        let x = [0.0f32; 8];
78        let mut out = [0.0f32; 4];
79        assert_eq!(
80            envelope_follow(&x, 0.0, 0.9, &mut out),
81            Err(AudioError::OutputBufferTooSmall)
82        );
83    }
84
85    /// Golden: on a decaying sinusoid the follower yields an envelope that is
86    /// monotonically decreasing at coarse scale after the (instant) attack.
87    #[test]
88    fn tracks_monotonic_decay_of_decaying_sinusoid() {
89        let sr = 8000.0f32;
90        let f = 200.0f32;
91        let tau = 4000.0f32; // decay time constant in samples (0.5 s)
92        let n = 8000usize;
93        let mut x = vec![0.0f32; n];
94        for (i, s) in x.iter_mut().enumerate() {
95            let t = i as f32;
96            let a = (-t / tau).exp();
97            *s = a * (2.0 * std::f32::consts::PI * f * t / sr).sin();
98        }
99        // Fast attack (instant), slow release.
100        let mut env = vec![0.0f32; n];
101        envelope_follow(&x, 0.0, 0.9990, &mut env).expect("follow");
102
103        // Sample the upper envelope well past the attack transient.
104        let probes = [1000usize, 2500, 4000, 5500, 7000];
105        for w in probes.windows(2) {
106            assert!(
107                env[w[0]] > env[w[1]],
108                "envelope not decreasing: env[{}]={} !> env[{}]={}",
109                w[0],
110                env[w[0]],
111                w[1],
112                env[w[1]]
113            );
114        }
115        // Envelope stays positive and never exceeds the input peak (~1.0).
116        assert!(env[1000] > 0.0 && env[1000] <= 1.0);
117    }
118}