Skip to main content

qualia_audio/features/framing/
istft.rs

1//! Inverse STFT: resynthesise a time-domain signal from per-frame complex spectra
2//! via inverse FFT + weighted overlap-add (WOLA).
3//!
4//! Reuses [`crate::features::fft::ifft_to_real`] for the per-frame inverse.
5//! Reconstruction is normalised by the running sum of the analysis·synthesis
6//! window product, so the output is exact wherever frames overlap (the NOLA
7//! condition) regardless of whether the window+hop strictly satisfies COLA — the
8//! standard robust ISTFT. Zero-heap hot path: every buffer is caller-owned; the
9//! spectra are inverse-transformed in place.
10
11use crate::features::fft::ifft_to_real;
12use crate::types::AudioError;
13
14/// Inverse STFT of a run of complex spectra into a single time-domain signal.
15///
16/// - `spectra`: `num_frames × (2·fft_size)` interleaved-complex bins
17///   (`[re, im, …]`), frame `i` at `spectra[i*2N .. (i+1)*2N]`. **Clobbered** in
18///   place (each frame is inverse-transformed). `num_frames` is inferred as
19///   `spectra.len() / (2·fft_size)`.
20/// - `fft_size`: `N`, a power of two; equals the analysis frame size.
21/// - `hop`: sample advance between frames (`> 0`).
22/// - `analysis_window` / `synthesis_window`: the length-`N` windows used in
23///   analysis and applied in synthesis. Their product forms the normalisation.
24/// - `ifft_scratch`: `≥ N` floats; per-frame real inverse output (clobbered).
25/// - `norm`: `≥ out_len` floats; accumulates `Σ w_a·w_s` (clobbered).
26/// - `out`: `≥ out_len` floats; receives the reconstructed signal, where
27///   `out_len = (num_frames − 1)·hop + N`.
28///
29/// Returns the number of output samples written (`out_len`).
30///
31/// Errors: [`AudioError::InvalidParameter`] for a non-power-of-two/zero
32/// `fft_size`, zero `hop`, wrong window lengths, or a `spectra` length that is
33/// not a multiple of `2·fft_size`; [`AudioError::OutputBufferTooSmall`] if
34/// `ifft_scratch`, `norm`, or `out` are too short.
35#[allow(clippy::too_many_arguments)]
36pub fn istft(
37    spectra: &mut [f32],
38    fft_size: usize,
39    hop: usize,
40    analysis_window: &[f32],
41    synthesis_window: &[f32],
42    ifft_scratch: &mut [f32],
43    norm: &mut [f32],
44    out: &mut [f32],
45) -> Result<usize, AudioError> {
46    let n = fft_size;
47    if n == 0 || !n.is_power_of_two() || hop == 0 {
48        return Err(AudioError::InvalidParameter);
49    }
50    if analysis_window.len() != n || synthesis_window.len() != n {
51        return Err(AudioError::InvalidParameter);
52    }
53    let two_n = 2 * n;
54    if !spectra.len().is_multiple_of(two_n) {
55        return Err(AudioError::InvalidParameter);
56    }
57    let num_frames = spectra.len() / two_n;
58    if num_frames == 0 {
59        return Ok(0);
60    }
61    let out_len = (num_frames - 1)
62        .checked_mul(hop)
63        .and_then(|v| v.checked_add(n))
64        .ok_or(AudioError::InvalidParameter)?;
65    if ifft_scratch.len() < n || norm.len() < out_len || out.len() < out_len {
66        return Err(AudioError::OutputBufferTooSmall);
67    }
68
69    for v in out[..out_len].iter_mut() {
70        *v = 0.0;
71    }
72    for v in norm[..out_len].iter_mut() {
73        *v = 0.0;
74    }
75
76    for i in 0..num_frames {
77        let frame_spec = &mut spectra[i * two_n..(i + 1) * two_n];
78        ifft_to_real(frame_spec, &mut ifft_scratch[..n])?;
79        let base = i * hop;
80        for j in 0..n {
81            let wa = analysis_window[j];
82            let ws = synthesis_window[j];
83            out[base + j] += ws * ifft_scratch[j];
84            norm[base + j] += wa * ws;
85        }
86    }
87
88    // Normalise by the window-overlap envelope (WOLA). Below the epsilon the
89    // envelope carries no energy, so the output stays zero rather than dividing.
90    const EPS: f32 = 1e-8;
91    for k in 0..out_len {
92        if norm[k].abs() > EPS {
93            out[k] /= norm[k];
94        }
95    }
96    Ok(out_len)
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::features::fft::fft_radix2;
103    use crate::features::framing::frame_cutter::{cut_frame, frame_count};
104    use crate::features::window::{apply_window, hann_window};
105    use core::f32::consts::TAU;
106
107    /// Forward analysis: window each frame and FFT it into an interleaved-complex
108    /// spectra buffer (`num_frames × 2N`). Test-only helper (may allocate).
109    fn analyse(signal: &[f32], n: usize, hop: usize, window: &[f32]) -> (Vec<f32>, usize) {
110        let frames = frame_count(signal.len(), n, hop);
111        let two_n = 2 * n;
112        let mut spectra = vec![0.0f32; frames * two_n];
113        let mut frame = vec![0.0f32; n];
114        for i in 0..frames {
115            cut_frame(signal, n, hop, i, &mut frame).unwrap();
116            apply_window(&mut frame, window).unwrap();
117            let seg = &mut spectra[i * two_n..(i + 1) * two_n];
118            for j in 0..n {
119                seg[2 * j] = frame[j];
120                seg[2 * j + 1] = 0.0;
121            }
122            fft_radix2(seg, false).unwrap();
123        }
124        (spectra, frames)
125    }
126
127    #[test]
128    fn stft_then_istft_reconstructs_signal() {
129        // GOLDEN identity: analyse then synthesise a two-tone signal and recover
130        // it within a tight tolerance over the steady-state (fully overlapped)
131        // interior, using a COLA window+hop (periodic Hann, hop = N/2).
132        let n = 512usize;
133        let hop = n / 2;
134        let len = 8192usize;
135        let fs = 16_000.0f32;
136        let signal: Vec<f32> = (0..len)
137            .map(|i| {
138                let t = i as f32 / fs;
139                0.6 * (TAU * 440.0 * t).sin() + 0.4 * (TAU * 1015.0 * t).sin()
140            })
141            .collect();
142
143        let mut window = vec![0.0f32; n];
144        hann_window(&mut window).unwrap();
145
146        let (mut spectra, frames) = analyse(&signal, n, hop, &window);
147        let out_len = (frames - 1) * hop + n;
148        let mut ifft_scratch = vec![0.0f32; n];
149        let mut norm = vec![0.0f32; out_len];
150        let mut out = vec![0.0f32; out_len];
151        istft(
152            &mut spectra,
153            n,
154            hop,
155            &window,
156            &window,
157            &mut ifft_scratch,
158            &mut norm,
159            &mut out,
160        )
161        .unwrap();
162
163        // Steady-state region [n, out_len - n): every sample seen by full overlap.
164        let (lo, hi) = (n, out_len - n);
165        let mut mae = 0.0f64;
166        for k in lo..hi {
167            mae += (out[k] - signal[k]).abs() as f64;
168        }
169        mae /= (hi - lo) as f64;
170        assert!(mae < 1e-3, "steady-state MAE {mae} exceeds 1e-3");
171    }
172
173    #[test]
174    fn rejects_non_power_of_two_fft() {
175        let mut spectra = vec![0.0f32; 2 * 6];
176        let w = vec![0.0f32; 6];
177        let mut sc = vec![0.0f32; 6];
178        let mut nm = vec![0.0f32; 6];
179        let mut out = vec![0.0f32; 6];
180        assert_eq!(
181            istft(&mut spectra, 6, 3, &w, &w, &mut sc, &mut nm, &mut out),
182            Err(AudioError::InvalidParameter)
183        );
184    }
185
186    #[test]
187    fn rejects_wrong_window_length() {
188        let n = 8usize;
189        let mut spectra = vec![0.0f32; 2 * n];
190        let w = vec![0.0f32; n - 1];
191        let mut sc = vec![0.0f32; n];
192        let mut nm = vec![0.0f32; n];
193        let mut out = vec![0.0f32; n];
194        assert_eq!(
195            istft(&mut spectra, n, 4, &w, &w, &mut sc, &mut nm, &mut out),
196            Err(AudioError::InvalidParameter)
197        );
198    }
199
200    #[test]
201    fn rejects_short_output() {
202        let n = 8usize;
203        let mut spectra = vec![0.0f32; 2 * 2 * n]; // 2 frames
204        let w = vec![0.0f32; n];
205        let mut sc = vec![0.0f32; n];
206        let mut nm = vec![0.0f32; 100];
207        let mut out = vec![0.0f32; 4]; // far too short
208        assert_eq!(
209            istft(&mut spectra, n, 4, &w, &w, &mut sc, &mut nm, &mut out),
210            Err(AudioError::OutputBufferTooSmall)
211        );
212    }
213}