Skip to main content

qualia_audio/features/framing/
overlap_add.rs

1//! Overlap-add (OLA) reconstruction: sum a sequence of (already-windowed) frames
2//! back into a contiguous signal at a fixed hop.
3//!
4//! Zero-heap: the accumulation writes directly into a caller-owned `out` buffer.
5//! Frames are supplied pre-windowed and concatenated (`num_frames × frame_size`
6//! floats); no window is applied here — this is the pure add stage, so it works
7//! for any analysis/synthesis window the caller chose. With a COLA-satisfying
8//! window+hop (e.g. periodic Hann at hop = frame/2) the interior envelope is flat.
9
10use crate::types::AudioError;
11
12/// Overlap-add `frames` into `out` with stride `hop`.
13///
14/// - `frames`: `num_frames × frame_size` concatenated frame samples (row-major,
15///   frame `i` occupies `frames[i*frame_size .. (i+1)*frame_size]`). Already
16///   windowed by the caller if a window is desired.
17/// - `frame_size`: samples per frame (`> 0`); `frames.len()` must be a whole
18///   multiple of it.
19/// - `hop`: sample advance between consecutive frames (`> 0`).
20/// - `out`: receives the summed signal; must hold at least the returned length.
21///
22/// Returns the number of output samples written,
23/// `(num_frames − 1) × hop + frame_size`. The used region of `out` is zeroed
24/// before accumulation, so stale contents do not leak in.
25///
26/// Errors: [`AudioError::InvalidParameter`] for a zero `frame_size`/`hop` or a
27/// `frames` length that is not a multiple of `frame_size`;
28/// [`AudioError::OutputBufferTooSmall`] if `out` cannot hold the result.
29pub fn overlap_add(
30    frames: &[f32],
31    frame_size: usize,
32    hop: usize,
33    out: &mut [f32],
34) -> Result<usize, AudioError> {
35    if frame_size == 0 || hop == 0 || !frames.len().is_multiple_of(frame_size) {
36        return Err(AudioError::InvalidParameter);
37    }
38    let num_frames = frames.len() / frame_size;
39    if num_frames == 0 {
40        return Ok(0);
41    }
42    let out_len = (num_frames - 1)
43        .checked_mul(hop)
44        .and_then(|v| v.checked_add(frame_size))
45        .ok_or(AudioError::InvalidParameter)?;
46    if out.len() < out_len {
47        return Err(AudioError::OutputBufferTooSmall);
48    }
49
50    for v in out[..out_len].iter_mut() {
51        *v = 0.0;
52    }
53    for i in 0..num_frames {
54        let frame = &frames[i * frame_size..(i + 1) * frame_size];
55        let base = i * hop;
56        for (n, &s) in frame.iter().enumerate() {
57            out[base + n] += s;
58        }
59    }
60    Ok(out_len)
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::features::window::hann_window;
67
68    #[test]
69    fn single_frame_is_copied_verbatim() {
70        let frames = [1.0f32, 2.0, 3.0, 4.0];
71        let mut out = [0.0f32; 4];
72        let n = overlap_add(&frames, 4, 2, &mut out).unwrap();
73        assert_eq!(n, 4);
74        assert_eq!(out, [1.0, 2.0, 3.0, 4.0]);
75    }
76
77    #[test]
78    fn two_frames_sum_in_the_overlap() {
79        // frame_size 4, hop 2 → outputs overlap on indices 2,3.
80        let frames = [1.0f32, 1.0, 1.0, 1.0, /* f2 */ 2.0, 2.0, 2.0, 2.0];
81        let mut out = [0.0f32; 6];
82        let n = overlap_add(&frames, 4, 2, &mut out).unwrap();
83        assert_eq!(n, 6);
84        // idx0,1 = f1 only; idx2,3 = f1+f2; idx4,5 = f2 only.
85        assert_eq!(out, [1.0, 1.0, 3.0, 3.0, 2.0, 2.0]);
86    }
87
88    #[test]
89    fn hann_cola_constant_envelope() {
90        // GOLDEN COLA: overlap-adding periodic Hann frames at hop = N/2 gives a
91        // constant unity envelope in the steady-state interior.
92        let n = 256usize;
93        let hop = n / 2;
94        let frames_count = 12usize;
95        let mut w = vec![0.0f32; n];
96        hann_window(&mut w).unwrap();
97
98        let mut frames = vec![0.0f32; frames_count * n];
99        for i in 0..frames_count {
100            frames[i * n..(i + 1) * n].copy_from_slice(&w);
101        }
102        let out_len = (frames_count - 1) * hop + n;
103        let mut out = vec![0.0f32; out_len];
104        overlap_add(&frames, n, hop, &mut out).unwrap();
105
106        // Steady state: indices [n, out_len - n) see full 2-frame overlap.
107        for k in n..out_len - n {
108            assert!((out[k] - 1.0).abs() < 1e-5, "envelope at {k} = {}", out[k]);
109        }
110    }
111
112    #[test]
113    fn rejects_ragged_frame_length() {
114        let frames = [0.0f32; 10]; // not a multiple of 4
115        let mut out = [0.0f32; 32];
116        assert_eq!(
117            overlap_add(&frames, 4, 2, &mut out),
118            Err(AudioError::InvalidParameter)
119        );
120    }
121
122    #[test]
123    fn rejects_short_output() {
124        let frames = [0.0f32; 8]; // 2 frames of 4, hop 2 → needs 6
125        let mut out = [0.0f32; 5];
126        assert_eq!(
127            overlap_add(&frames, 4, 2, &mut out),
128            Err(AudioError::OutputBufferTooSmall)
129        );
130    }
131
132    #[test]
133    fn zero_frames_is_zero_length() {
134        let frames: [f32; 0] = [];
135        let mut out = [0.0f32; 4];
136        assert_eq!(overlap_add(&frames, 4, 2, &mut out), Ok(0));
137    }
138}