// SpectralGoldenValueTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing @_spi(LyrebirdExtensions) import LyrebirdSynth // Golden values for the real-FFT path through `SpectralChain` — the only place // the portable `vDSP_fft_zrip` / `vDSP_ctoz` / `vDSP_ztoc` replacements are // exercised as *audio* rather than as isolated primitives. // // Two directions are pinned: // • forward — the analysis magnitude spectrum of a bin-centred sine, which // depends on the split-complex packing (DC and Nyquist share one complex // slot) and on vDSP's factor-of-two real-FFT scaling. Get either wrong and // the peak lands in the wrong bin or at the wrong height. // • inverse — the resynthesised waveform after windowed overlap-add, which // only comes back out as a clean unit-amplitude sine if forward and inverse // agree on both conventions. // // Captured on macOS (arm64, vDSP-backed). Internals here are `Float`, so the // tolerances are looser than the double-precision filter goldens. @MainActor @Suite("Portable DSP golden values — spectral") struct SpectralGoldenValueTests { private static let fftSize: Int = 64 private static let hopSize: Int = 32 private static let sampleRate: Double = 44100 /// Sine placed exactly on bin 8 so the analysis peak is unambiguous. private static let analysisBin: Int = 8 private static var binFrequency: Double { sampleRate * Double(analysisBin) / Double(fftSize) } /// Blocks needed to fill the analysis ring and reach steady-state overlap-add. private static let warmUpBlocks: Int = 8 @Test func analysisMagnitudeSpectrumOfBinCentredSine() throws { let engine: SynthesisEngine = makePortableTestEngine( blockSize: Self.hopSize, sampleRate: Self.sampleRate ) try engine.start() defer { engine.stop() } let chain: SpectralChain.Audio = SpectralChain.Audio( input: OscSin.Audio(freq: Self.binFrequency), fftSize: Self.fftSize, hopSize: Self.hopSize, analyzeOnly: true ) for _ in 0.. magnitudes[peakBin] { peakBin = bin } #expect(peakBin == Self.analysisBin, "peak landed in bin \(peakBin)") } @Test func resynthesisReconstructsInputSine() throws { let engine: SynthesisEngine = makePortableTestEngine( blockSize: Self.hopSize, sampleRate: Self.sampleRate ) try engine.start() defer { engine.stop() } let chain: SpectralChain.Audio = SpectralChain.Audio( input: OscSin.Audio(freq: Self.binFrequency), fftSize: Self.fftSize, hopSize: Self.hopSize ) var resynthesised: [Double] = [] for _ in 0..