Skip to main content

qualia_audio/features/envelope/
derivative_sfx.rs

1//! DerivativeSFX — mean first difference of the envelope after its maximum.
2
3use crate::types::AudioError;
4
5/// DerivativeSFX: the mean of the first difference (`env[i+1] - env[i]`) of the
6/// `envelope` taken over the region **after** the maximum. It characterises the
7/// decay shape: a smooth, gentle decay yields a small negative value; a sharp
8/// drop yields a larger-magnitude negative value.
9///
10/// # Errors
11/// - [`AudioError::InvalidParameter`] if the envelope has fewer than two
12///   samples after the maximum (no derivative is defined).
13pub fn derivative_sfx(envelope: &[f32]) -> Result<f32, AudioError> {
14    if envelope.len() < 2 {
15        return Err(AudioError::InvalidParameter);
16    }
17    // Locate the maximum.
18    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    // Need at least two samples in the post-max tail to form one difference.
27    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        // Maximum is the last element -> no post-max derivative.
50        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    /// Golden: a linear decay of known slope returns that slope as the mean
58    /// derivative.
59    #[test]
60    fn linear_decay_recovers_slope() {
61        // Rise to a peak at index 2, then fall by exactly 0.25 per sample.
62        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}