Skip to main content

qualia_audio/features/envelope/
min_to_total.rs

1//! MinToTotal — position of the envelope minimum, normalised to length.
2
3use crate::types::AudioError;
4
5/// Position of the minimum of `envelope`, normalised to `[0, 1)` by the total
6/// length (`argmin / len`).
7///
8/// # Errors
9/// - [`AudioError::InvalidParameter`] if `envelope` is empty.
10pub fn min_to_total(envelope: &[f32]) -> Result<f32, AudioError> {
11    if envelope.is_empty() {
12        return Err(AudioError::InvalidParameter);
13    }
14    let mut idx = 0usize;
15    let mut best = f32::INFINITY;
16    for (i, &v) in envelope.iter().enumerate() {
17        if v < best {
18            best = v;
19            idx = i;
20        }
21    }
22    Ok(idx as f32 / envelope.len() as f32)
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn rejects_empty() {
31        assert_eq!(min_to_total(&[]), Err(AudioError::InvalidParameter));
32    }
33
34    /// Golden: minimum at a known fraction is recovered.
35    #[test]
36    fn recovers_min_fraction() {
37        let len = 4000usize;
38        let trough = 3000usize; // fraction 0.75
39        let mut env = vec![1.0f32; len];
40        env[trough] = -0.5;
41        let r = min_to_total(&env).expect("mtt");
42        assert!((r - 0.75).abs() < 1e-3, "min_to_total={r}");
43    }
44}