Skip to main content

tinymind/int8/
fft.rs

1//! Quantized radix-2 FFT (C++ `cpp/qfft1d.hpp`).
2
3/// Saturate an `i32` to `i16` (C++ `qfft_detail::saturateInt16`).
4#[inline(always)]
5pub(crate) fn saturate_i16(v: i32) -> i16 {
6    if v < i32::from(i16::MIN) {
7        i16::MIN
8    } else if v > i32::from(i16::MAX) {
9        i16::MAX
10    } else {
11        v as i16
12    }
13}
14
15/// Whether the forward transform checks once per butterfly that its two
16/// products fit in `i16`, and then skips the four saturations, which cannot
17/// change anything then. Both forms give the same results. On a Cortex-M0+
18/// the check pays (a 256-point transform took 91,430 cycles instead of
19/// 117,640 at opt-level 3): Thumb-1 has no saturating instruction, and each
20/// saturation loads its bounds from the literal pool. On a Cortex-M4 it costs
21/// (48,363 against 41,991), since `ssat` saturates in one instruction. Stable
22/// Rust names no instruction-set features in `cfg`, so this uses the closest
23/// available sign: ARMv6-M has no 32-bit atomic instructions, Armv7-M does.
24const SKIP_SATURATION: bool = cfg!(not(target_has_atomic = "32"));
25
26/// True when `v` is in the `i16` range: `v >> 15` is -1 or 0 exactly then.
27/// A shift and a compare with small immediates, no 32-bit constants.
28#[inline(always)]
29pub(crate) fn fits_i16(v: i32) -> bool {
30    ((v >> 15) + 1) as u32 <= 1
31}
32
33/// Q1.15 multiply, `(a * b) >> 15` in `i32` (C++ `qfft_detail::q15Mul`). The
34/// shift is arithmetic, so the result floors. With both operands from `i16`
35/// the product is at most `2^30` and cannot overflow.
36#[inline(always)]
37pub(crate) fn q15_mul(a: i32, b: i32) -> i32 {
38    (a * b) >> 15
39}
40
41/// A quantized radix-2 decimation-in-time FFT of length `N`, in place on `i16`
42/// real and imaginary buffers (C++ `QFFT1D<N>`).
43///
44/// For vibration, audio or IMU front ends on cores without a floating-point
45/// unit: butterflies are 16-bit with `i32` intermediates, twiddle factors are
46/// Q1.15 (scale `1/32768`). The layer only borrows its two twiddle tables, so
47/// they can live in flash as `static` or `const` data; the work buffers are
48/// the caller's, and the transform needs no other memory beyond a few
49/// registers.
50///
51/// `HALF` is `N / 2`, the length of each twiddle table: entry `k` holds
52/// `cos(-2πk/N)` and `sin(-2πk/N)` in Q1.15. Stable Rust cannot write `[i16;
53/// N / 2]` for a generic `N`, so the half length is a parameter of its own.
54/// `N` must be a power of two of at least 2 and `HALF` must be `N / 2`, or
55/// calling any method does not compile. `calibration::build_fft_twiddles`
56/// (`std` feature) computes the tables as tinymind (C++) does, so generate them
57/// on the host and embed them.
58///
59/// [`forward`](Self::forward) scales each of its `log2(N)` stages by 1/2, so
60/// the output is the discrete Fourier transform divided by `N` and the working
61/// values stay within 16 bits. [`inverse`](Self::inverse) does not scale, so
62/// it undoes `forward` up to rounding. Each butterfly saturates its results to
63/// `i16`.
64///
65/// ```
66/// use tinymind::int8::QFft1D;
67///
68/// // Twiddles for N = 8: cos and sin of -2πk/8 for k = 0..4, in Q1.15.
69/// static COS: [i16; 4] = [32767, 23170, 0, -23170];
70/// static SIN: [i16; 4] = [0, -23170, -32768, -23170];
71/// static FFT: QFft1D<'static, 8, 4> = QFft1D { twiddle_cos: &COS, twiddle_sin: &SIN };
72///
73/// // A cosine that completes one cycle over the eight samples.
74/// let mut real = [8000, 5657, 0, -5657, -8000, -5657, 0, 5657];
75/// let mut imag = [0; 8];
76/// FFT.forward(&mut real, &mut imag);
77/// // Scaled by 1/8, its energy lands in bins 1 and 7, each with half the
78/// // amplitude; each stage's halving floors, so a few values are off by one.
79/// assert_eq!(real, [-1, 3999, 0, 0, 0, 0, 0, 4000]);
80/// assert_eq!(imag, [0, -1, 0, 0, 0, 0, 0, 0]);
81/// let mut power = [0i32; 8];
82/// FFT.magnitude_squared(&real, &imag, &mut power);
83/// assert_eq!(power[7], 4000 * 4000);
84/// ```
85///
86/// A table of the wrong length does not compile:
87///
88/// ```compile_fail
89/// # use tinymind::int8::QFft1D;
90/// static COS: [i16; 8] = [0; 8];
91/// static SIN: [i16; 8] = [0; 8];
92/// let fft: QFft1D<'_, 8, 8> = QFft1D { twiddle_cos: &COS, twiddle_sin: &SIN };
93/// fft.forward(&mut [0; 8], &mut [0; 8]);
94/// ```
95#[derive(Clone, Copy, Debug)]
96pub struct QFft1D<'a, const N: usize, const HALF: usize> {
97    /// `twiddle_cos[k]` = `cos(-2πk/N)` in Q1.15.
98    pub twiddle_cos: &'a [i16; HALF],
99    /// `twiddle_sin[k]` = `sin(-2πk/N)` in Q1.15.
100    pub twiddle_sin: &'a [i16; HALF],
101}
102
103impl<const N: usize, const HALF: usize> QFft1D<'_, N, HALF> {
104    /// `log2(N)`, after checking `N` and `HALF` (the C++ `static_assert`s).
105    const STAGES: u32 = {
106        assert!(N >= 2, "FFT length must be at least 2");
107        assert!(N.is_power_of_two(), "FFT length must be a power of two");
108        assert!(HALF == N / 2, "HALF must be N / 2");
109        N.trailing_zeros()
110    };
111
112    /// Forward transform in place, scaled by `1/N`.
113    pub fn forward(&self, real: &mut [i16; N], imag: &mut [i16; N]) {
114        self.transform::<true, SKIP_SATURATION>(real, imag);
115    }
116
117    /// Inverse transform in place, unscaled, so it cancels the `1/N` of
118    /// [`forward`](Self::forward). Computed as the conjugate of the forward
119    /// transform of the conjugate; negating `-32768` wraps to `-32768`, as the
120    /// C++ cast does.
121    pub fn inverse(&self, real: &mut [i16; N], imag: &mut [i16; N]) {
122        for x in imag.iter_mut() {
123            *x = x.wrapping_neg();
124        }
125        self.transform::<false, SKIP_SATURATION>(real, imag);
126        for x in imag.iter_mut() {
127            *x = x.wrapping_neg();
128        }
129    }
130
131    /// Squared magnitude of each bin, `real^2 + imag^2`, in `i32`, into the
132    /// caller's `mag_sq` (C++ `magnitudeSquared`). The output is in the square
133    /// of the working scale;
134    /// a [`Requantizer`](super::Requantizer) can rescale it to an int8 grid.
135    /// The only sum that does not fit, `(-32768)^2 + (-32768)^2 = 2^31`,
136    /// saturates to `i32::MAX`.
137    pub fn magnitude_squared(&self, real: &[i16; N], imag: &[i16; N], mag_sq: &mut [i32; N]) {
138        let _ = Self::STAGES;
139        magnitude_squared(real, imag, mag_sq);
140    }
141
142    /// The radix-2 stages (C++ `forwardImpl`), with or without the per-stage
143    /// halving.
144    //
145    // Never inlined: with the stages inlined into it, it is large, and when
146    // LLVM inlined it into a caller anyway (once the stages became a free
147    // function shared with QRFft1D) a 256-point forward transform took
148    // 103,209 cycles on a Cortex-M0+ instead of 91,430, and 43,604 instead of
149    // 41,991 on a Cortex-M4, for 4 KB more code.
150    #[inline(never)]
151    pub(crate) fn transform<const SCALE: bool, const SKIP: bool>(
152        &self,
153        real: &mut [i16; N],
154        imag: &mut [i16; N],
155    ) {
156        // The checks on N and HALF (a post-monomorphization error if they fail).
157        let _ = Self::STAGES;
158        bit_reverse_permute(real, imag);
159        run_stages::<SCALE, SKIP, N, HALF, 1>(self.twiddle_cos, self.twiddle_sin, real, imag);
160    }
161}
162
163/// The radix-2 stages with half sizes `FIRST`, `2 * FIRST`, ... below `L` (the
164/// C++ stage loop), on buffers of `L` values with twiddle tables of `T`
165/// entries; stage `H` reads entry `pair * T / H`. [`QFft1D`] runs every stage
166/// (`L = N`, `T = N / 2`); [`QRFft1D`] runs those after its fused first stage
167/// on its `N / 2`-point inner transform with the `N`-point tables
168/// (`L = T = N / 2`), so it reads every second entry.
169///
170/// Each stage runs with its half size as a constant, so offsets, strides and
171/// trip counts are immediates and more registers stay free for the butterfly:
172/// on a Cortex-M0+ this took a 256-point forward transform from 153,698 cycles
173/// to 117,640 at opt-level 3, and from 157,939 to 135,233 at "s", for about
174/// 1.5 KB more code (before the saturation skip). Stages that a length does
175/// not have compile to nothing. The list reaches past any array that fits a
176/// 32-bit address space.
177#[inline(always)]
178fn run_stages<
179    const SCALE: bool,
180    const SKIP: bool,
181    const L: usize,
182    const T: usize,
183    const FIRST: usize,
184>(
185    cos: &[i16; T],
186    sin: &[i16; T],
187    real: &mut [i16; L],
188    imag: &mut [i16; L],
189) {
190    macro_rules! stages {
191        ($($h:literal)*) => {$(
192            if $h >= FIRST && $h < L {
193                stage::<SCALE, SKIP, L, T, $h>(cos, sin, real, imag);
194            }
195        )*};
196    }
197    stages!(
198        1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144
199        524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728
200        268435456 536870912 1073741824
201    );
202}
203
204/// One stage with half size `H` (C++ `halfSize`). The C++ runs group by group
205/// and loads the twiddle for every butterfly; the butterflies of a stage are
206/// independent, so this runs twiddle by twiddle instead, loading each pair
207/// once per stage. The results are the same. Every index is already in range;
208/// the masks only let the compiler see it, so no bounds check (and no panic)
209/// is emitted. `L` and `T` are powers of two.
210#[inline(always)]
211fn stage<const SCALE: bool, const SKIP: bool, const L: usize, const T: usize, const H: usize>(
212    cos: &[i16; T],
213    sin: &[i16; T],
214    real: &mut [i16; L],
215    imag: &mut [i16; L],
216) {
217    let mask = L - 1;
218    let tw_mask = T - 1;
219    let stride = T / H;
220    for pair in 0..H {
221        let k = (pair * stride) & tw_mask;
222        let w_cos = i32::from(cos[k]);
223        let w_sin = i32::from(sin[k]);
224        let mut top = pair;
225        while top < L {
226            butterfly::<SCALE, SKIP, L>(real, imag, top & mask, (top + H) & mask, w_cos, w_sin);
227            top += 2 * H;
228        }
229    }
230}
231
232/// One radix-2 butterfly on `top` and `bot` with the twiddle `(w_cos, w_sin)`
233/// (the body of the C++ `forwardImpl` loop).
234#[inline(always)]
235fn butterfly<const SCALE: bool, const SKIP: bool, const N: usize>(
236    real: &mut [i16; N],
237    imag: &mut [i16; N],
238    top: usize,
239    bot: usize,
240    w_cos: i32,
241    w_sin: i32,
242) {
243    let bot_real = i32::from(real[bot]);
244    let bot_imag = i32::from(imag[bot]);
245    let t_real = q15_mul(w_cos, bot_real) - q15_mul(w_sin, bot_imag);
246    let t_imag = q15_mul(w_cos, bot_imag) + q15_mul(w_sin, bot_real);
247
248    let top_real = i32::from(real[top]);
249    let top_imag = i32::from(imag[top]);
250    if SCALE {
251        // With both products in the i16 range, every halved sum is too:
252        // top + t lies in [-65536, 65534] and top - t in [-65535, 65535], so
253        // after `>> 1` all four fit and the saturation can be skipped (see
254        // SKIP_SATURATION). The products leave that range only near full
255        // scale.
256        if SKIP && fits_i16(t_real) && fits_i16(t_imag) {
257            real[top] = ((top_real + t_real) >> 1) as i16;
258            imag[top] = ((top_imag + t_imag) >> 1) as i16;
259            real[bot] = ((top_real - t_real) >> 1) as i16;
260            imag[bot] = ((top_imag - t_imag) >> 1) as i16;
261        } else {
262            real[top] = saturate_i16((top_real + t_real) >> 1);
263            imag[top] = saturate_i16((top_imag + t_imag) >> 1);
264            real[bot] = saturate_i16((top_real - t_real) >> 1);
265            imag[bot] = saturate_i16((top_imag - t_imag) >> 1);
266        }
267    } else {
268        real[top] = saturate_i16(top_real + t_real);
269        imag[top] = saturate_i16(top_imag + t_imag);
270        real[bot] = saturate_i16(top_real - t_real);
271        imag[bot] = saturate_i16(top_imag - t_imag);
272    }
273}
274
275/// Swap each index with its bit reversal (C++ `bitReversalPermute`). The C++
276/// reads the reversed index from an `N`-entry table; here `j` steps through
277/// the reversed sequence by adding 1 at its top bit and carrying downwards, so
278/// the permutation is the same without a table in flash or RAM.
279fn bit_reverse_permute<const N: usize>(real: &mut [i16; N], imag: &mut [i16; N]) {
280    let mask = N - 1;
281    let mut j = 0;
282    for i in 0..N {
283        if i < j {
284            // Not `slice::swap`: when it is not inlined (opt-level z) its
285            // bounds checks stay.
286            let (a, b) = (i & mask, j & mask);
287            (real[a], real[b]) = (real[b], real[a]);
288            (imag[a], imag[b]) = (imag[b], imag[a]);
289        }
290        // j = reverse(reverse(j) + 1).
291        let mut bit = N >> 1;
292        while j & bit != 0 {
293            j ^= bit;
294            bit >>= 1;
295        }
296        j |= bit;
297    }
298}
299
300/// `real^2 + imag^2` per entry in `i64`, saturated to `i32::MAX` (C++
301/// `magnitudeSquared`, the same in `QFFT1D` and `QRFFT1D`).
302fn magnitude_squared<const L: usize>(real: &[i16; L], imag: &[i16; L], mag_sq: &mut [i32; L]) {
303    for ((o, &r), &m) in mag_sq.iter_mut().zip(real).zip(imag) {
304        let (r, m) = (i64::from(r), i64::from(m));
305        let sq = r * r + m * m;
306        *o = if sq > i64::from(i32::MAX) {
307            i32::MAX
308        } else {
309            sq as i32
310        };
311    }
312}
313
314/// A quantized real-input FFT of length `N` (C++ `QRFFT1D<N>`): `N` real `i16`
315/// samples in, the `N / 2 + 1` bins that are not redundant out, scaled by
316/// `1/N` like [`QFft1D::forward`].
317///
318/// The spectrum of a real signal is conjugate-symmetric, so a complex FFT of
319/// it, with the imaginary part zeroed, spends half its input and half its
320/// output on nothing. This one packs the `N` samples into `N / 2` complex
321/// values (even samples real, odd samples imaginary), runs an `N / 2`-point
322/// complex FFT on them and separates the two halves in a final split step. At
323/// `N = 256` that is 448 butterflies (64 of them without a multiply) and 128
324/// split outputs instead of [`QFft1D`]'s 1,024 butterflies.
325///
326/// It takes the same twiddle tables as `QFft1D<N>`: `HALF` is `N / 2`, and
327/// entry `k` holds `cos(-2πk/N)` and `sin(-2πk/N)` in Q1.15
328/// (`calibration::build_fft_twiddles::<N, HALF>()`, `std` feature). The inner
329/// transform reads every second entry. `N` must be a power of two of at least
330/// 2 and `HALF` must be `N / 2`, or calling any method does not compile.
331///
332/// The bins go to two caller arrays of [`BINS`](Self::BINS) `= N / 2 + 1`
333/// entries, which are also the inner transform's work space: stable Rust
334/// cannot write `[i16; N / 2 + 1]` for a generic `N`, so their length is a
335/// parameter of each method, and a length other than `BINS` does not compile.
336/// Bin 0 (DC) and bin `N / 2` (Nyquist) are real, so their imaginary parts are
337/// 0. Bin `k` for `k > N / 2` is the conjugate of bin `N - k`.
338///
339/// Scaling and headroom: packing two real samples into one complex value
340/// lets a value of the inner transform reach `sqrt(2)` times full scale. So
341/// the first inner stage, whose twiddle is exactly 1, computes `(a ± b) >> 2`
342/// from the samples instead of `>> 1`, and the split step does not halve its
343/// result. No input then saturates an intermediate value; the split step
344/// saturates only where rounding reaches the `i16` rails. The cost is
345/// precision: against an exact DFT divided by `N`, the largest bin error is
346/// about 1.3 to 1.7 times [`QFft1D`]'s on the same real input (about 9 LSB
347/// at `N = 256` on random and full-scale input, where `QFft1D`'s is about 6). Use
348/// `QFft1D` with a zeroed imaginary buffer when that matters more than the
349/// halved work. Rounding is `QFft1D`'s: every shift floors, and every Q1.15
350/// product is `(a * b) >> 15`.
351///
352/// ```
353/// use tinymind::int8::QRFft1D;
354///
355/// // Twiddles for N = 8 (the same tables QFft1D<8, 4> takes).
356/// static COS: [i16; 4] = [32767, 23170, 0, -23170];
357/// static SIN: [i16; 4] = [0, -23170, -32768, -23170];
358/// static FFT: QRFft1D<'static, 8, 4> = QRFft1D { twiddle_cos: &COS, twiddle_sin: &SIN };
359///
360/// // A cosine that completes one cycle over the eight samples.
361/// let input = [8000, 5657, 0, -5657, -8000, -5657, 0, 5657];
362/// let mut real = [0; QRFft1D::<8, 4>::BINS];
363/// let mut imag = [0; QRFft1D::<8, 4>::BINS];
364/// FFT.forward(&input, &mut real, &mut imag);
365/// // Scaled by 1/8, bin 1 holds half the amplitude (bin 7, its mirror, is
366/// // not computed); the floored shifts leave a few values off by a few LSB.
367/// assert_eq!(real, [0, 3998, 0, -1, 0]);
368/// assert_eq!(imag, [0, -1, 0, 0, 0]);
369/// let mut power = [0i32; 5];
370/// FFT.magnitude_squared(&real, &imag, &mut power);
371/// assert_eq!(power[1], 3998 * 3998 + 1);
372/// ```
373///
374/// Output arrays of the wrong length do not compile:
375///
376/// ```compile_fail
377/// # use tinymind::int8::QRFft1D;
378/// static COS: [i16; 4] = [0; 4];
379/// static SIN: [i16; 4] = [0; 4];
380/// let fft: QRFft1D<'_, 8, 4> = QRFft1D { twiddle_cos: &COS, twiddle_sin: &SIN };
381/// fft.forward(&[0; 8], &mut [0; 4], &mut [0; 4]);
382/// ```
383#[derive(Clone, Copy, Debug)]
384pub struct QRFft1D<'a, const N: usize, const HALF: usize> {
385    /// `twiddle_cos[k]` = `cos(-2πk/N)` in Q1.15.
386    pub twiddle_cos: &'a [i16; HALF],
387    /// `twiddle_sin[k]` = `sin(-2πk/N)` in Q1.15.
388    pub twiddle_sin: &'a [i16; HALF],
389}
390
391impl<const N: usize, const HALF: usize> QRFft1D<'_, N, HALF> {
392    /// The number of bins, `N / 2 + 1`: the length of the output arrays.
393    pub const BINS: usize = HALF + 1;
394
395    /// Checks `N` and `HALF` (the C++ `static_assert`s) and that `BINS` is
396    /// `HALF + 1`; a post-monomorphization error if they fail.
397    const fn check<const BINS: usize>() {
398        assert!(N >= 2, "FFT length must be at least 2");
399        assert!(N.is_power_of_two(), "FFT length must be a power of two");
400        assert!(HALF == N / 2, "HALF must be N / 2");
401        assert!(
402            BINS == HALF + 1,
403            "the output arrays must hold N / 2 + 1 bins"
404        );
405    }
406
407    /// Forward real FFT, scaled by `1/N`: bins 0 to `N / 2` of `input`'s
408    /// spectrum into `real` and `imag`. `input` is left unchanged.
409    pub fn forward<const BINS: usize>(
410        &self,
411        input: &[i16; N],
412        real: &mut [i16; BINS],
413        imag: &mut [i16; BINS],
414    ) {
415        self.forward_impl::<BINS, SKIP_SATURATION>(input, real, imag);
416    }
417
418    /// Squared magnitude of each of the `BINS` bins, `real^2 + imag^2`, in
419    /// `i32`, saturated to `i32::MAX` as in [`QFft1D::magnitude_squared`].
420    pub fn magnitude_squared<const BINS: usize>(
421        &self,
422        real: &[i16; BINS],
423        imag: &[i16; BINS],
424        mag_sq: &mut [i32; BINS],
425    ) {
426        const { Self::check::<BINS>() };
427        magnitude_squared(real, imag, mag_sq);
428    }
429
430    /// [`forward`](Self::forward), with or without the saturation skip in the
431    /// inner stages (see `SKIP_SATURATION`; both give the same results).
432    #[inline(never)]
433    pub(crate) fn forward_impl<const BINS: usize, const SKIP: bool>(
434        &self,
435        input: &[i16; N],
436        real: &mut [i16; BINS],
437        imag: &mut [i16; BINS],
438    ) {
439        const { Self::check::<BINS>() };
440        // Bins 0 to HALF - 1 hold the inner transform, bin HALF the Nyquist
441        // bin. BINS == HALF + 1, so none of these splits fails.
442        let Some((zr, tail_r)) = real.split_first_chunk_mut::<HALF>() else {
443            return;
444        };
445        let Some((zi, tail_i)) = imag.split_first_chunk_mut::<HALF>() else {
446            return;
447        };
448        let (Some(nyquist_r), Some(nyquist_i)) = (tail_r.first_mut(), tail_i.first_mut()) else {
449            return;
450        };
451        let (cos, sin) = (self.twiddle_cos, self.twiddle_sin);
452        let zmask = HALF - 1;
453
454        if HALF >= 2 {
455            // Bit-reversed load of the packed samples, fused with the first
456            // stage (twiddle 1): (a ± b) >> 2 from the full-precision samples,
457            // so the inner transform has the headroom packing costs. For even
458            // n, reverse(n) over log2(HALF) bits is reverse(n / 2) over one bit
459            // fewer, and reverse(n + 1) adds HALF / 2; `j` steps through the
460            // first sequence by reverse-carry, as in `bit_reverse_permute`.
461            let mask = N - 1;
462            let quarter = HALF / 2;
463            let mut j = 0;
464            for m in 0..quarter {
465                let (j0, j1) = (j, j + quarter);
466                let a_real = i32::from(input[(2 * j0) & mask]);
467                let a_imag = i32::from(input[(2 * j0 + 1) & mask]);
468                let b_real = i32::from(input[(2 * j1) & mask]);
469                let b_imag = i32::from(input[(2 * j1 + 1) & mask]);
470                // |a ± b| <= 65535, so each quarter fits in i16.
471                let n = 2 * m;
472                zr[n & zmask] = ((a_real + b_real) >> 2) as i16;
473                zi[n & zmask] = ((a_imag + b_imag) >> 2) as i16;
474                zr[(n + 1) & zmask] = ((a_real - b_real) >> 2) as i16;
475                zi[(n + 1) & zmask] = ((a_imag - b_imag) >> 2) as i16;
476                let mut bit = quarter >> 1;
477                while j & bit != 0 {
478                    j ^= bit;
479                    bit >>= 1;
480                }
481                j |= bit;
482            }
483            // The remaining stages of the inner transform, QFft1D's scaled
484            // butterflies; stage twiddle W_{2h}^p = W_N^{p * (N / 2) / h}.
485            run_stages::<true, SKIP, HALF, HALF, 2>(cos, sin, zr, zi);
486        } else {
487            // N = 2: one complex value, no inner stage.
488            zr[0] = input[0];
489            zi[0] = input[N - 1];
490        }
491
492        // Split step. DC and Nyquist come from Z[0] alone; for N = 2 the
493        // first-stage halving is taken here instead.
494        let z0_real = i32::from(zr[0]);
495        let z0_imag = i32::from(zi[0]);
496        let edge_shift = if HALF >= 2 { 0 } else { 1 };
497        zr[0] = saturate_i16((z0_real + z0_imag) >> edge_shift);
498        *nyquist_r = saturate_i16((z0_real - z0_imag) >> edge_shift);
499        zi[0] = 0;
500        *nyquist_i = 0;
501
502        for k in 1..=HALF / 2 {
503            let (a, b) = (k & zmask, (HALF - k) & zmask);
504            let (a_real, a_imag) = (i32::from(zr[a]), i32::from(zi[a]));
505            let (b_real, b_imag) = (i32::from(zr[b]), i32::from(zi[b]));
506            (zr[a], zi[a]) = split_bin(a_real, a_imag, b_real, b_imag, cos[a], sin[a]);
507            if a != b {
508                (zr[b], zi[b]) = split_bin(b_real, b_imag, a_real, a_imag, cos[b], sin[b]);
509            }
510        }
511    }
512}
513
514/// One bin of the real FFT's split step (C++ `qfft_detail::qrfftSplitBin`):
515/// `X[k] = E[k] + W * O[k]` from `a = Z[k]` and `b = Z[M - k]`, with
516/// `E = (a + conj(b)) / 2` and `O = (a - conj(b)) / (2i)`.
517#[inline(always)]
518fn split_bin(
519    a_real: i32,
520    a_imag: i32,
521    b_real: i32,
522    b_imag: i32,
523    w_cos: i16,
524    w_sin: i16,
525) -> (i16, i16) {
526    let (w_cos, w_sin) = (i32::from(w_cos), i32::from(w_sin));
527    let even_real = (a_real + b_real) >> 1;
528    let even_imag = (a_imag - b_imag) >> 1;
529    let odd_real = (a_imag + b_imag) >> 1;
530    let odd_imag = (b_real - a_real) >> 1;
531    let t_real = q15_mul(w_cos, odd_real) - q15_mul(w_sin, odd_imag);
532    let t_imag = q15_mul(w_cos, odd_imag) + q15_mul(w_sin, odd_real);
533    (
534        saturate_i16(even_real + t_real),
535        saturate_i16(even_imag + t_imag),
536    )
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    fn reverse(i: usize, bits: u32) -> usize {
544        (0..bits).fold(0, |r, b| (r << 1) | ((i >> b) & 1))
545    }
546
547    fn check_permutation<const N: usize>() {
548        let mut real: [i16; N] = core::array::from_fn(|i| i as i16);
549        let mut imag: [i16; N] = core::array::from_fn(|i| !(i as i16));
550        bit_reverse_permute(&mut real, &mut imag);
551        let bits = N.trailing_zeros();
552        for i in 0..N {
553            assert_eq!(real[i] as usize, reverse(i, bits), "N={N} i={i}");
554            assert_eq!(imag[i], !(reverse(i, bits) as i16));
555        }
556    }
557
558    /// The forward transform gives the same bits with and without the
559    /// saturation skip, at every power-of-two length up to 1024, on random
560    /// samples and twiddles that reach the rails (where the skip does not
561    /// apply) and on smaller ones (where it does). The host sweep runs the
562    /// form the host gets; QEMU's Cortex-M0 runs the other against the C++.
563    #[test]
564    fn saturation_skip_changes_nothing() {
565        fn check<const N: usize, const HALF: usize>(rng: &mut crate::rand::GlibcRand) {
566            for trial in 0..20 {
567                let scale = [0, 1, 6][trial % 3];
568                let mut draw = || (rng.next_i32() as i16) >> scale;
569                let cos: [i16; HALF] = core::array::from_fn(|_| draw());
570                let sin: [i16; HALF] = core::array::from_fn(|_| draw());
571                let real: [i16; N] = core::array::from_fn(|_| draw());
572                let imag: [i16; N] = core::array::from_fn(|_| draw());
573                let fft: QFft1D<'_, N, HALF> = QFft1D {
574                    twiddle_cos: &cos,
575                    twiddle_sin: &sin,
576                };
577                let (mut r0, mut i0) = (real, imag);
578                fft.transform::<true, false>(&mut r0, &mut i0);
579                let (mut r1, mut i1) = (real, imag);
580                fft.transform::<true, true>(&mut r1, &mut i1);
581                assert_eq!((r0, i0), (r1, i1), "N={N} trial {trial}");
582            }
583        }
584        let mut rng = crate::rand::GlibcRand::new(11);
585        check::<2, 1>(&mut rng);
586        check::<4, 2>(&mut rng);
587        check::<8, 4>(&mut rng);
588        check::<64, 32>(&mut rng);
589        check::<256, 128>(&mut rng);
590        check::<1024, 512>(&mut rng);
591    }
592
593    /// The real FFT's forward transform gives the same bits with and without
594    /// the saturation skip in its inner stages, as `QFft1D`'s does.
595    #[test]
596    fn rfft_saturation_skip_changes_nothing() {
597        fn check<const N: usize, const HALF: usize, const BINS: usize>(
598            rng: &mut crate::rand::GlibcRand,
599        ) {
600            for trial in 0..20 {
601                let scale = [0, 1, 6][trial % 3];
602                let mut draw = || (rng.next_i32() as i16) >> scale;
603                let cos: [i16; HALF] = core::array::from_fn(|_| draw());
604                let sin: [i16; HALF] = core::array::from_fn(|_| draw());
605                let input: [i16; N] = core::array::from_fn(|_| draw());
606                let fft: QRFft1D<'_, N, HALF> = QRFft1D {
607                    twiddle_cos: &cos,
608                    twiddle_sin: &sin,
609                };
610                let (mut r0, mut i0) = ([0; BINS], [0; BINS]);
611                fft.forward_impl::<BINS, false>(&input, &mut r0, &mut i0);
612                let (mut r1, mut i1) = ([0; BINS], [0; BINS]);
613                fft.forward_impl::<BINS, true>(&input, &mut r1, &mut i1);
614                assert_eq!((r0, i0), (r1, i1), "N={N} trial {trial}");
615            }
616        }
617        let mut rng = crate::rand::GlibcRand::new(12);
618        check::<2, 1, 2>(&mut rng);
619        check::<4, 2, 3>(&mut rng);
620        check::<8, 4, 5>(&mut rng);
621        check::<64, 32, 33>(&mut rng);
622        check::<256, 128, 129>(&mut rng);
623        check::<1024, 512, 513>(&mut rng);
624    }
625
626    /// N = 2 is the sum and the difference, halved (the scaling by 1/N).
627    #[test]
628    fn rfft_of_two_samples() {
629        static T: [i16; 1] = [32767];
630        let fft: QRFft1D<'_, 2, 1> = QRFft1D {
631            twiddle_cos: &T,
632            twiddle_sin: &[0],
633        };
634        for (a, b) in [(3, 1), (-32768, -32768), (32767, -32768), (-5, 2)] {
635            let (mut re, mut im) = ([9; 2], [9; 2]);
636            fft.forward(&[a, b], &mut re, &mut im);
637            let (a, b) = (i32::from(a), i32::from(b));
638            assert_eq!(re, [((a + b) >> 1) as i16, ((a - b) >> 1) as i16]);
639            assert_eq!(im, [0, 0]);
640        }
641    }
642
643    /// The split step saturates its sums. With tables from
644    /// `build_fft_twiddles` only rounding can reach the rails; other tables
645    /// reach past them. Expected values from tinymind (C++)'s
646    /// `qrfftSplitBin`.
647    #[test]
648    fn rfft_split_saturates() {
649        assert_eq!(
650            split_bin(0, -23000, 23000, -23000, -32768, -32768),
651            (i16::MAX, 11500)
652        );
653        assert_eq!(
654            split_bin(0, 23000, -23000, 23000, -32768, -32768),
655            (i16::MIN, -11500)
656        );
657    }
658
659    #[test]
660    fn bit_reversal_matches_the_table() {
661        check_permutation::<2>();
662        check_permutation::<4>();
663        check_permutation::<8>();
664        check_permutation::<64>();
665        check_permutation::<1024>();
666        check_permutation::<4096>();
667    }
668
669    #[test]
670    fn saturate_and_q15() {
671        assert_eq!(saturate_i16(40_000), i16::MAX);
672        assert_eq!(saturate_i16(-40_000), i16::MIN);
673        assert_eq!(saturate_i16(-32_768), i16::MIN);
674        assert_eq!(q15_mul(-32768, -32768), 32768);
675        assert_eq!(q15_mul(1, -1), -1);
676    }
677
678    #[test]
679    fn magnitude_saturates_only_at_both_rails() {
680        static T: [i16; 1] = [32767];
681        let fft: QFft1D<'_, 2, 1> = QFft1D {
682            twiddle_cos: &T,
683            twiddle_sin: &[0],
684        };
685        let mut m = [0; 2];
686        fft.magnitude_squared(&[-32768, -32768], &[-32768, 32767], &mut m);
687        assert_eq!(m, [i32::MAX, 32768 * 32768 + 32767 * 32767]);
688    }
689}