qualia_audio/features/envelope/
follower.rs1use crate::types::AudioError;
4
5pub 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 #[test]
88 fn tracks_monotonic_decay_of_decaying_sinusoid() {
89 let sr = 8000.0f32;
90 let f = 200.0f32;
91 let tau = 4000.0f32; 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 let mut env = vec![0.0f32; n];
101 envelope_follow(&x, 0.0, 0.9990, &mut env).expect("follow");
102
103 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 assert!(env[1000] > 0.0 && env[1000] <= 1.0);
117 }
118}