Files
Lyrebird/Tests/LyrebirdTests/Generators/PhysicalModels/ScannedSynthesizerTests.swift
T
2026-06-21 11:45:58 -07:00

407 lines
15 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.
// ScannedSynthesizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ScannedSynthesizer")
struct ScannedSynthesizerTests {
// MARK: - Test fixture
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
let testSampleRate: Double = 44100
let testBlockSize: Int = 512
let testMassCount: Int = 16
init() throws {
try engine.start()
}
// MARK: - Rate
@Test func rateIsAudio() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
#expect(gen.rate == .audio)
}
// MARK: - Output count
@Test func outputCountMatchesRequest() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
#expect(out.count >= 1)
#expect(out[0].count >= 512)
}
// MARK: - Fan-out
@Test func fanOutSingleEvaluation() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out1: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let out2: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
// Same segment serial — second call must return the cached result.
let s1: [Double] = Array(out1[0].prefix(512))
let s2: [Double] = Array(out2[0].prefix(512))
#expect(s1 == s2, "Fan-out: two calculatedSamples calls in the same segment must return identical data")
}
// MARK: - State advances once per block
@Test func stateAdvancesOncePerBlock() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
_ = gen.calculatedSamples(graph: graph, count: 512)
_ = gen.calculatedSamples(graph: graph, count: 512) // cache hit
advanceBlock(engine)
let graph2: SynthGraph = makeSynthGraph(engine: engine)
let block2: [[Double]] = gen.calculatedSamples(graph: graph2, count: 512)
let allFinite: Bool = Array(block2[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "All output samples must be finite after one additional block")
}
// MARK: - Zeros initial displacement gives silence
@Test func zerosInitialDisplacementAndZeroExcitationProducesSilence() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
initialDisplacement: .zeros,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let allZero: Bool = samples.allSatisfy { abs($0) < 1e-15 }
#expect(allZero, "With .zeros initial state and zero excitation, output must be silent")
}
// MARK: - Gaussian initial displacement produces non-zero output
@Test func gaussianInitialDisplacementProducesNonZeroOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
stiffness: 200.0,
damping: 0.001,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let rms: Double = rmsValue(samples)
#expect(rms > 0, "Gaussian initial displacement must produce non-zero output, got rms=\(rms)")
}
// MARK: - Sine initial displacement produces non-zero output
@Test func sineInitialDisplacementProducesNonZeroOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
damping: 0.001,
initialDisplacement: .sine,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let rms: Double = rmsValue(samples)
#expect(rms > 0, "Sine initial displacement must produce non-zero output, got rms=\(rms)")
}
// MARK: - Impulse initial displacement produces non-zero output
@Test func impulseInitialDisplacementProducesNonZeroOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
damping: 0.001,
initialDisplacement: .impulse,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let samples: [Double] = Array(out[0].prefix(512))
let rms: Double = rmsValue(samples)
#expect(rms > 0, "Impulse initial displacement must produce non-zero output, got rms=\(rms)")
}
// MARK: - High damping decays faster than low damping
@Test func highDampingDecaysFasterThanLowDamping() {
// Two instances with identical gaussian init; one with high damping, one with almost none.
let hiDamp: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
stiffness: 200.0,
damping: 5.0,
centeringForce: 0.0,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let loDamp: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
stiffness: 200.0,
damping: 0.001,
centeringForce: 0.0,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
// Run many blocks and compare final RMS levels.
let decayBlocks: Int = 200
var hiOut: [[Double]] = [[]]
var loOut: [[Double]] = [[]]
for _ in 0..<decayBlocks {
let g: SynthGraph = makeSynthGraph(engine: engine)
hiOut = hiDamp.calculatedSamples(graph: g, count: 512)
loOut = loDamp.calculatedSamples(graph: g, count: 512)
advanceBlock(engine)
}
let hiRms: Double = rmsValue(Array(hiOut[0].prefix(512)))
let loRms: Double = rmsValue(Array(loOut[0].prefix(512)))
#expect(hiRms < loRms,
"High damping must decay to smaller amplitude: hiRms=\(hiRms) loRms=\(loRms)")
}
// MARK: - Excitation drives a silent network
@Test func excitationDrivesZeroInitialNetwork() {
// .zeros start + one-shot excitation should produce non-zero output after a few blocks
// once the energy spreads from excitationIndex and the scan traverses displaced masses.
let impulseTrigger: OneShotScannedTrigger = OneShotScannedTrigger()
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: impulseTrigger,
freq: 110.0,
massCount: testMassCount,
stiffness: 200.0,
damping: 0.001,
centeringForce: 0.0,
excitationIndex: 0,
initialDisplacement: .zeros,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
// Block 0: excitation fires → mass 0 receives a force.
_ = gen.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Run several blocks so energy propagates around the ring.
let propagationBlocks: Int = 20
var lastOut: [[Double]] = [[]]
for _ in 0..<propagationBlocks {
lastOut = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
advanceBlock(engine)
}
let rms: Double = rmsValue(Array(lastOut[0].prefix(512)))
#expect(rms > 0, "Excitation of .zeros network must produce non-zero output after propagation")
}
// MARK: - mulAdd
@Test func mulAddApplied() {
// Two instances with same gaussian initial state; one plain, one with mul:2 add:1.
let base: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
damping: 0.001,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let scaled: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
damping: 0.001,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize,
mul: 2.0,
add: 1.0
)
let outBase: [Double] = Array(base.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
let outScaled: [Double] = Array(scaled.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
var holds: Bool = true
for i: Int in 0..<512 {
let expected: Double = outBase[i] * 2.0 + 1.0
if abs(outScaled[i] - expected) > 1e-10 {
holds = false
break
}
}
#expect(holds, "mul:2.0 add:1.0 must produce output × 2 + 1")
}
// MARK: - No NaN or Inf over many blocks (phasor wrap)
@Test func noNaNOrInfOverManyBlocks() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 440.0,
massCount: testMassCount,
stiffness: 50.0,
damping: 0.001,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let iterations: Int = 500
var allFinite: Bool = true
for _ in 0..<iterations {
let out: [[Double]] = gen.calculatedSamples(graph: makeSynthGraph(engine: engine), count: 512)
let samples: [Double] = Array(out[0].prefix(512))
if !samples.allSatisfy({ $0.isFinite }) {
allFinite = false
break
}
advanceBlock(engine)
}
#expect(allFinite, "All output samples must remain finite over \(iterations) blocks")
}
// MARK: - Interpolation modes all produce finite output
@Test func interpolationNoneProducesFiniteOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
interpolation: .none,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let allFinite: Bool = Array(out[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "interpolation:.none must produce all finite samples")
}
@Test func interpolationLinearProducesFiniteOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
interpolation: .linear,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let allFinite: Bool = Array(out[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "interpolation:.linear must produce all finite samples")
}
@Test func interpolationCubicProducesFiniteOutput() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: 0.0,
freq: 220.0,
massCount: testMassCount,
interpolation: .cubic,
initialDisplacement: .gaussian,
sampleRate: testSampleRate,
blockSize: testBlockSize
)
let out: [[Double]] = gen.calculatedSamples(graph: graph, count: 512)
let allFinite: Bool = Array(out[0].prefix(512)).allSatisfy { $0.isFinite }
#expect(allFinite, "interpolation:.cubic must produce all finite samples")
}
// MARK: - Integration with engine
@Test func integrationWithEngine() throws {
final class ScannedSynth: SynthesizerBase {
override func build() {
let gen: ScannedSynthesizer.Audio = ScannedSynthesizer.Audio(
excitation: Impulse.Audio(freq: 2.0),
freq: 220.0,
massCount: 16,
stiffness: 200.0,
damping: 0.05,
initialDisplacement: .gaussian,
sampleRate: 44100,
blockSize: 512
)
addOutputGenerator(Out.Audio(bus: 0, source: gen))
}
}
let intEngine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
try intEngine.start()
let synth: ScannedSynth = ScannedSynth()
try intEngine.add(synth)
for _ in 0..<4 {
intEngine.processBlock(inputSamples: [])
}
intEngine.stop()
}
}
// MARK: - Local test helpers
/// Emits 1.0 on the first `_computeSamples` call, 0.0 on all subsequent calls.
/// Simulates a single block of excitation, then silence.
private final class OneShotScannedTrigger: GeneratorBase, AudioGenerator {
private var _fired: Bool = false
public func floatValue(graph: SynthGraph) -> Double { 0.0 }
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(
count <= _result[0].count,
"OneShotScannedTrigger: count \(count) exceeds buffer size \(_result[0].count)"
)
let value: Double = _fired ? 0.0 : 1.0
for i: Int in 0..<count { _result[0][i] = value }
_fired = true
return _result
}
}