Skip to main content

qualia_audio/features/envelope/
tc_to_total.rs

1//! TCToTotal — temporal centroid of the envelope, normalised to length.
2
3use crate::types::AudioError;
4
5/// Temporal centroid of `envelope` (the amplitude-weighted mean index),
6/// normalised to `[0, 1)` by the total length. For a symmetric envelope the
7/// centroid sits at the middle (≈ 0.5); an early-weighted envelope returns a
8/// smaller value.
9///
10/// # Errors
11/// - [`AudioError::InvalidParameter`] if `envelope` is empty or its total
12///   (absolute) weight is zero.
13pub fn tc_to_total(envelope: &[f32]) -> Result<f32, AudioError> {
14    if envelope.is_empty() {
15        return Err(AudioError::InvalidParameter);
16    }
17    let mut weighted = 0.0f64;
18    let mut total = 0.0f64;
19    for (i, &v) in envelope.iter().enumerate() {
20        let w = v.abs() as f64;
21        weighted += i as f64 * w;
22        total += w;
23    }
24    if total == 0.0 {
25        return Err(AudioError::InvalidParameter);
26    }
27    let centroid = weighted / total;
28    Ok((centroid / envelope.len() as f64) as f32)
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn rejects_degenerate() {
37        assert_eq!(tc_to_total(&[]), Err(AudioError::InvalidParameter));
38        assert_eq!(
39            tc_to_total(&[0.0, 0.0, 0.0]),
40            Err(AudioError::InvalidParameter)
41        );
42    }
43
44    /// Golden: a symmetric triangular envelope has its centroid at ≈ 0.5.
45    #[test]
46    fn symmetric_centroid_is_middle() {
47        let len = 1001usize; // odd -> exact centre index
48        let mid = len / 2;
49        let mut env = vec![0.0f32; len];
50        for i in 0..len {
51            env[i] = 1.0 - (i as f32 - mid as f32).abs() / mid as f32;
52        }
53        let r = tc_to_total(&env).expect("tc");
54        // centroid index ≈ mid=500, /len=1001 -> ≈0.4995
55        assert!((r - 0.5).abs() < 0.01, "tc_to_total={r}");
56    }
57}