Skip to main content

qualia_audio/features/envelope/
max_to_total.rs

1//! MaxToTotal — position of the envelope maximum, normalised to length.
2
3use crate::types::AudioError;
4
5/// Position of the maximum of `envelope`, normalised to `[0, 1)` by the total
6/// length (`argmax / len`). A value near 0 indicates an early peak (percussive
7/// onset); near 1, a late peak.
8///
9/// # Errors
10/// - [`AudioError::InvalidParameter`] if `envelope` is empty.
11pub fn max_to_total(envelope: &[f32]) -> Result<f32, AudioError> {
12    if envelope.is_empty() {
13        return Err(AudioError::InvalidParameter);
14    }
15    let mut idx = 0usize;
16    let mut best = f32::NEG_INFINITY;
17    for (i, &v) in envelope.iter().enumerate() {
18        if v > best {
19            best = v;
20            idx = i;
21        }
22    }
23    Ok(idx as f32 / envelope.len() as f32)
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn rejects_empty() {
32        assert_eq!(max_to_total(&[]), Err(AudioError::InvalidParameter));
33    }
34
35    /// Golden: a signal peaking at a known fraction returns that fraction.
36    #[test]
37    fn recovers_peak_fraction() {
38        let len = 5000usize;
39        let peak = 1000usize; // fraction 0.2
40        let mut env = vec![0.0f32; len];
41        for i in 0..len {
42            // Rise to peak at `peak`, then fall — unique maximum at `peak`.
43            env[i] = if i <= peak {
44                i as f32 / peak as f32
45            } else {
46                (len - i) as f32 / (len - peak) as f32
47            };
48        }
49        let r = max_to_total(&env).expect("mtt");
50        assert!((r - 0.2).abs() < 1e-3, "max_to_total={r}");
51    }
52}