Skip to main content

qualia_audio/features/fft/
inverse.rs

1//! ISTFT-friendly inverse helper: inverse FFT then extract the real part.
2//!
3//! Built on [`super::radix2::fft_radix2`]. Caller-buffered and zero-heap: the
4//! interleaved-complex spectrum is inverse-transformed in place, then the real
5//! components are copied into a caller-supplied real buffer.
6
7use crate::features::fft::radix2::fft_radix2;
8use crate::types::AudioError;
9
10/// Inverse FFT of an interleaved-complex spectrum, writing the real part of the
11/// time-domain result.
12///
13/// - `spectrum`: `2 * N` interleaved complex bins, `N` a power of two. Clobbered
14///   in place (holds the full complex inverse on return).
15/// - `out_real`: at least `N` floats; receives `Re(x[n])` for `n = 0..N`.
16///
17/// The inverse is `1/N`-normalised (via [`fft_radix2`]), so pairing this with a
18/// forward real FFT reconstructs the original samples — the ISTFT synthesis path.
19///
20/// Returns [`AudioError::InvalidParameter`] if the spectrum length is invalid,
21/// or [`AudioError::OutputBufferTooSmall`] if `out_real` is short.
22pub fn ifft_to_real(spectrum: &mut [f32], out_real: &mut [f32]) -> Result<(), AudioError> {
23    if spectrum.is_empty() || !spectrum.len().is_multiple_of(2) {
24        return Err(AudioError::InvalidParameter);
25    }
26    let n = spectrum.len() / 2;
27    if out_real.len() < n {
28        return Err(AudioError::OutputBufferTooSmall);
29    }
30    fft_radix2(spectrum, true)?;
31    for i in 0..n {
32        out_real[i] = spectrum[2 * i];
33    }
34    Ok(())
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use crate::features::fft::radix2::fft_radix2;
41    use core::f32::consts::TAU;
42
43    #[test]
44    fn forward_then_ifft_to_real_reconstructs() {
45        let n = 64usize;
46        let orig: Vec<f32> = (0..n)
47            .map(|i| (TAU * 3.0 * i as f32 / n as f32).cos() * 0.8)
48            .collect();
49        let mut spec = vec![0.0f32; 2 * n];
50        for i in 0..n {
51            spec[2 * i] = orig[i];
52        }
53        fft_radix2(&mut spec, false).unwrap();
54
55        let mut out = vec![0.0f32; n];
56        ifft_to_real(&mut spec, &mut out).unwrap();
57        for i in 0..n {
58            assert!(
59                (out[i] - orig[i]).abs() < 1e-4,
60                "sample {i}: {} vs {}",
61                out[i],
62                orig[i]
63            );
64        }
65    }
66
67    #[test]
68    fn rejects_short_output() {
69        let mut spec = vec![0.0f32; 2 * 8];
70        let mut out = vec![0.0f32; 4]; // needs 8
71        assert_eq!(
72            ifft_to_real(&mut spec, &mut out),
73            Err(AudioError::OutputBufferTooSmall)
74        );
75    }
76}