qualia_audio/features/envelope/
derivative_sfx.rs1use crate::types::AudioError;
4
5pub fn derivative_sfx(envelope: &[f32]) -> Result<f32, AudioError> {
14 if envelope.len() < 2 {
15 return Err(AudioError::InvalidParameter);
16 }
17 let mut max_idx = 0usize;
19 let mut best = f32::NEG_INFINITY;
20 for (i, &v) in envelope.iter().enumerate() {
21 if v > best {
22 best = v;
23 max_idx = i;
24 }
25 }
26 if max_idx + 1 >= envelope.len() {
28 return Err(AudioError::InvalidParameter);
29 }
30 let tail = &envelope[max_idx..];
31 let mut sum = 0.0f64;
32 let mut count = 0u32;
33 for w in tail.windows(2) {
34 sum += (w[1] - w[0]) as f64;
35 count += 1;
36 }
37 if count == 0 {
38 return Err(AudioError::InvalidParameter);
39 }
40 Ok((sum / count as f64) as f32)
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn rejects_no_tail() {
49 assert_eq!(
51 derivative_sfx(&[0.0, 1.0, 2.0]),
52 Err(AudioError::InvalidParameter)
53 );
54 assert_eq!(derivative_sfx(&[1.0]), Err(AudioError::InvalidParameter));
55 }
56
57 #[test]
60 fn linear_decay_recovers_slope() {
61 let env = [0.0f32, 0.5, 1.0, 0.75, 0.5, 0.25, 0.0];
63 let d = derivative_sfx(&env).expect("d");
64 assert!((d - (-0.25)).abs() < 1e-6, "derivative={d}");
65 }
66}