Skip to main content

qualia_audio/features/envelope/
log_attack_time.rs

1//! LogAttackTime — Essentia-style log10 of the attack duration.
2
3use crate::types::AudioError;
4
5/// Fraction of the envelope maximum at which the attack is considered to start.
6const START_THRESHOLD: f32 = 0.02;
7
8/// Log (base 10) of the attack time of an amplitude `envelope`.
9///
10/// The attack runs from the first sample whose value exceeds
11/// `START_THRESHOLD` × max up to the sample of maximum amplitude (the
12/// "stop"). The returned value is `log10(attack_seconds)`. Following Essentia,
13/// an effectively-zero attack is clamped to one sample so the log is finite.
14///
15/// # Errors
16/// - [`AudioError::InvalidParameter`] if `sample_rate <= 0`, the envelope is
17///   empty, or its maximum is not positive.
18pub fn log_attack_time(envelope: &[f32], sample_rate: f32) -> Result<f32, AudioError> {
19    if sample_rate <= 0.0 || !sample_rate.is_finite() || envelope.is_empty() {
20        return Err(AudioError::InvalidParameter);
21    }
22    let (max_idx, max_val) = arg_max(envelope);
23    if !max_val.is_finite() || max_val <= 0.0 {
24        return Err(AudioError::InvalidParameter);
25    }
26    let thresh = START_THRESHOLD * max_val;
27    let mut start_idx = 0usize;
28    for (i, &v) in envelope.iter().enumerate() {
29        if v >= thresh {
30            start_idx = i;
31            break;
32        }
33    }
34    // Attack spans at least one sample.
35    let span_samples = max_idx.saturating_sub(start_idx).max(1) as f32;
36    let attack_seconds = span_samples / sample_rate;
37    Ok(attack_seconds.log10())
38}
39
40#[inline]
41fn arg_max(env: &[f32]) -> (usize, f32) {
42    let mut idx = 0usize;
43    let mut best = f32::NEG_INFINITY;
44    for (i, &v) in env.iter().enumerate() {
45        if v > best {
46            best = v;
47            idx = i;
48        }
49    }
50    (idx, best)
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    fn build_attack_decay(sr: f32, attack_s: f32, total_s: f32) -> (Vec<f32>, usize) {
58        let attack_n = (attack_s * sr) as usize;
59        let total_n = (total_s * sr) as usize;
60        let mut env = vec![0.0f32; total_n];
61        // Linear attack 0 -> 1.
62        for i in 0..attack_n {
63            env[i] = (i + 1) as f32 / attack_n as f32;
64        }
65        let peak = attack_n - 1;
66        // Exponential decay after peak.
67        let tau = (0.2 * sr).max(1.0);
68        for i in attack_n..total_n {
69            env[i] = (-((i - peak) as f32) / tau).exp();
70        }
71        (env, peak)
72    }
73
74    #[test]
75    fn rejects_bad_input() {
76        assert_eq!(
77            log_attack_time(&[], 8000.0),
78            Err(AudioError::InvalidParameter)
79        );
80        assert_eq!(
81            log_attack_time(&[1.0, 2.0], 0.0),
82            Err(AudioError::InvalidParameter)
83        );
84        assert_eq!(
85            log_attack_time(&[0.0, 0.0], 8000.0),
86            Err(AudioError::InvalidParameter)
87        );
88    }
89
90    /// Golden: a 100 ms linear attack recovers ≈ log10(0.1) = -1.
91    #[test]
92    fn recovers_hundred_ms_attack() {
93        let sr = 10000.0f32;
94        let (env, _peak) = build_attack_decay(sr, 0.1, 1.0);
95        let lat = log_attack_time(&env, sr).expect("lat");
96        let expected = 0.1f32.log10(); // -1.0
97        assert!(
98            (lat - expected).abs() < 0.05,
99            "lat={lat} expected≈{expected}"
100        );
101    }
102}