316 lines
15 KiB
Swift
316 lines
15 KiB
Swift
// AudioRateInputTests.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Foundation
|
||
import Testing
|
||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||
|
||
// MARK: - DFT helper
|
||
|
||
/// Compute normalised DFT magnitude at a single frequency — O(N). Used for sideband detection.
|
||
private func dftMagnitude(samples: [Double], freq: Double, sampleRate: Double) -> Double {
|
||
let n: Int = samples.count
|
||
guard n > 0 else { return 0 }
|
||
var real: Double = 0.0
|
||
var imag: Double = 0.0
|
||
for i: Int in 0..<n {
|
||
let phase: Double = 2.0 * Double.pi * freq * Double(i) / sampleRate
|
||
real += Double(samples[i]) * cos(phase)
|
||
imag -= Double(samples[i]) * sin(phase)
|
||
}
|
||
return sqrt(real * real + imag * imag) / Double(n)
|
||
}
|
||
|
||
/// Collect `totalSamples` of output from a generator across multiple blocks.
|
||
private func collectSamples(
|
||
_ gen: any Generator,
|
||
engine: SynthesisEngine,
|
||
totalSamples: Int
|
||
) -> [Double] {
|
||
let blockSize: Int = engine.blockSize
|
||
var output: [Double] = []
|
||
output.reserveCapacity(totalSamples)
|
||
while output.count < totalSamples {
|
||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||
let needed: Int = min(blockSize, totalSamples - output.count)
|
||
let block: [Double] = gen.calculatedSamples(graph: g, count: blockSize)[0]
|
||
output += block.prefix(needed)
|
||
advanceBlock(engine)
|
||
}
|
||
return output
|
||
}
|
||
|
||
// MARK: - AudioRateInput suite
|
||
|
||
@Suite("AudioRateInput")
|
||
struct AudioRateInputTests {
|
||
|
||
let engine: SynthesisEngine
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||
|
||
// MARK: OscSin
|
||
|
||
@Test func oscSinScalarAndConstantGeneratorInputMatch() {
|
||
let count: Int = 64
|
||
let oscScalar: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let oscConst: OscSin.Audio = OscSin.Audio(freq: ConstantGeneratorInput(440.0))
|
||
let s1: [Double] = oscScalar.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let s2: [Double] = oscConst.calculatedSamples(graph: graph, count: count)[0]
|
||
for i: Int in 0..<count {
|
||
#expect(abs(Double(s1[i]) - Double(s2[i])) < 1e-5,
|
||
"sample \(i): scalar=\(s1[i]) const=\(s2[i])")
|
||
}
|
||
}
|
||
|
||
@Test func oscSinGeneratorFreqDiffersFromScalar() {
|
||
let count: Int = 64
|
||
let carrierFreq: Double = 440.0
|
||
let modDepth: Double = 200.0
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
let fmOsc: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||
let constOsc: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
|
||
let fmSamples: [Double] = fmOsc.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = constOsc.calculatedSamples(graph: graph, count: count)[0]
|
||
|
||
let maxDiff: Double = (0..<count).map { abs(Double(fmSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||
#expect(maxDiff > 0.01, "FM-modulated OscSin should differ from constant-freq version")
|
||
}
|
||
|
||
@Test func oscSinGeneratorFreqRateIsAudio() {
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let carrier: OscSin.Audio = OscSin.Audio(freq: modulator * 200 + 440)
|
||
#expect(carrier.rate == .audio)
|
||
}
|
||
|
||
// MARK: OscTable
|
||
|
||
@Test func oscTableGeneratorFreqDiffersFromScalar() {
|
||
let count: Int = 64
|
||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||
table.fillSine()
|
||
let carrierFreq: Double = 440.0
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
let fmOsc: OscTable.Audio = OscTable.Audio(table: table, freq: modulator * 200 + carrierFreq)
|
||
let constOsc: OscTable.Audio = OscTable.Audio(table: table, freq: carrierFreq)
|
||
|
||
let fmSamples: [Double] = fmOsc.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = constOsc.calculatedSamples(graph: graph, count: count)[0]
|
||
|
||
let maxDiff: Double = (0..<count).map { abs(Double(fmSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||
#expect(maxDiff > 0.01, "FM-modulated OscTable should differ from constant-freq version")
|
||
}
|
||
|
||
@Test func oscTableScalarAndConstantGeneratorMatch() {
|
||
let count: Int = 64
|
||
let table: LyrebirdBuffer = LyrebirdBuffer(count: 1024)
|
||
table.fillSine()
|
||
let oscScalar: OscTable.Audio = OscTable.Audio(table: table, freq: 440.0)
|
||
let oscConst: OscTable.Audio = OscTable.Audio(table: table, freq: ConstantGeneratorInput(440.0))
|
||
let s1: [Double] = oscScalar.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let s2: [Double] = oscConst.calculatedSamples(graph: graph, count: count)[0]
|
||
for i: Int in 0..<count {
|
||
#expect(abs(Double(s1[i]) - Double(s2[i])) < 1e-4,
|
||
"sample \(i): scalar=\(s1[i]) const=\(s2[i])")
|
||
}
|
||
}
|
||
|
||
// MARK: Impulse
|
||
|
||
@Test func impulseGeneratorFreqProducesFiniteOutput() {
|
||
let count: Int = 64
|
||
let freqMod: BinaryOpGenerator = OscSin.Audio(freq: 4.0) * 2.0 + 4.0
|
||
let imp: Impulse.Audio = Impulse.Audio(freq: freqMod)
|
||
let samples: [Double] = imp.calculatedSamples(graph: graph, count: count)[0]
|
||
#expect(samples.prefix(count).allSatisfy { $0.isFinite })
|
||
}
|
||
|
||
@Test func impulseGeneratorFreqDiffersFromScalar() {
|
||
let count: Int = 64
|
||
let sampleRate: Double = Double(engine.sampleRate)
|
||
let baseFreq: Double = sampleRate / 8 // fires every 8 samples at 1x
|
||
let modDepth: Double = sampleRate / 32 // large enough to shift timing
|
||
// OscSin completes a half-cycle over the block, sweeping freq up and back.
|
||
// The varying phase accumulation produces different impulse positions than constant baseFreq.
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: sampleRate / 128.0)
|
||
let impMod: Impulse.Audio = Impulse.Audio(freq: modulator * modDepth + baseFreq)
|
||
let impConst: Impulse.Audio = Impulse.Audio(freq: baseFreq)
|
||
let modSamples: [Double] = impMod.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = impConst.calculatedSamples(graph: graph, count: count)[0]
|
||
#expect(modSamples.prefix(count).allSatisfy { $0.isFinite })
|
||
#expect(constSamples.prefix(count).allSatisfy { $0.isFinite })
|
||
#expect(modSamples != constSamples,
|
||
"audio-rate freq path should produce different impulse timing than scalar path")
|
||
}
|
||
|
||
// MARK: FirstOrderSection
|
||
|
||
@Test func firstOrderSectionGeneratorCoefficientChangesOutput() {
|
||
let count: Int = 64
|
||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
// Audio-rate a0 modulated by a slow sine — should change the output vs constant a0
|
||
let a0Mod: BinaryOpGenerator = OscSin.Audio(freq: 1.0) * 0.05 + 0.1 // a0 in [0.05, 0.15]
|
||
let filterMod: FirstOrderSection = FirstOrderSection(input: signal, a0: a0Mod, a1: 0.0, b1: 0.9)
|
||
let filterConst: FirstOrderSection = FirstOrderSection(input: OscSin.Audio(freq: 440.0), a0: 0.1, a1: 0.0, b1: 0.9)
|
||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||
#expect(maxDiff > 0.0, "Audio-rate coefficient filter should differ from constant-coefficient version")
|
||
}
|
||
|
||
// MARK: SecondOrderSection
|
||
|
||
@Test func secondOrderSectionGeneratorCoefficientChangesOutput() {
|
||
let count: Int = 64
|
||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let a0Mod: BinaryOpGenerator = OscSin.Audio(freq: 2.0) * 0.1 + 0.5
|
||
let filterMod: SecondOrderSection = SecondOrderSection(input: signal, a0: a0Mod, a1: 0.0, a2: 0.0, b1: 0.0, b2: 0.0)
|
||
let filterConst: SecondOrderSection = SecondOrderSection(input: OscSin.Audio(freq: 440.0), a0: 0.5, a1: 0.0, a2: 0.0, b1: 0.0, b2: 0.0)
|
||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||
#expect(maxDiff > 0.0)
|
||
}
|
||
|
||
// MARK: RBJBandPass
|
||
|
||
@Test func rbjBandPassGeneratorFreqChangesOutput() {
|
||
let count: Int = 64
|
||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let freqMod: BinaryOpGenerator = OscSin.Audio(freq: 1.0) * 200.0 + 1000.0 // sweeping 800–1200 Hz
|
||
let filterMod: RBJBandPass.Audio = RBJBandPass.Audio(input: signal, freq: freqMod, bandwidth: 1.0)
|
||
let filterConst: RBJBandPass.Audio = RBJBandPass.Audio(input: OscSin.Audio(freq: 440.0), freq: 1000.0, bandwidth: 1.0)
|
||
let modSamples: [Double] = filterMod.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let constSamples: [Double] = filterConst.calculatedSamples(graph: graph, count: count)[0]
|
||
let maxDiff: Double = (0..<count).map { abs(Double(modSamples[$0]) - Double(constSamples[$0])) }.max() ?? 0
|
||
#expect(maxDiff > 0.0, "Audio-rate swept RBJ filter should differ from fixed-freq version")
|
||
}
|
||
|
||
// MARK: DelayLine
|
||
|
||
@Test func delayLineGeneratorDelayProducesFiniteOutput() {
|
||
let count: Int = 64
|
||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
let delayMod: BinaryOpGenerator = OscSin.Audio(freq: 2.0) * 0.005 + 0.01
|
||
let delay: DelayLine = DelayLine(input: signal, maxDelay: 0.1, delay: delayMod, sampleRate: 44100)
|
||
let samples: [Double] = delay.calculatedSamples(graph: graph, count: count)[0]
|
||
#expect(samples.prefix(count).allSatisfy { $0.isFinite })
|
||
}
|
||
|
||
@Test func delayLineGeneratorDelayDiffersFromScalar() {
|
||
let count: Int = 64
|
||
let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
|
||
// Use a large-amplitude modulator so the varying delay is clearly different from fixed
|
||
let delayMod: ConstantGeneratorInput = ConstantGeneratorInput(0.005) // constant via Generator path
|
||
let delayConst: Double = 0.005 as Double // literal scalar path
|
||
let delayLineGen: DelayLine = DelayLine(input: signal, maxDelay: 0.1, delay: delayMod, sampleRate: 44100)
|
||
let delayLineLit: DelayLine = DelayLine(input: OscSin.Audio(freq: 440.0), maxDelay: 0.1, delay: delayConst, sampleRate: 44100)
|
||
let genSamples: [Double] = delayLineGen.calculatedSamples(graph: graph, count: count)[0]
|
||
advanceBlock(engine)
|
||
let litSamples: [Double] = delayLineLit.calculatedSamples(graph: graph, count: count)[0]
|
||
// Both should produce finite, non-silent output (signal is passing through the delay)
|
||
#expect(genSamples.prefix(count).allSatisfy { $0.isFinite })
|
||
#expect(litSamples.prefix(count).allSatisfy { $0.isFinite })
|
||
}
|
||
}
|
||
|
||
// MARK: - FMSynthesis suite
|
||
|
||
@Suite("FMSynthesis")
|
||
struct FMSynthesisTests {
|
||
|
||
let sampleRate: Double = 44100
|
||
let blockSize: Int = 256
|
||
let engine: SynthesisEngine
|
||
|
||
init() throws {
|
||
engine = makeTestEngine(blockSize: 256, sampleRate: 44100)
|
||
try engine.start()
|
||
}
|
||
|
||
var graph: SynthGraph { makeSynthGraph(engine: engine) }
|
||
|
||
@Test func fmOutputDiffersFromConstantFrequencyOscillator() {
|
||
let carrierFreq: Double = 440.0
|
||
let modDepth: Double = 200.0
|
||
let totalSamples: Int = 1024
|
||
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
let fmCarrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||
let constCarrier: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
|
||
let fmSamples: [Double] = collectSamples(fmCarrier, engine: engine, totalSamples: totalSamples)
|
||
let constSamples: [Double] = collectSamples(constCarrier, engine: engine, totalSamples: totalSamples)
|
||
|
||
let rmsSquared: Double = (0..<totalSamples).map {
|
||
pow(Double(fmSamples[$0]) - Double(constSamples[$0]), 2)
|
||
}.reduce(0, +)
|
||
let rmsDiff: Double = sqrt(rmsSquared / Double(totalSamples))
|
||
|
||
// FM with modIndex ≈ 0.45 produces sidebands with ~22% amplitude → significant RMS difference
|
||
#expect(rmsDiff > 0.05, "FM output should differ substantially from constant-freq version (rmsDiff=\(rmsDiff))")
|
||
}
|
||
|
||
@Test func fmHasEnergyAtSidebandFrequency() {
|
||
// modIndex = 1.0 → J_1(1.0) ≈ 0.44 (strong first sideband)
|
||
let carrierFreq: Double = 441.0 // 100 samples/cycle at 44100 Hz
|
||
let modulatorFreq: Double = 441.0
|
||
let modDepth: Double = 441.0 // modIndex = depth / carrier = 1.0
|
||
|
||
let totalSamples: Int = 8820 // 88.2 cycles at 100 samples/cycle
|
||
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: modulatorFreq)
|
||
let fmCarrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||
let constCarrier: OscSin.Audio = OscSin.Audio(freq: carrierFreq)
|
||
|
||
let fmSamples: [Double] = collectSamples(fmCarrier, engine: engine, totalSamples: totalSamples)
|
||
let constSamples: [Double] = collectSamples(constCarrier, engine: engine, totalSamples: totalSamples)
|
||
|
||
// First upper sideband at carrier + modulator = 882 Hz
|
||
let sidebandFreq: Double = 882.0
|
||
let fmSidebandMag: Double = dftMagnitude(samples: fmSamples, freq: sidebandFreq, sampleRate: sampleRate)
|
||
let constSidebandMag: Double = dftMagnitude(samples: constSamples, freq: sidebandFreq, sampleRate: sampleRate)
|
||
|
||
// FM should have strong sideband energy (J_1(1.0) ≈ 0.44 → expect > 0.1)
|
||
#expect(fmSidebandMag > 0.1,
|
||
"FM output should contain sideband energy at \(sidebandFreq) Hz (mag=\(fmSidebandMag))")
|
||
// Constant sine should have negligible energy at sideband frequency
|
||
#expect(constSidebandMag < 0.05,
|
||
"Constant-freq sine should have no sideband energy (mag=\(constSidebandMag))")
|
||
}
|
||
|
||
@Test func fmSynthExampleBuilds() {
|
||
// Smoke-test the canonical FM synthesis example.
|
||
class FMSynth: SynthesizerBase {
|
||
override func build() {
|
||
let modulatorFreq: Double = 440.0
|
||
let carrierFreq: Double = 440.0
|
||
let modDepth: Double = 200.0
|
||
let modulator: OscSin.Audio = OscSin.Audio(freq: modulatorFreq)
|
||
let carrier: OscSin.Audio = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
|
||
output(bus: 0, source: carrier * 0.3)
|
||
output(bus: 1, source: carrier * 0.3)
|
||
}
|
||
}
|
||
let synth: FMSynth = FMSynth()
|
||
synth.build()
|
||
}
|
||
}
|