#[inline(always)]
pub(crate) fn saturate_i16(v: i32) -> i16 {
if v < i32::from(i16::MIN) {
i16::MIN
} else if v > i32::from(i16::MAX) {
i16::MAX
} else {
v as i16
}
}
const SKIP_SATURATION: bool = cfg!(not(target_has_atomic = "32"));
#[inline(always)]
pub(crate) fn fits_i16(v: i32) -> bool {
((v >> 15) + 1) as u32 <= 1
}
#[inline(always)]
pub(crate) fn q15_mul(a: i32, b: i32) -> i32 {
(a * b) >> 15
}
#[derive(Clone, Copy, Debug)]
pub struct QFft1D<'a, const N: usize, const HALF: usize> {
pub twiddle_cos: &'a [i16; HALF],
pub twiddle_sin: &'a [i16; HALF],
}
impl<const N: usize, const HALF: usize> QFft1D<'_, N, HALF> {
const STAGES: u32 = {
assert!(N >= 2, "FFT length must be at least 2");
assert!(N.is_power_of_two(), "FFT length must be a power of two");
assert!(HALF == N / 2, "HALF must be N / 2");
N.trailing_zeros()
};
pub fn forward(&self, real: &mut [i16; N], imag: &mut [i16; N]) {
self.transform::<true, SKIP_SATURATION>(real, imag);
}
pub fn inverse(&self, real: &mut [i16; N], imag: &mut [i16; N]) {
for x in imag.iter_mut() {
*x = x.wrapping_neg();
}
self.transform::<false, SKIP_SATURATION>(real, imag);
for x in imag.iter_mut() {
*x = x.wrapping_neg();
}
}
pub fn magnitude_squared(&self, real: &[i16; N], imag: &[i16; N], mag_sq: &mut [i32; N]) {
let _ = Self::STAGES;
magnitude_squared(real, imag, mag_sq);
}
#[inline(never)]
pub(crate) fn transform<const SCALE: bool, const SKIP: bool>(
&self,
real: &mut [i16; N],
imag: &mut [i16; N],
) {
let _ = Self::STAGES;
bit_reverse_permute(real, imag);
run_stages::<SCALE, SKIP, N, HALF, 1>(self.twiddle_cos, self.twiddle_sin, real, imag);
}
}
#[inline(always)]
fn run_stages<
const SCALE: bool,
const SKIP: bool,
const L: usize,
const T: usize,
const FIRST: usize,
>(
cos: &[i16; T],
sin: &[i16; T],
real: &mut [i16; L],
imag: &mut [i16; L],
) {
macro_rules! stages {
($($h:literal)*) => {$(
if $h >= FIRST && $h < L {
stage::<SCALE, SKIP, L, T, $h>(cos, sin, real, imag);
}
)*};
}
stages!(
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144
524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728
268435456 536870912 1073741824
);
}
#[inline(always)]
fn stage<const SCALE: bool, const SKIP: bool, const L: usize, const T: usize, const H: usize>(
cos: &[i16; T],
sin: &[i16; T],
real: &mut [i16; L],
imag: &mut [i16; L],
) {
let mask = L - 1;
let tw_mask = T - 1;
let stride = T / H;
for pair in 0..H {
let k = (pair * stride) & tw_mask;
let w_cos = i32::from(cos[k]);
let w_sin = i32::from(sin[k]);
let mut top = pair;
while top < L {
butterfly::<SCALE, SKIP, L>(real, imag, top & mask, (top + H) & mask, w_cos, w_sin);
top += 2 * H;
}
}
}
#[inline(always)]
fn butterfly<const SCALE: bool, const SKIP: bool, const N: usize>(
real: &mut [i16; N],
imag: &mut [i16; N],
top: usize,
bot: usize,
w_cos: i32,
w_sin: i32,
) {
let bot_real = i32::from(real[bot]);
let bot_imag = i32::from(imag[bot]);
let t_real = q15_mul(w_cos, bot_real) - q15_mul(w_sin, bot_imag);
let t_imag = q15_mul(w_cos, bot_imag) + q15_mul(w_sin, bot_real);
let top_real = i32::from(real[top]);
let top_imag = i32::from(imag[top]);
if SCALE {
if SKIP && fits_i16(t_real) && fits_i16(t_imag) {
real[top] = ((top_real + t_real) >> 1) as i16;
imag[top] = ((top_imag + t_imag) >> 1) as i16;
real[bot] = ((top_real - t_real) >> 1) as i16;
imag[bot] = ((top_imag - t_imag) >> 1) as i16;
} else {
real[top] = saturate_i16((top_real + t_real) >> 1);
imag[top] = saturate_i16((top_imag + t_imag) >> 1);
real[bot] = saturate_i16((top_real - t_real) >> 1);
imag[bot] = saturate_i16((top_imag - t_imag) >> 1);
}
} else {
real[top] = saturate_i16(top_real + t_real);
imag[top] = saturate_i16(top_imag + t_imag);
real[bot] = saturate_i16(top_real - t_real);
imag[bot] = saturate_i16(top_imag - t_imag);
}
}
fn bit_reverse_permute<const N: usize>(real: &mut [i16; N], imag: &mut [i16; N]) {
let mask = N - 1;
let mut j = 0;
for i in 0..N {
if i < j {
let (a, b) = (i & mask, j & mask);
(real[a], real[b]) = (real[b], real[a]);
(imag[a], imag[b]) = (imag[b], imag[a]);
}
let mut bit = N >> 1;
while j & bit != 0 {
j ^= bit;
bit >>= 1;
}
j |= bit;
}
}
fn magnitude_squared<const L: usize>(real: &[i16; L], imag: &[i16; L], mag_sq: &mut [i32; L]) {
for ((o, &r), &m) in mag_sq.iter_mut().zip(real).zip(imag) {
let (r, m) = (i64::from(r), i64::from(m));
let sq = r * r + m * m;
*o = if sq > i64::from(i32::MAX) {
i32::MAX
} else {
sq as i32
};
}
}
#[derive(Clone, Copy, Debug)]
pub struct QRFft1D<'a, const N: usize, const HALF: usize> {
pub twiddle_cos: &'a [i16; HALF],
pub twiddle_sin: &'a [i16; HALF],
}
impl<const N: usize, const HALF: usize> QRFft1D<'_, N, HALF> {
pub const BINS: usize = HALF + 1;
const fn check<const BINS: usize>() {
assert!(N >= 2, "FFT length must be at least 2");
assert!(N.is_power_of_two(), "FFT length must be a power of two");
assert!(HALF == N / 2, "HALF must be N / 2");
assert!(
BINS == HALF + 1,
"the output arrays must hold N / 2 + 1 bins"
);
}
pub fn forward<const BINS: usize>(
&self,
input: &[i16; N],
real: &mut [i16; BINS],
imag: &mut [i16; BINS],
) {
self.forward_impl::<BINS, SKIP_SATURATION>(input, real, imag);
}
pub fn magnitude_squared<const BINS: usize>(
&self,
real: &[i16; BINS],
imag: &[i16; BINS],
mag_sq: &mut [i32; BINS],
) {
const { Self::check::<BINS>() };
magnitude_squared(real, imag, mag_sq);
}
#[inline(never)]
pub(crate) fn forward_impl<const BINS: usize, const SKIP: bool>(
&self,
input: &[i16; N],
real: &mut [i16; BINS],
imag: &mut [i16; BINS],
) {
const { Self::check::<BINS>() };
let Some((zr, tail_r)) = real.split_first_chunk_mut::<HALF>() else {
return;
};
let Some((zi, tail_i)) = imag.split_first_chunk_mut::<HALF>() else {
return;
};
let (Some(nyquist_r), Some(nyquist_i)) = (tail_r.first_mut(), tail_i.first_mut()) else {
return;
};
let (cos, sin) = (self.twiddle_cos, self.twiddle_sin);
let zmask = HALF - 1;
if HALF >= 2 {
let mask = N - 1;
let quarter = HALF / 2;
let mut j = 0;
for m in 0..quarter {
let (j0, j1) = (j, j + quarter);
let a_real = i32::from(input[(2 * j0) & mask]);
let a_imag = i32::from(input[(2 * j0 + 1) & mask]);
let b_real = i32::from(input[(2 * j1) & mask]);
let b_imag = i32::from(input[(2 * j1 + 1) & mask]);
let n = 2 * m;
zr[n & zmask] = ((a_real + b_real) >> 2) as i16;
zi[n & zmask] = ((a_imag + b_imag) >> 2) as i16;
zr[(n + 1) & zmask] = ((a_real - b_real) >> 2) as i16;
zi[(n + 1) & zmask] = ((a_imag - b_imag) >> 2) as i16;
let mut bit = quarter >> 1;
while j & bit != 0 {
j ^= bit;
bit >>= 1;
}
j |= bit;
}
run_stages::<true, SKIP, HALF, HALF, 2>(cos, sin, zr, zi);
} else {
zr[0] = input[0];
zi[0] = input[N - 1];
}
let z0_real = i32::from(zr[0]);
let z0_imag = i32::from(zi[0]);
let edge_shift = if HALF >= 2 { 0 } else { 1 };
zr[0] = saturate_i16((z0_real + z0_imag) >> edge_shift);
*nyquist_r = saturate_i16((z0_real - z0_imag) >> edge_shift);
zi[0] = 0;
*nyquist_i = 0;
for k in 1..=HALF / 2 {
let (a, b) = (k & zmask, (HALF - k) & zmask);
let (a_real, a_imag) = (i32::from(zr[a]), i32::from(zi[a]));
let (b_real, b_imag) = (i32::from(zr[b]), i32::from(zi[b]));
(zr[a], zi[a]) = split_bin(a_real, a_imag, b_real, b_imag, cos[a], sin[a]);
if a != b {
(zr[b], zi[b]) = split_bin(b_real, b_imag, a_real, a_imag, cos[b], sin[b]);
}
}
}
}
#[inline(always)]
fn split_bin(
a_real: i32,
a_imag: i32,
b_real: i32,
b_imag: i32,
w_cos: i16,
w_sin: i16,
) -> (i16, i16) {
let (w_cos, w_sin) = (i32::from(w_cos), i32::from(w_sin));
let even_real = (a_real + b_real) >> 1;
let even_imag = (a_imag - b_imag) >> 1;
let odd_real = (a_imag + b_imag) >> 1;
let odd_imag = (b_real - a_real) >> 1;
let t_real = q15_mul(w_cos, odd_real) - q15_mul(w_sin, odd_imag);
let t_imag = q15_mul(w_cos, odd_imag) + q15_mul(w_sin, odd_real);
(
saturate_i16(even_real + t_real),
saturate_i16(even_imag + t_imag),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn reverse(i: usize, bits: u32) -> usize {
(0..bits).fold(0, |r, b| (r << 1) | ((i >> b) & 1))
}
fn check_permutation<const N: usize>() {
let mut real: [i16; N] = core::array::from_fn(|i| i as i16);
let mut imag: [i16; N] = core::array::from_fn(|i| !(i as i16));
bit_reverse_permute(&mut real, &mut imag);
let bits = N.trailing_zeros();
for i in 0..N {
assert_eq!(real[i] as usize, reverse(i, bits), "N={N} i={i}");
assert_eq!(imag[i], !(reverse(i, bits) as i16));
}
}
#[test]
fn saturation_skip_changes_nothing() {
fn check<const N: usize, const HALF: usize>(rng: &mut crate::rand::GlibcRand) {
for trial in 0..20 {
let scale = [0, 1, 6][trial % 3];
let mut draw = || (rng.next_i32() as i16) >> scale;
let cos: [i16; HALF] = core::array::from_fn(|_| draw());
let sin: [i16; HALF] = core::array::from_fn(|_| draw());
let real: [i16; N] = core::array::from_fn(|_| draw());
let imag: [i16; N] = core::array::from_fn(|_| draw());
let fft: QFft1D<'_, N, HALF> = QFft1D {
twiddle_cos: &cos,
twiddle_sin: &sin,
};
let (mut r0, mut i0) = (real, imag);
fft.transform::<true, false>(&mut r0, &mut i0);
let (mut r1, mut i1) = (real, imag);
fft.transform::<true, true>(&mut r1, &mut i1);
assert_eq!((r0, i0), (r1, i1), "N={N} trial {trial}");
}
}
let mut rng = crate::rand::GlibcRand::new(11);
check::<2, 1>(&mut rng);
check::<4, 2>(&mut rng);
check::<8, 4>(&mut rng);
check::<64, 32>(&mut rng);
check::<256, 128>(&mut rng);
check::<1024, 512>(&mut rng);
}
#[test]
fn rfft_saturation_skip_changes_nothing() {
fn check<const N: usize, const HALF: usize, const BINS: usize>(
rng: &mut crate::rand::GlibcRand,
) {
for trial in 0..20 {
let scale = [0, 1, 6][trial % 3];
let mut draw = || (rng.next_i32() as i16) >> scale;
let cos: [i16; HALF] = core::array::from_fn(|_| draw());
let sin: [i16; HALF] = core::array::from_fn(|_| draw());
let input: [i16; N] = core::array::from_fn(|_| draw());
let fft: QRFft1D<'_, N, HALF> = QRFft1D {
twiddle_cos: &cos,
twiddle_sin: &sin,
};
let (mut r0, mut i0) = ([0; BINS], [0; BINS]);
fft.forward_impl::<BINS, false>(&input, &mut r0, &mut i0);
let (mut r1, mut i1) = ([0; BINS], [0; BINS]);
fft.forward_impl::<BINS, true>(&input, &mut r1, &mut i1);
assert_eq!((r0, i0), (r1, i1), "N={N} trial {trial}");
}
}
let mut rng = crate::rand::GlibcRand::new(12);
check::<2, 1, 2>(&mut rng);
check::<4, 2, 3>(&mut rng);
check::<8, 4, 5>(&mut rng);
check::<64, 32, 33>(&mut rng);
check::<256, 128, 129>(&mut rng);
check::<1024, 512, 513>(&mut rng);
}
#[test]
fn rfft_of_two_samples() {
static T: [i16; 1] = [32767];
let fft: QRFft1D<'_, 2, 1> = QRFft1D {
twiddle_cos: &T,
twiddle_sin: &[0],
};
for (a, b) in [(3, 1), (-32768, -32768), (32767, -32768), (-5, 2)] {
let (mut re, mut im) = ([9; 2], [9; 2]);
fft.forward(&[a, b], &mut re, &mut im);
let (a, b) = (i32::from(a), i32::from(b));
assert_eq!(re, [((a + b) >> 1) as i16, ((a - b) >> 1) as i16]);
assert_eq!(im, [0, 0]);
}
}
#[test]
fn rfft_split_saturates() {
assert_eq!(
split_bin(0, -23000, 23000, -23000, -32768, -32768),
(i16::MAX, 11500)
);
assert_eq!(
split_bin(0, 23000, -23000, 23000, -32768, -32768),
(i16::MIN, -11500)
);
}
#[test]
fn bit_reversal_matches_the_table() {
check_permutation::<2>();
check_permutation::<4>();
check_permutation::<8>();
check_permutation::<64>();
check_permutation::<1024>();
check_permutation::<4096>();
}
#[test]
fn saturate_and_q15() {
assert_eq!(saturate_i16(40_000), i16::MAX);
assert_eq!(saturate_i16(-40_000), i16::MIN);
assert_eq!(saturate_i16(-32_768), i16::MIN);
assert_eq!(q15_mul(-32768, -32768), 32768);
assert_eq!(q15_mul(1, -1), -1);
}
#[test]
fn magnitude_saturates_only_at_both_rails() {
static T: [i16; 1] = [32767];
let fft: QFft1D<'_, 2, 1> = QFft1D {
twiddle_cos: &T,
twiddle_sin: &[0],
};
let mut m = [0; 2];
fft.magnitude_squared(&[-32768, -32768], &[-32768, 32767], &mut m);
assert_eq!(m, [i32::MAX, 32768 * 32768 + 32767 * 32767]);
}
}