Files
Lyrebird/Tests/LyrebirdTests/SpatialDistanceTests.swift
T
2026-06-01 18:27:40 -07:00

317 lines
13 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SpatialDistanceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("SpatialDistance")
struct SpatialDistanceTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
let blockSize: Int = 512
init() throws {
try engine.start()
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(input: 0.0, sampleRate: testSampleRate)
#expect(gen.rate == .audio)
}
// MARK: - 2. Output count
@Test func outputCountMatchesRequest() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(input: 0.0, sampleRate: testSampleRate)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
#expect(samples.count == blockSize)
}
// MARK: - 2b. Deterministic first sample (exact numeric verification)
@Test func firstSampleDeterministic() {
// Zero input, identity mul/add → first sample is exactly 0.0.
// Delay line is zero-initialised so dry=0 → delay line write of 0 → delayed=0 →
// LP state = (1-a)*0 + a*0 = 0 → output = 0 * attenuation = 0.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.0),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 1)
#expect(abs(out[0][0] - 0.0) < 1e-12,
"Zero input first sample must be exactly 0.0, got \(out[0][0])")
// With mul=2, add=1 the same chain (output 0 before mulAdd) must yield 0*2 + 1 = 1.0.
let gen2: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.0),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out2: [[Double]] = gen2.calculatedSamples(graph: graph, count: 1)
#expect(abs(out2[0][0] - 1.0) < 1e-12,
"Zero input + mul=2,add=1 first sample must be exactly 1.0, got \(out2[0][0])")
}
// MARK: - 3. Silent input → silent output
@Test func silentInputProducesSilentOutput() {
// No feedback path, so zero input → zero output.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: 0.0,
distance: 2.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allNearZero: Bool = samples.allSatisfy { abs($0) < 1e-10 }
#expect(allNearZero, "Zero input must produce near-zero output (no feedback)")
}
// MARK: - 4. First block is finite
@Test func firstBlockNotNaN() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.5),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allFinite: Bool = samples.allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples must be finite for sane parameters at distance=1.0")
}
// MARK: - 5. Larger distance attenuates output
@Test func largerDistanceAttenuatesOutput() {
// Feed several blocks to fill the delay line, then compare RMS.
let nearGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.8),
distance: 1.0,
velocity: 0.0,
sampleRate: testSampleRate
)
let farGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.8),
distance: 10.0,
velocity: 0.0,
sampleRate: testSampleRate
)
// Prime the delay lines.
for _ in 0..<5 {
_ = nearGen.calculatedSamples(graph: graph, count: blockSize)
_ = farGen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
}
let nearOut: [[Double]] = nearGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let farOut: [[Double]] = farGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let nearRms: Double = rmsValue(Array(nearOut[0].prefix(blockSize)))
let farRms: Double = rmsValue(Array(farOut[0].prefix(blockSize)))
// The far source should be materially quieter (at least half).
#expect(
farRms < 0.5 * nearRms,
"Far source (d=10) RMS \(farRms) should be < half of near source (d=1) RMS \(nearRms)"
)
}
// MARK: - 6. Larger distance lowpasses output
@Test func largerDistanceLowpassesOutput() {
// Drive an 8 kHz sine and compare high-frequency energy (via 1-sample differences)
// between near and far instances. Far should have less HF energy due to air absorption.
let freq: Double = 8000.0
let nearGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 1.0,
velocity: 0.0,
airAbsorptionCutoff: 16000.0,
sampleRate: testSampleRate
)
let farGen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 20.0,
velocity: 0.0,
airAbsorptionCutoff: 16000.0,
sampleRate: testSampleRate
)
// Prime with several blocks.
for _ in 0..<10 {
_ = nearGen.calculatedSamples(graph: graph, count: blockSize)
_ = farGen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
}
let nearSamples: [Double] = Array(nearGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)[0].prefix(blockSize))
let farSamples: [Double] = Array(farGen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)[0].prefix(blockSize))
// Crude high-pass: compute RMS of first-differences (consecutive sample deltas).
var nearDiffSumSq: Double = 0.0
var farDiffSumSq: Double = 0.0
for i: Int in 1..<blockSize {
let nd: Double = nearSamples[i] - nearSamples[i - 1]
let fd: Double = farSamples[i] - farSamples[i - 1]
nearDiffSumSq += nd * nd
farDiffSumSq += fd * fd
}
let nearHF: Double = (nearDiffSumSq / Double(blockSize - 1)).squareRoot()
let farHF: Double = (farDiffSumSq / Double(blockSize - 1)).squareRoot()
// At d=20, air absorption cutoff is (1/20)^2 × 16000 ≈ 40 Hz — very aggressive LP.
// The far HF RMS must be materially less than the near HF RMS.
#expect(
farHF < 0.5 * nearHF,
"Far source (d=20) HF energy \(farHF) should be < half of near source (d=1) HF energy \(nearHF)"
)
}
// MARK: - 7. Velocity produces pitch shift via delay change
@Test func velocityProducesPitchShiftViaDelayChange() throws {
// Feed a constant-frequency sine and count zero crossings over many blocks.
// With velocity > 0 the Doppler read-rate < 1 stretches the waveform,
// producing fewer zero crossings per unit time (lower apparent frequency).
let freq: Double = 440.0
let numBlocks: Int = 20
// Helper: count zero crossings (sign changes) in a flat sample array.
func zeroCrossings(_ s: [Double]) -> Int {
var cnt: Int = 0
for i: Int in 1..<s.count {
if (s[i - 1] < 0 && s[i] >= 0) || (s[i - 1] >= 0 && s[i] < 0) {
cnt += 1
}
}
return cnt
}
func collectSamples(velocity: Double) throws -> [Double] {
let eng: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: testSampleRate)
try eng.start()
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: freq),
distance: 5.0,
velocity: velocity,
sampleRate: testSampleRate
)
var allSamples: [Double] = []
for _ in 0..<numBlocks {
let g: SynthGraph = makeSynthGraph(engine: eng)
let out: [[Double]] = gen.calculatedSamples(graph: g, count: blockSize)
allSamples += Array(out[0].prefix(blockSize))
advanceBlock(eng)
}
eng.stop()
return allSamples
}
let noVelSamples: [Double] = try collectSamples(velocity: 0.0)
let highVelSamples: [Double] = try collectSamples(velocity: 30.0)
let crossingsNoVel: Int = zeroCrossings(noVelSamples)
let crossingsHighVel: Int = zeroCrossings(highVelSamples)
// velocity=30 m/s → readRate ≈ 0.913 → waveform stretched → fewer zero crossings.
let ratio: Double = Double(crossingsHighVel) / Double(max(crossingsNoVel, 1))
#expect(
ratio < 0.97,
"Positive velocity should reduce zero crossings (lower apparent frequency)"
)
}
// MARK: - 8. Fan-out (same segment returns identical result)
@Test func fanOutSingleEvaluation() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.4),
distance: 2.0,
sampleRate: testSampleRate
)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let s1: [Double] = Array(out1[0].prefix(blockSize))
let s2: [Double] = Array(out2[0].prefix(blockSize))
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in the same segment must return identical data")
}
// MARK: - 9. State advances once per block
@Test func stateAdvancesOncePerBlock() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: ConstantGeneratorInput(0.5),
distance: 3.0,
sampleRate: testSampleRate
)
// Two calls in the same segment — second must be a cache hit (no double-advance).
_ = gen.calculatedSamples(graph: graph, count: blockSize)
_ = gen.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
let block2: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: blockSize)
let allFinite: Bool = Array(block2[0].prefix(blockSize)).allSatisfy { $0.isFinite }
#expect(allFinite, "Block 2 output must be finite after exactly one advance")
}
// MARK: - 10. mulAdd applied
@Test func mulAddApplied() {
// Zero input → zero output before mulAdd. With mul:2, add:1 → output = 1.
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: 0.0,
distance: 1.0,
sampleRate: testSampleRate,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: blockSize)
let samples: [Double] = Array(out[0].prefix(blockSize))
let allNearOne: Bool = samples.allSatisfy { abs($0 - 1.0) < 1e-10 }
#expect(allNearOne, "mulAdd(mul:2, add:1) on zero input must produce output of 1.0")
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class SpatialSynth: SynthesizerBase {
override func build() {
let gen: SpatialDistance.Audio = SpatialDistance.Audio(
input: OscSin.Audio(freq: 220.0),
distance: 3.0,
velocity: 5.0,
sampleRate: 44100
)
addOutputGenerator(Out.Audio(bus: 0, source: gen))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: SpatialSynth = SpatialSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}