Files
2026-06-21 11:45:58 -07:00

416 lines
16 KiB
Swift

// SpectralComplexClosureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpectralComplexClosure")
struct SpectralComplexClosureTests {
// MARK: - Helpers
private static func fillKnownPolar(_ buf: SpectralBuffer) {
buf.dcValue = 0.5
buf.nyquistValue = -0.25
let halfSize: Int = buf.fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = Float(k) * 0.01
buf[phase: k] = 0.3
}
}
// MARK: - Basic structural tests
@Test func identityClosureDoesNotMutate() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
Self.fillKnownPolar(buf)
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { _ in }
proc.process(spectral: buf, engine: makeTestEngine())
// After a no-op closure, the round-trip (polar→complex→polar) should
// reproduce magnitudes and phases within Float trigonometric error (~1e-6).
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
let expectedMag: Float = Float(k) * 0.01
#expect(abs(buf[magnitude: k] - expectedMag) < 1e-4,
"magnitude of bin \(k) drifted after identity: \(buf[magnitude: k]) vs \(expectedMag)")
#expect(abs(buf[phase: k] - 0.3) < 1e-4,
"phase of bin \(k) drifted after identity: \(buf[phase: k])")
}
// DC and Nyquist pass through as-is.
#expect(abs(buf.dcValue - 0.5) < 1e-6)
#expect(abs(buf.nyquistValue - (-0.25)) < 1e-6)
}
@Test func closureReceivesCorrectBinCount() {
let fftSize: Int = 128
var observedBinCount: Int = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 64, sampleRate: 44100
) { ctx in
observedBinCount = ctx.binCount
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
// binCount = fftSize/2 (includes packed DC[0] and Nyquist imag[0])
#expect(observedBinCount == fftSize / 2)
}
@Test func closureReceivesCorrectMetadata() {
let fftSize: Int = 256
let hopSize: Int = 64
let sampleRate: Double = 48000.0
var seenFFTSize: Int = 0
var seenHopSize: Int = 0
var seenSampleRate: Double = 0.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: sampleRate
) { ctx in
seenFFTSize = ctx.fftSize
seenHopSize = ctx.hopSize
seenSampleRate = ctx.sampleRate
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
proc.process(spectral: buf, engine: makeTestEngine())
#expect(seenFFTSize == fftSize)
#expect(seenHopSize == hopSize)
#expect(seenSampleRate == sampleRate)
}
// MARK: - Split-complex layout
@Test func dcPackedAtRealIndex0() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = 7.0
var observedDC: Float = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedDC = ctx.real[0]
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(observedDC - 7.0) < 1e-6,
"DC should be packed at real[0], got \(observedDC)")
}
@Test func nyquistPackedAtImagIndex0() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.nyquistValue = -3.0
var observedNyquist: Float = 0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedNyquist = ctx.imag[0]
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(observedNyquist - (-3.0)) < 1e-6,
"Nyquist should be packed at imag[0], got \(observedNyquist)")
}
@Test func zeroBinHasZeroCartesian() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
// All bins zeroed.
buf.dcValue = 0
buf.nyquistValue = 0
for k: Int in 1..<halfSize {
buf[magnitude: k] = 0
buf[phase: k] = 0
}
var anyNonZero: Bool = false
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount {
if abs(ctx.real[i]) > 1e-6 || abs(ctx.imag[i]) > 1e-6 {
anyNonZero = true
}
}
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(!anyNonZero, "Zero-magnitude bins should yield zero Cartesian values")
}
// MARK: - Mutation round-trip
@Test func zeroClearsSingleBinInPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
let halfSize: Int = fftSize / 2
for k: Int in 1..<halfSize {
buf[magnitude: k] = 1.0
buf[phase: k] = 0.5
}
// Zero out bin 3 in Cartesian space (index 3 in real/imag maps to spectral bin 3).
let targetBin: Int = 3
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.real[targetBin] = 0
ctx.imag[targetBin] = 0
}
proc.process(spectral: buf, engine: makeTestEngine())
// After zeroing, magnitude of the target bin should be ≈ 0.
#expect(buf[magnitude: targetBin] < 1e-6,
"Zeroed Cartesian bin should have ≈ 0 magnitude, got \(buf[magnitude: targetBin])")
}
@Test func dcMutationWritesBackThroughPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.dcValue = 2.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.real[0] = 5.0
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.dcValue - 5.0) < 1e-6,
"DC write-back failed: \(buf.dcValue)")
}
@Test func nyquistMutationWritesBackThroughPolar() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf.nyquistValue = -1.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
ctx.imag[0] = 4.0
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(abs(buf.nyquistValue - 4.0) < 1e-6,
"Nyquist write-back failed: \(buf.nyquistValue)")
}
// MARK: - Frame index
@Test func frameIndexIncrementsAcrossHops() {
let fftSize: Int = 64
var observedIndices: [Int] = []
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
observedIndices.append(ctx.frameIndex)
}
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
for _ in 0..<5 {
proc.process(spectral: buf, engine: makeTestEngine())
}
#expect(observedIndices == [0, 1, 2, 3, 4])
}
// MARK: - Guard conditions
@Test func fftSizeMismatchIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: 128)
buf[magnitude: 1] = 99.0
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.real[i] = 0; ctx.imag[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 1] == 99.0)
}
@Test func invalidBufferIsBypassed() {
let fftSize: Int = 64
let buf: SpectralBuffer = SpectralBuffer(fftSize: fftSize)
buf[magnitude: 4] = 5.0
buf.invalidate()
let proc: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: 32, sampleRate: 44100
) { ctx in
for i: Int in 0..<ctx.binCount { ctx.real[i] = 0; ctx.imag[i] = 0 }
}
proc.process(spectral: buf, engine: makeTestEngine())
#expect(buf[magnitude: 4] == 5.0)
}
// MARK: - SpectralChain integration
/// Complex identity closure: round-trip through SpectralChain.Audio
/// should produce the same mean level as the no-processor path
/// within polar↔Cartesian round-trip tolerance.
@Test func identityClosureRoundTripEquivalentToNoProcessor() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let dcInput: Double = 0.4
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let chainNone: SpectralChain.Audio = SpectralChain.Audio(input: dcInput, fftSize: fftSize, hopSize: hopSize)
let identity: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { _ in }
let chainIdentity: SpectralChain.Audio = SpectralChain.Audio(
input: dcInput, fftSize: fftSize, hopSize: hopSize, stages: [.mono(identity)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sumNone: Double = 0.0
var sumId: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let outNone: [[Double]] = chainNone.calculatedSamples(graph: g, count: blockSize)
let outId: [[Double]] = chainIdentity.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize {
sumNone += outNone[0][i]
sumId += outId[0][i]
}
}
advanceBlock(engine)
}
let n: Double = Double(measureBlocks * blockSize)
let meanNone: Double = sumNone / n
let meanId: Double = sumId / n
// Both should have the same mean. Allow 0.01 for round-trip trig error.
#expect(abs(meanNone - meanId) < 0.01,
"Identity closure shifted mean from \(meanNone) to \(meanId)")
}
/// Complex all-zero closure: zeroing all Cartesian bins produces silence.
@Test func zeroClearAllBinsProducesSilence() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let sineFreq: Double = 880.0
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
let osc: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let mute: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { ctx in
for i: Int in 0..<ctx.binCount {
ctx.real[i] = 0
ctx.imag[i] = 0
}
}
let chain: SpectralChain.Audio = SpectralChain.Audio(
input: osc, fftSize: fftSize, hopSize: hopSize, stages: [.mono(mute)]
)
let warmUpBlocks: Int = 4
let measureBlocks: Int = 4
var sumSq: Double = 0.0
for block: Int in 0..<(warmUpBlocks + measureBlocks) {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chain.calculatedSamples(graph: g, count: blockSize)
if block >= warmUpBlocks {
for i: Int in 0..<blockSize { let s: Double = out[0][i]; sumSq += s * s }
}
advanceBlock(engine)
}
let rms: Double = (sumSq / Double(measureBlocks * blockSize)).squareRoot()
// Spectral mute — all Cartesian bins zeroed. Output should be ≈ silence.
#expect(rms < 0.01, "Zeroed complex closure should produce near-silence, got RMS \(rms)")
}
/// Complex spectral freeze: latch real/imag arrays on the first hop
/// using pre-allocated scratch (RT-safe), then replay each subsequent hop.
/// After the input goes silent, the output should sustain the latched spectrum.
@Test func complexFreezeLatchesSpectrum() throws {
let fftSize: Int = 64
let hopSize: Int = 32
let blockSize: Int = hopSize
let sineFreq: Double = 440.0
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize)
try engine.start()
defer { engine.stop() }
// Pre-allocate latch buffers (non-RT allocation).
let halfSize: Int = fftSize / 2
let latchReal: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
let latchImag: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
latchReal.initialize(repeating: 0, count: halfSize)
latchImag.initialize(repeating: 0, count: halfSize)
defer {
latchReal.deinitialize(count: halfSize)
latchReal.deallocate()
latchImag.deinitialize(count: halfSize)
latchImag.deallocate()
}
var latched: Bool = false
let freeze: SpectralComplexClosure = SpectralComplexClosure(
fftSize: fftSize, hopSize: hopSize, sampleRate: engine.sampleRate
) { ctx in
if !latched {
// Capture first frame into pre-allocated scratch.
for i: Int in 0..<ctx.binCount {
latchReal[i] = ctx.real[i]
latchImag[i] = ctx.imag[i]
}
latched = true
} else {
// Replay latched frame.
for i: Int in 0..<ctx.binCount {
ctx.real[i] = latchReal[i]
ctx.imag[i] = latchImag[i]
}
}
}
// Warm up: drive several blocks with the oscillator so the freeze
// latches a real non-silent spectrum.
let oscForFreeze: OscSin.Audio = OscSin.Audio(freq: sineFreq)
let chainFreeze: SpectralChain.Audio = SpectralChain.Audio(
input: oscForFreeze, fftSize: fftSize, hopSize: hopSize, stages: [.mono(freeze)]
)
let warmUpBlocks: Int = 4
for _ in 0..<warmUpBlocks {
let g: SynthGraph = makeSynthGraph(engine: engine)
_ = chainFreeze.calculatedSamples(graph: g, count: blockSize)
advanceBlock(engine)
}
// Measure RMS over several blocks — latched spectrum should be sustained.
let measureBlocks: Int = 4
var sumSq: Double = 0.0
for _ in 0..<measureBlocks {
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [[Double]] = chainFreeze.calculatedSamples(graph: g, count: blockSize)
for i: Int in 0..<blockSize { let s: Double = out[0][i]; sumSq += s * s }
advanceBlock(engine)
}
let rms: Double = (sumSq / Double(measureBlocks * blockSize)).squareRoot()
// Frozen spectrum should produce non-silence.
#expect(rms > 0.001, "Frozen complex spectrum produced near-silence (RMS \(rms)); expected sustained tone")
}
}