// ResonatingFilterTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import Testing @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // MARK: - Local DFT helper private func dftMag(samples: [Double], freq: Double, sampleRate: Double) -> Double { let n: Int = samples.count guard n > 0 else { return 0 } var re: Double = 0.0, im = 0.0 for i: Int in 0.. 0.001) #expect(samples.allSatisfy { $0.isFinite }) } @Test func longerDecayTimeDecaysSlower() throws { // The same impulse with a longer decayTime should have more energy remaining after the same interval. let impulse1: Impulse.Audio = Impulse.Audio(freq: 1.0) let r1: ResonatingFilter = ResonatingFilter(input: impulse1, freq: 440.0, decayTime: 0.05) let s1: [Double] = collectBlocks(r1, engine: engine, blocks: 30) let rms1: Double = rmsValue(Array(s1.suffix(10 * engine.blockSize))) let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) try engine2.start() let impulse2: Impulse.Audio = Impulse.Audio(freq: 1.0) let r2: ResonatingFilter = ResonatingFilter(input: impulse2, freq: 440.0, decayTime: 0.5) let s2: [Double] = collectBlocks(r2, engine: engine2, blocks: 30) let rms2: Double = rmsValue(Array(s2.suffix(10 * engine2.blockSize))) // Longer decay → more energy remaining late in the signal #expect(rms2 > rms1) } @Test func dcInputDecays() { // With DC input and feedback, the output should eventually decay rather than grow. let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let resonator: ResonatingFilter = ResonatingFilter(input: dc, freq: 440.0, decayTime: 0.1) let samples: [Double] = collectBlocks(resonator, engine: engine, blocks: 50) #expect(samples.allSatisfy { $0.isFinite }) } @Test func audioRateFreqModNoCrash() { let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0) let freqGen: BinaryOpGenerator = lfo * 200.0 + 440.0 let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let resonator: ResonatingFilter = ResonatingFilter(input: impulse, freq: freqGen, decayTime: 0.2) let samples: [Double] = collectBlocks(resonator, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func audioRateDecayModNoCrash() { let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5) let decayGen: BinaryOpGenerator = lfo * 0.1 + 0.2 let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let resonator: ResonatingFilter = ResonatingFilter(input: impulse, freq: 440.0, decayTime: decayGen) let samples: [Double] = collectBlocks(resonator, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func participatesInFanOutCache() { let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let resonator: ResonatingFilter = ResonatingFilter(input: impulse, freq: 440.0, decayTime: 0.5) let g: SynthGraph = makeSynthGraph(engine: engine) let r1: [[Double]] = resonator.calculatedSamples(graph: g, count: engine.blockSize) let r2: [[Double]] = resonator.calculatedSamples(graph: g, count: engine.blockSize) #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) } @Test func denormalsDoNotAccumulate() { // After a brief excitation the resonator tail should remain finite and not subnormal. let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let resonator: ResonatingFilter = ResonatingFilter(input: impulse, freq: 440.0, decayTime: 0.01) let samples: [Double] = collectBlocks(resonator, engine: engine, blocks: 200) #expect(samples.allSatisfy { $0.isFinite }) #expect(samples.allSatisfy { !$0.isSubnormal }) } @Test func deterministicFirstSampleMatchesFormula() { // Step input, zero initial state. // First output = b0 = 1 - R, where R = exp(log(0.001) / (decayTime * sr)). let decayTime: Double = 1.0 let log0001: Double = log(0.001) let R: Double = exp(log0001 / (decayTime * sr)) let expectedFirstSample: Double = 1.0 - R // b0 * x[0], x[0] = 1, y1=y2=0 let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let resonator: ResonatingFilter = ResonatingFilter(input: input, freq: 440.0, decayTime: decayTime) let g: SynthGraph = makeSynthGraph(engine: engine) let samples: [[Double]] = resonator.calculatedSamples(graph: g, count: engine.blockSize) #expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10) } } // MARK: - RingingFilterTests @Suite("RingingFilter") struct RingingFilterTests { let engine: SynthesisEngine let sr: Double = 44100 init() throws { engine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() } @Test func dftPeakAtFreq() { // Drive with noise; DFT peak should be at the resonant frequency. let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ringer: RingingFilter = RingingFilter(input: noise, freq: 1000.0, bandwidth: 50.0) let samples: [Double] = collectBlocks(ringer, engine: engine, blocks: 200) let magAt: Double = dftMag(samples: Array(samples.suffix(100 * engine.blockSize)), freq: 1000, sampleRate: sr) let magBelow: Double = dftMag(samples: Array(samples.suffix(100 * engine.blockSize)), freq: 200, sampleRate: sr) let magAbove: Double = dftMag(samples: Array(samples.suffix(100 * engine.blockSize)), freq: 5000, sampleRate: sr) #expect(magAt > magBelow) #expect(magAt > magAbove) } @Test func narrowerBandwidthRingsLonger() throws { // Narrower bandwidth → higher Q → longer ring. let impulse1: Impulse.Audio = Impulse.Audio(freq: 1.0) let wide: RingingFilter = RingingFilter(input: impulse1, freq: 440.0, bandwidth: 200.0) let s1: [Double] = collectBlocks(wide, engine: engine, blocks: 80) let rms1: Double = rmsValue(Array(s1.suffix(20 * engine.blockSize))) let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) try engine2.start() let impulse2: Impulse.Audio = Impulse.Audio(freq: 1.0) let narrow: RingingFilter = RingingFilter(input: impulse2, freq: 440.0, bandwidth: 10.0) let s2: [Double] = collectBlocks(narrow, engine: engine2, blocks: 80) let rms2: Double = rmsValue(Array(s2.suffix(20 * engine2.blockSize))) #expect(rms2 > rms1) } @Test func finiteOutputAllSamples() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ringer: RingingFilter = RingingFilter(input: noise, freq: 440.0, bandwidth: 20.0) let samples: [Double] = collectBlocks(ringer, engine: engine, blocks: 30) #expect(samples.allSatisfy { $0.isFinite }) } @Test func audioRateFreqModNoCrash() { let lfo: OscSin.Audio = OscSin.Audio(freq: 1.0) let freqGen: BinaryOpGenerator = lfo * 200.0 + 600.0 let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ringer: RingingFilter = RingingFilter(input: noise, freq: freqGen, bandwidth: 30.0) let samples: [Double] = collectBlocks(ringer, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func audioRateBandwidthModNoCrash() { let lfo: OscSin.Audio = OscSin.Audio(freq: 0.3) let bwGen: BinaryOpGenerator = lfo * 10.0 + 30.0 // sweeps 20–40 Hz bandwidth let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ringer: RingingFilter = RingingFilter(input: noise, freq: 440.0, bandwidth: bwGen) let samples: [Double] = collectBlocks(ringer, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func participatesInFanOutCache() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ringer: RingingFilter = RingingFilter(input: noise, freq: 440.0, bandwidth: 20.0) let g: SynthGraph = makeSynthGraph(engine: engine) let r1: [[Double]] = ringer.calculatedSamples(graph: g, count: engine.blockSize) let r2: [[Double]] = ringer.calculatedSamples(graph: g, count: engine.blockSize) #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) } @Test func denormalsDoNotAccumulate() { let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let ringer: RingingFilter = RingingFilter(input: impulse, freq: 440.0, bandwidth: 500.0) let samples: [Double] = collectBlocks(ringer, engine: engine, blocks: 200) #expect(samples.allSatisfy { $0.isFinite }) #expect(samples.allSatisfy { !$0.isSubnormal }) } @Test func deterministicFirstSampleMatchesFormula() { // Step input, zero initial state. // R = max(-0.9999, min(1 - π·bw/sr, 0.9999)) // b0 = (1-R²)·sin(w0)/2 // First output = b0 · x[0] = b0, since y1=y2=0. let bw: Double = 20.0 let R: Double = min(1.0 - Double.pi * bw / sr, 0.9999) let w0: Double = 2.0 * Double.pi * 440.0 / sr let expectedFirstSample: Double = (1.0 - R * R) * sin(w0) / 2.0 let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let ringer: RingingFilter = RingingFilter(input: input, freq: 440.0, bandwidth: bw) let g: SynthGraph = makeSynthGraph(engine: engine) let samples: [[Double]] = ringer.calculatedSamples(graph: g, count: engine.blockSize) #expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10) } } // MARK: - CombFilterTests @Suite("CombFilter") struct CombFilterTests { let engine: SynthesisEngine let sr: Double = 44100 init() throws { engine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() } @Test func spectralCombEnergyAtFundamental() { // A comb filter with delay D has resonances at multiples of 1/D Hz. // Feed white noise and verify DFT magnitude at the fundamental comb frequency. let delayTime: Double = 0.01 // 100 Hz fundamental let noise: WhiteNoise.Audio = WhiteNoise.Audio() let comb: CombFilter = CombFilter(input: noise, maxDelay: 0.1, delay: delayTime, decayTime: 1.0, sampleRate: sr) let samples: [Double] = collectBlocks(comb, engine: engine, blocks: 200) let tail: [Double] = Array(samples.suffix(100 * engine.blockSize)) let magAt100: Double = dftMag(samples: tail, freq: 100, sampleRate: sr) let magAt200: Double = dftMag(samples: tail, freq: 200, sampleRate: sr) let magAt50: Double = dftMag(samples: tail, freq: 50, sampleRate: sr) // Comb peaks at multiples of 1/delay Hz; both 100 and 200 Hz should exceed off-comb 50 Hz. #expect(magAt100 > magAt50) #expect(magAt200 > magAt50) } @Test func finiteOutputAllSamples() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let comb: CombFilter = CombFilter(input: noise, maxDelay: 0.1, delay: 0.02, decayTime: 0.5, sampleRate: sr) let samples: [Double] = collectBlocks(comb, engine: engine, blocks: 30) #expect(samples.allSatisfy { $0.isFinite }) } @Test func allInterpolationModesNoCrash() { let modes: [DelayInterpolation] = [.none, .linear, .cubic, .allpass] for mode: DelayInterpolation in modes { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let comb: CombFilter = CombFilter(input: noise, maxDelay: 0.1, delay: 0.02, decayTime: 0.5, sampleRate: sr, interpolation: mode) let samples: [Double] = collectBlocks(comb, engine: engine, blocks: 10) #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) produced non-finite output") #expect(!samples.allSatisfy { $0 == 0 }, "mode \(mode) produced all-zero output") } } @Test func audioRateDelayModNoCrash() { // Audio-rate delay modulation — exercises per-sample coefficient path. let lfo: OscSin.Audio = OscSin.Audio(freq: 5.0) let delayGen: BinaryOpGenerator = lfo * 0.005 + 0.02 // sweeps 15–25 ms let noise: WhiteNoise.Audio = WhiteNoise.Audio() let comb: CombFilter = CombFilter(input: noise, maxDelay: 0.1, delay: delayGen, decayTime: 0.5, sampleRate: sr) let samples: [Double] = collectBlocks(comb, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func denormalsDoNotAccumulate() { let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let comb: CombFilter = CombFilter(input: impulse, maxDelay: 0.1, delay: 0.02, decayTime: 0.05, sampleRate: sr) let samples: [Double] = collectBlocks(comb, engine: engine, blocks: 300) #expect(samples.allSatisfy { $0.isFinite }) #expect(samples.allSatisfy { !$0.isSubnormal }) } @Test func participatesInFanOutCache() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let comb: CombFilter = CombFilter(input: noise, maxDelay: 0.1, delay: 0.02, decayTime: 0.5, sampleRate: sr) let g: SynthGraph = makeSynthGraph(engine: engine) let r1: [[Double]] = comb.calculatedSamples(graph: g, count: engine.blockSize) let r2: [[Double]] = comb.calculatedSamples(graph: g, count: engine.blockSize) #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) } @Test func deterministicFirstSamplesMatchFormula() { // Step input (all 1.0s), integer delay D = Int(delay*sr), no-interp mode. // For n < D: y[n] = x[n] + g*y[n-D] = 1 + g*0 = 1.0 // g = exp(log(0.001) * delay / decayTime) let delayTime: Double = 0.01 // D = 441 samples at 44100 Hz let decayTime: Double = 1.0 let log0001: Double = log(0.001) let g: Double = exp(log0001 * delayTime / decayTime) _ = g // used implicitly: for n < D, output = 1.0 let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let comb: CombFilter = CombFilter(input: input, maxDelay: 0.1, delay: delayTime, decayTime: decayTime, sampleRate: sr, interpolation: .none) let synthGraph: SynthGraph = makeSynthGraph(engine: engine) let samples: [[Double]] = comb.calculatedSamples(graph: synthGraph, count: engine.blockSize) // First blockSize (64) samples are well within D=441, so all equal 1.0 for i: Int in 0.. 0.3 && rmsOut < 1.0) } @Test func deterministicFirstSampleMatchesFormula() { // Step input (all 1.0s), integer delay D, no-interp mode. // y[n] = -g*x[n] + x[n-D] + g*y[n-D] // For n < D: x[n-D] = 0, y[n-D] = 0, so y[n] = -g * 1.0 = -g let delayTime: Double = 0.01 // D = 441 samples at 44100 Hz; blockSize=64 < 441 let decayTime: Double = 1.0 let log0001: Double = log(0.001) let expectedG: Double = exp(log0001 * delayTime / decayTime) let expectedFirstSample: Double = -expectedG // y[0] = -g * x[0] let input: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let ap: AllpassFilter = AllpassFilter(input: input, maxDelay: 0.1, delay: delayTime, decayTime: decayTime, sampleRate: sr, interpolation: .none) let g: SynthGraph = makeSynthGraph(engine: engine) let samples: [[Double]] = ap.calculatedSamples(graph: g, count: engine.blockSize) #expect(abs(Double(samples[0][0]) - expectedFirstSample) < 1e-10) } @Test func dftMagnitudeApproximatelyFlat() throws { // Drive with a fixed sine at two different frequencies; both should pass with similar magnitude. let delay: Double = 0.005 let decayTime: Double = 0.05 let sine1: OscSin.Audio = OscSin.Audio(freq: 440.0) let ap1: AllpassFilter = AllpassFilter(input: sine1, maxDelay: 0.1, delay: delay, decayTime: decayTime, sampleRate: sr) let s1: [Double] = collectBlocks(ap1, engine: engine, blocks: 100) let mag1: Double = dftMag(samples: Array(s1.suffix(50 * engine.blockSize)), freq: 440, sampleRate: sr) let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) try engine2.start() let sine2: OscSin.Audio = OscSin.Audio(freq: 2000.0) let ap2: AllpassFilter = AllpassFilter(input: sine2, maxDelay: 0.1, delay: delay, decayTime: decayTime, sampleRate: sr) let s2: [Double] = collectBlocks(ap2, engine: engine2, blocks: 100) let mag2: Double = dftMag(samples: Array(s2.suffix(50 * engine2.blockSize)), freq: 2000, sampleRate: sr) // Both should pass with substantial magnitude (within 10× of each other) #expect(mag1 > 0) #expect(mag2 > 0) if mag1 > 0 && mag2 > 0 { let ratio: Double = mag1 / mag2 #expect(ratio > 0.1 && ratio < 10.0) } } @Test func finiteOutputAllSamples() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let allpass: AllpassFilter = AllpassFilter(input: noise, maxDelay: 0.05, delay: 0.01, decayTime: 0.5, sampleRate: sr) let samples: [Double] = collectBlocks(allpass, engine: engine, blocks: 30) #expect(samples.allSatisfy { $0.isFinite }) } @Test func allInterpolationModesNoCrash() { let modes: [DelayInterpolation] = [.none, .linear, .cubic, .allpass] for mode: DelayInterpolation in modes { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ap: AllpassFilter = AllpassFilter(input: noise, maxDelay: 0.05, delay: 0.01, decayTime: 0.5, sampleRate: sr, interpolation: mode) let samples: [Double] = collectBlocks(ap, engine: engine, blocks: 10) #expect(samples.allSatisfy { $0.isFinite }, "mode \(mode) produced non-finite output") } } @Test func audioRateDelayModNoCrash() { let lfo: OscSin.Audio = OscSin.Audio(freq: 3.0) let delayGen: BinaryOpGenerator = lfo * 0.002 + 0.01 let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ap: AllpassFilter = AllpassFilter(input: noise, maxDelay: 0.05, delay: delayGen, decayTime: 0.5, sampleRate: sr) let samples: [Double] = collectBlocks(ap, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) } @Test func denormalsDoNotAccumulate() { let impulse: Impulse.Audio = Impulse.Audio(freq: 1.0) let ap: AllpassFilter = AllpassFilter(input: impulse, maxDelay: 0.05, delay: 0.01, decayTime: 0.05, sampleRate: sr) let samples: [Double] = collectBlocks(ap, engine: engine, blocks: 300) #expect(samples.allSatisfy { $0.isFinite }) #expect(samples.allSatisfy { !$0.isSubnormal }) } @Test func participatesInFanOutCache() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let ap: AllpassFilter = AllpassFilter(input: noise, maxDelay: 0.05, delay: 0.01, decayTime: 0.5, sampleRate: sr) let g: SynthGraph = makeSynthGraph(engine: engine) let r1: [[Double]] = ap.calculatedSamples(graph: g, count: engine.blockSize) let r2: [[Double]] = ap.calculatedSamples(graph: g, count: engine.blockSize) #expect(r1[0].prefix(engine.blockSize).elementsEqual(r2[0].prefix(engine.blockSize))) } } // MARK: - DelayInterpolation allpass mode @Suite("DelayInterpolationAllpass") struct DelayInterpolationAllpassTests { let engine: SynthesisEngine let sr: Double = 44100 init() throws { engine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() } @Test func delayLineAllpassNoCrash() { let noise: WhiteNoise.Audio = WhiteNoise.Audio() let dl: DelayLine = DelayLine(input: noise, maxDelay: 0.1, delay: 0.023, sampleRate: sr, interpolation: .allpass) let samples: [Double] = collectBlocks(dl, engine: engine, blocks: 20) #expect(samples.allSatisfy { $0.isFinite }) #expect(!samples.allSatisfy { $0 == 0 }) } @Test func allpassOutputDiffersFromLinear() throws { // Allpass and linear interpolation should produce different output for fractional delay. let seed: UInt64 = 42 _ = seed // WhiteNoise uses PRNG seeded by clock, so we just verify structural difference let noise1: WhiteNoise.Audio = WhiteNoise.Audio() let dlLinear: DelayLine = DelayLine(input: noise1, maxDelay: 0.1, delay: 0.0234, sampleRate: sr, interpolation: .linear) let s1: [Double] = collectBlocks(dlLinear, engine: engine, blocks: 5) let engine2: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: sr) try engine2.start() let noise2: WhiteNoise.Audio = WhiteNoise.Audio() let dlAllpass: DelayLine = DelayLine(input: noise2, maxDelay: 0.1, delay: 0.0234, sampleRate: sr, interpolation: .allpass) let s2: [Double] = collectBlocks(dlAllpass, engine: engine2, blocks: 5) // Both are finite; they need not be identical since inputs differ (separate WhiteNoise) #expect(s1.allSatisfy { $0.isFinite }) #expect(s2.allSatisfy { $0.isFinite }) } @Test func delayLineAllpassDeterministicSecondSampleMatchesFormula() throws { // Delay = 1.5 samples exactly → frac = 0.5, eta = (1−0.5)/(1+0.5) = 1/3. // Read happens before write each frame. // Frame 0: buffer empty → out = 0. Write input=1.0. // Frame 1: yn = buffer[0] = 1.0, ynm1 = 0, prevOut = 0 → out = (1/3)·1.0 = 1/3. let delaySecs: Double = 1.5 / sr let etaExpected: Double = (1.0 - 0.5) / (1.0 + 0.5) // 1/3 let expectedSample1: Double = etaExpected // yn=1, ynm1=0, prevOut=0 let dc: ConstantGeneratorInput = ConstantGeneratorInput(1.0) let dl: DelayLine = DelayLine(input: dc, maxDelay: 8.0 / sr, delay: delaySecs, sampleRate: sr, interpolation: .allpass) let g: SynthGraph = makeSynthGraph(engine: engine) let samples: [[Double]] = dl.calculatedSamples(graph: g, count: engine.blockSize) #expect(abs(Double(samples[0][0]) - 0.0) < 1e-10) #expect(abs(Double(samples[0][1]) - expectedSample1) < 1e-10) } }