Skip to main content

qualia_core_db/audio/
istft.rs

1//! Real inverse STFT — resynthesise a time-domain signal from the two-sided
2//! complex frames produced by [`crate::audio::stft::forward_stft`].
3//!
4//! This is the cold-path inverse companion to the forward STFT: it delegates to
5//! the caller-buffered WOLA resynthesiser in
6//! [`etalon_signal::audio::istft_overlap_add_into`] (weighted overlap-add normalised by
7//! the running Σ analysis·synthesis window product), so reconstruction is exact
8//! over the fully-overlapped interior regardless of whether the window+hop
9//! strictly satisfy COLA.
10//!
11//! Heap allocation is fine here: ISTFT runs at ingest / edit (cold path), never
12//! in the zero-heap U3 hot worklet.
13
14use crate::audio::stft_bake::StftBakeError;
15use etalon_signal::{
16    audio::{hann_window_sample, istft_overlap_add_into},
17    SignalError,
18};
19
20/// Hann window coefficient `w[i] = 0.5*(1 - cos(2π·i/(N-1)))` for a length-`n`
21/// frame — identical to [`crate::audio::stft`]'s analysis window, so the same
22/// window drives both the analysis and synthesis args of the WOLA resynthesis.
23#[inline]
24fn hann(i: usize, n: usize) -> f32 {
25    hann_window_sample(i, n)
26}
27
28/// Inverse STFT of the two-sided complex frames from
29/// [`crate::audio::stft::forward_stft`] back into a single time-domain signal.
30///
31/// - `spec`: `num_frames` frames, each a length-`frame_size` two-sided spectrum
32///   of \[re, im\] bins (exactly the [`crate::audio::stft::forward_stft`] output).
33/// - `frame_size`: `N`, a power of two; the analysis/synthesis frame length.
34/// - `hop`: sample advance between frames (`> 0`). A COLA Hann at `hop = N/2`
35///   gives exact interior reconstruction.
36///
37/// The frames are flattened into a `num_frames × 2·N` interleaved-complex buffer
38/// (`[re, im, …]`), a length-`N` Hann window is built for both the analysis and
39/// synthesis arguments, and the WOLA resynthesiser
40/// [`etalon_signal::audio::istft_overlap_add_into`] is invoked with caller-owned
41/// norm/out buffers (`out_len = (num_frames − 1)·hop + N`).
42///
43/// Returns the reconstructed samples (length `out_len`), or an empty `Vec` when
44/// `spec` is empty.
45#[cfg(not(target_arch = "wasm32"))]
46pub fn inverse_stft(
47    spec: &[Vec<[f32; 2]>],
48    frame_size: usize,
49    hop: usize,
50) -> Result<Vec<f32>, StftBakeError> {
51    if !frame_size.is_power_of_two() || frame_size == 0 || hop == 0 {
52        return Err(StftBakeError::InvalidFrameCount);
53    }
54    let num_frames = spec.len();
55    if num_frames == 0 {
56        return Ok(Vec::new());
57    }
58    // Every frame must be a full two-sided spectrum of `frame_size` bins.
59    for frame in spec {
60        if frame.len() != frame_size {
61            return Err(StftBakeError::InvalidFrameCount);
62        }
63    }
64
65    let two_n = 2 * frame_size;
66    // Flatten frames into `num_frames × 2N` interleaved complex `[re, im, …]`.
67    let mut spectra = vec![0.0_f32; num_frames * two_n];
68    for (f, frame) in spec.iter().enumerate() {
69        let seg = &mut spectra[f * two_n..(f + 1) * two_n];
70        for (k, &[re, im]) in frame.iter().enumerate() {
71            seg[2 * k] = re;
72            seg[2 * k + 1] = im;
73        }
74    }
75
76    // Length-N Hann for both analysis and synthesis window args.
77    let window: Vec<f32> = (0..frame_size).map(|i| hann(i, frame_size)).collect();
78
79    let out_len = (num_frames - 1)
80        .checked_mul(hop)
81        .and_then(|v| v.checked_add(frame_size))
82        .ok_or(StftBakeError::InvalidFrameCount)?;
83
84    let mut norm = vec![0.0_f32; out_len];
85    let mut out = vec![0.0_f32; out_len];
86
87    let written = istft_overlap_add_into(
88        &mut spectra,
89        frame_size,
90        hop,
91        &window,
92        &mut norm,
93        &mut out,
94    )
95    .map_err(map_signal_err)?;
96
97    out.truncate(written);
98    Ok(out)
99}
100
101#[cfg(not(target_arch = "wasm32"))]
102#[inline]
103fn map_signal_err(e: SignalError) -> StftBakeError {
104    match e {
105        SignalError::LengthMismatch => StftBakeError::OutputTooSmall,
106        _ => StftBakeError::InvalidFrameCount,
107    }
108}
109
110#[cfg(all(test, not(target_arch = "wasm32")))]
111mod tests {
112    use super::*;
113    use crate::audio::stft::forward_stft;
114    use core::f32::consts::TAU;
115
116    /// GOLDEN round trip: `forward_stft` → `inverse_stft` reconstructs the original
117    /// signal over the steady-state (fully-overlapped) interior with a COLA Hann at
118    /// hop = N/2 (mean-abs-error < 1e-2). Also proves no conjugate fix is needed.
119    #[test]
120    fn istft_round_trip_reconstructs_interior() {
121        const N: usize = 256;
122        const HOP: usize = N / 2; // COLA Hann
123        let fs = 16_000.0f32;
124        let len = 4096usize;
125        let signal: Vec<f32> = (0..len)
126            .map(|i| {
127                let t = i as f32 / fs;
128                0.6 * (TAU * 440.0 * t).sin() + 0.35 * (TAU * 1234.0 * t).cos()
129            })
130            .collect();
131
132        let spec = forward_stft(&signal, N, HOP).expect("forward stft");
133        let recon = inverse_stft(&spec, N, HOP).expect("inverse stft");
134
135        // Steady-state interior [N, out_len - N): every sample seen by full overlap.
136        let out_len = recon.len();
137        assert!(out_len >= 2 * N + 1, "not enough overlap for interior test");
138        let (lo, hi) = (N, out_len - N);
139        let mut mae = 0.0f64;
140        for k in lo..hi {
141            mae += (recon[k] - signal[k]).abs() as f64;
142        }
143        mae /= (hi - lo) as f64;
144        assert!(mae < 1e-2, "round-trip steady-state MAE {mae} exceeds 1e-2");
145    }
146
147    #[test]
148    fn istft_empty_spec_yields_empty() {
149        let empty: Vec<Vec<[f32; 2]>> = Vec::new();
150        let out = inverse_stft(&empty, 256, 128).expect("empty ok");
151        assert!(out.is_empty());
152    }
153
154    #[test]
155    fn istft_output_length_matches_formula() {
156        const N: usize = 64;
157        const HOP: usize = 32;
158        let signal = vec![0.2f32; N * 5];
159        let spec = forward_stft(&signal, N, HOP).expect("forward");
160        let num_frames = spec.len();
161        let recon = inverse_stft(&spec, N, HOP).expect("inverse");
162        assert_eq!(recon.len(), (num_frames - 1) * HOP + N);
163    }
164
165    #[test]
166    fn istft_rejects_non_power_of_two() {
167        let spec = vec![vec![[0.0f32; 2]; 48]];
168        assert_eq!(
169            inverse_stft(&spec, 48, 16),
170            Err(StftBakeError::InvalidFrameCount)
171        );
172    }
173
174    #[test]
175    fn istft_rejects_wrong_frame_width() {
176        // Frame length (10) disagrees with frame_size (256).
177        let spec = vec![vec![[0.0f32; 2]; 10]];
178        assert_eq!(
179            inverse_stft(&spec, 256, 128),
180            Err(StftBakeError::InvalidFrameCount)
181        );
182    }
183}