// ComplexFFTCore.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation // Portable radix-2 FFT cores backing the non-Apple `vDSP_fft_zrip` shim. These // are compiled on every platform (not behind an `#if`) so they can be parity- // tested against the real Accelerate FFT on Apple — the test is what proves the // fallback reproduces vDSP's real-FFT packing (DC in realp[0], Nyquist in // imagp[0]) and its scaling (forward ×2 per bin; forward→inverse ×2N), which // consumers depend on. /// In-place iterative Cooley–Tukey complex FFT, length `n = 2^log2n`. /// `forward == true` uses the `e^{-2πi}` sign; both directions are /// **unnormalized** (no `1/n`), matching vDSP. @inline(__always) func _lbComplexFFT( _ re: UnsafeMutablePointer, _ im: UnsafeMutablePointer, _ n: Int, _ forward: Bool ) { // Bit-reversal permutation. var j: Int = 0 for i: Int in 0..<(n - 1) { if i < j { let tr: Float = re[i]; re[i] = re[j]; re[j] = tr let ti: Float = im[i]; im[i] = im[j]; im[j] = ti } var m: Int = n >> 1 while m >= 1 && j >= m { j -= m; m >>= 1 } j += m } let sign: Float = forward ? -1 : 1 var len: Int = 2 while len <= n { let half: Int = len >> 1 let base: Float = sign * 2 * Float.pi / Float(len) var group: Int = 0 while group < n { for k: Int in 0.., _ imagp: UnsafeMutablePointer, _ half: Int, _ workRe: UnsafeMutablePointer, _ workIm: UnsafeMutablePointer ) { let n: Int = half * 2 for jIdx: Int in 0.., _ imagp: UnsafeMutablePointer, _ half: Int, _ workRe: UnsafeMutablePointer, _ workIm: UnsafeMutablePointer ) { let n: Int = half * 2 // Rebuild the full Hermitian-symmetric spectrum from the packed half. workRe[0] = realp[0]; workIm[0] = 0 workRe[half] = imagp[0]; workIm[half] = 0 for k: Int in 1..