Skip to main content

qualia_audio/features/peaks/
peak_detection.rs

1//! Generic local-maximum peak picker over a 1-D array.
2
3use crate::types::AudioError;
4
5/// Parabolic sub-sample offset of a peak located at the centre sample of the
6/// three ordinates `(ym1, y0, yp1)`. Returns a value in `(-0.5, 0.5)`; `0.0`
7/// when the three points are collinear (degenerate parabola).
8#[inline]
9fn parabolic_offset(ym1: f32, y0: f32, yp1: f32) -> f32 {
10    let denom = ym1 - 2.0 * y0 + yp1;
11    if denom == 0.0 || !denom.is_finite() {
12        return 0.0;
13    }
14    let d = 0.5 * (ym1 - yp1) / denom;
15    // A genuine local maximum yields |d| < 0.5; clamp defends against noise.
16    d.clamp(-0.5, 0.5)
17}
18
19/// Detect local-maximum peaks in `x`.
20///
21/// A sample `x[i]` (interior index `1..len-1`) is a candidate peak when it is
22/// strictly greater than its left neighbour, greater-or-equal to its right
23/// neighbour, and at least `threshold`. When two accepted peaks are closer than
24/// `min_distance` samples, the one with the **smaller** magnitude is discarded
25/// (greedy, cascading — the tallest survivor within any `min_distance` window
26/// is kept). Accepted peaks are written in ascending index order:
27/// `out_pos[k]` receives the parabolically-interpolated sub-sample position and
28/// `out_mag[k]` the peak sample magnitude.
29///
30/// Returns the number of peaks written.
31///
32/// Zero-heap: the output arrays double as the working stack; no allocation.
33///
34/// # Errors
35/// - [`AudioError::InvalidParameter`] if `threshold` is not finite.
36/// - [`AudioError::OutputBufferTooSmall`] if more peaks are found than the
37///   output arrays can hold (`min(out_pos.len(), out_mag.len())`).
38pub fn detect_peaks(
39    x: &[f32],
40    threshold: f32,
41    min_distance: usize,
42    out_pos: &mut [f32],
43    out_mag: &mut [f32],
44) -> Result<usize, AudioError> {
45    if !threshold.is_finite() {
46        return Err(AudioError::InvalidParameter);
47    }
48    let cap = out_pos.len().min(out_mag.len());
49    if x.len() < 3 || cap == 0 {
50        return Ok(0);
51    }
52
53    // Phase 1: forward scan. Store the integer index (as f32) so distance
54    // comparisons stay exact; parabolic interpolation is applied once at the end.
55    let mut count: usize = 0;
56    for i in 1..x.len() - 1 {
57        let v = x[i];
58        let is_peak = v > x[i - 1] && v >= x[i + 1] && v >= threshold;
59        if !is_peak {
60            continue;
61        }
62        // Cascading min-distance suppression against the accepted stack.
63        let mut rejected = false;
64        while count > 0 {
65            let last = out_pos[count - 1] as usize;
66            if i - last >= min_distance {
67                break;
68            }
69            if v > out_mag[count - 1] {
70                count -= 1; // pop the shorter neighbour, re-check the new top
71            } else {
72                rejected = true;
73                break;
74            }
75        }
76        if rejected {
77            continue;
78        }
79        if count == cap {
80            return Err(AudioError::OutputBufferTooSmall);
81        }
82        out_pos[count] = i as f32;
83        out_mag[count] = v;
84        count += 1;
85    }
86
87    // Phase 2: replace integer indices with interpolated sub-sample positions.
88    for k in 0..count {
89        let idx = out_pos[k] as usize;
90        let off = parabolic_offset(x[idx - 1], x[idx], x[idx + 1]);
91        out_pos[k] = idx as f32 + off;
92    }
93    Ok(count)
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    /// Golden: `[0,1,0,0,3,0,2,0]`, threshold 0.5 -> peaks at indices 1,4,6.
101    #[test]
102    fn golden_three_peaks() {
103        let x = [0.0f32, 1.0, 0.0, 0.0, 3.0, 0.0, 2.0, 0.0];
104        let mut pos = [0.0f32; 8];
105        let mut mag = [0.0f32; 8];
106        let n = detect_peaks(&x, 0.5, 1, &mut pos, &mut mag).expect("detect");
107        assert_eq!(n, 3);
108        // Symmetric neighbours -> zero parabolic offset -> exact integer positions.
109        assert!((pos[0] - 1.0).abs() < 1e-6, "pos0={}", pos[0]);
110        assert!((pos[1] - 4.0).abs() < 1e-6, "pos1={}", pos[1]);
111        assert!((pos[2] - 6.0).abs() < 1e-6, "pos2={}", pos[2]);
112        assert_eq!(mag[0], 1.0);
113        assert_eq!(mag[1], 3.0);
114        assert_eq!(mag[2], 2.0);
115    }
116
117    /// Threshold rejects the small peak at index 1.
118    #[test]
119    fn threshold_filters() {
120        let x = [0.0f32, 1.0, 0.0, 0.0, 3.0, 0.0, 2.0, 0.0];
121        let mut pos = [0.0f32; 8];
122        let mut mag = [0.0f32; 8];
123        let n = detect_peaks(&x, 1.5, 1, &mut pos, &mut mag).expect("detect");
124        assert_eq!(n, 2); // only 3.0 and 2.0 survive
125        assert_eq!(mag[0], 3.0);
126        assert_eq!(mag[1], 2.0);
127    }
128
129    /// min_distance suppresses the weaker of two close peaks.
130    /// Peaks at 1,4,6; gap(4,6)=2 < 3 -> the shorter (index 6, mag 2) is dropped.
131    #[test]
132    fn min_distance_suppresses_close() {
133        let x = [0.0f32, 1.0, 0.0, 0.0, 3.0, 0.0, 2.0, 0.0];
134        let mut pos = [0.0f32; 8];
135        let mut mag = [0.0f32; 8];
136        let n = detect_peaks(&x, 0.5, 3, &mut pos, &mut mag).expect("detect");
137        assert_eq!(n, 2);
138        assert!((pos[0] - 1.0).abs() < 1e-6);
139        assert!((pos[1] - 4.0).abs() < 1e-6);
140        assert_eq!(mag[1], 3.0);
141    }
142
143    /// Cascading: a tall central peak swallows shorter neighbours on both sides.
144    #[test]
145    fn cascading_keeps_tallest() {
146        // indices 1(=2),3(=5),5(=3) all within distance 2 of the tallest (idx 3)
147        let x = [0.0f32, 2.0, 0.0, 5.0, 0.0, 3.0, 0.0];
148        let mut pos = [0.0f32; 8];
149        let mut mag = [0.0f32; 8];
150        let n = detect_peaks(&x, 0.5, 3, &mut pos, &mut mag).expect("detect");
151        assert_eq!(n, 1);
152        assert!((pos[0] - 3.0).abs() < 1e-6);
153        assert_eq!(mag[0], 5.0);
154    }
155
156    /// Sub-sample interpolation: an asymmetric parabola peaks between bins.
157    #[test]
158    fn parabolic_interpolation() {
159        // Downward parabola with vertex at 4.3: vertex = i + 0.5*(ym1-yp1)/(ym1-2y0+yp1)
160        let center = 4.3f32;
161        let mut x = [0.0f32; 9];
162        for (i, xi) in x.iter_mut().enumerate() {
163            let v = 1.0 - 0.05 * (i as f32 - center) * (i as f32 - center);
164            *xi = v.max(0.0);
165        }
166        let mut pos = [0.0f32; 4];
167        let mut mag = [0.0f32; 4];
168        let n = detect_peaks(&x, 0.1, 1, &mut pos, &mut mag).expect("detect");
169        assert_eq!(n, 1);
170        assert!((pos[0] - 4.3).abs() < 1e-4, "pos={}", pos[0]);
171    }
172
173    #[test]
174    fn buffer_too_small_errors() {
175        let x = [0.0f32, 1.0, 0.0, 3.0, 0.0, 2.0, 0.0];
176        let mut pos = [0.0f32; 1];
177        let mut mag = [0.0f32; 1];
178        assert_eq!(
179            detect_peaks(&x, 0.5, 1, &mut pos, &mut mag),
180            Err(AudioError::OutputBufferTooSmall)
181        );
182    }
183
184    #[test]
185    fn rejects_nan_threshold() {
186        let x = [0.0f32, 1.0, 0.0];
187        let mut pos = [0.0f32; 2];
188        let mut mag = [0.0f32; 2];
189        assert_eq!(
190            detect_peaks(&x, f32::NAN, 1, &mut pos, &mut mag),
191            Err(AudioError::InvalidParameter)
192        );
193    }
194}