prep for 1.2.0 release updates

This commit is contained in:
2026-06-21 11:45:58 -07:00
parent 73191c958f
commit 032b7c39d3
286 changed files with 21116 additions and 121 deletions
@@ -0,0 +1,344 @@
// ConvolutionReverbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ConvolutionReverb.Audio — partitioned overlap-save FFT convolution")
struct ConvolutionReverbTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws {
try engine.start()
}
// MARK: - Helpers
/// Build a single-channel IR with `frames` frames; sample at `frame` is `value`.
private func makeUnitImpulseIR(frames: Int, position: Int = 0) -> LyrebirdBuffer {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: 1)
buf.setValue(1.0, at: position)
return buf
}
/// Build a multi-channel IR with the same shape on every channel.
private func makeMultiChannelImpulseIR(frames: Int, channels: Int) -> LyrebirdBuffer {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: channels)
for c: Int in 0..<channels {
buf.setValue(1.0, frame: 0, channel: c)
}
return buf
}
/// Drive the verb with a generator that emits the supplied input sequence.
private final class SequenceSource: GeneratorBase, AudioGenerator {
var samples: [Double]
var pos: Int = 0
init(_ samples: [Double]) { self.samples = samples; super.init() }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
for i: Int in 0..<count {
_result[0][i] = pos < samples.count ? samples[pos] : 0
pos += 1
}
return _result
}
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: ir)
#expect(verb.rate == .audio)
}
// MARK: - 2. outputChannelCount matches IR
@Test func outputChannelCountMatchesIR() {
let irMono: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
let monoVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: irMono)
#expect(monoVerb.outputChannelCount == 1)
let irStereo: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 4, channels: 2)
let stereoVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: irStereo)
#expect(stereoVerb.outputChannelCount == 2)
let ir4: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 4, channels: 4)
let quadVerb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(input: ConstantGeneratorInput(0.0), ir: ir4)
#expect(quadVerb.outputChannelCount == 4)
}
// MARK: - 3. Silent input → silent output (after warmup)
@Test func silentInputProducesSilentOutput() {
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.0),
ir: ir,
mix: 1.0
)
for _ in 0..<5 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let maxAbs: Double = out[0].prefix(512).map { abs($0) }.max() ?? 0
#expect(maxAbs < 1e-9, "Silent input → silent output; got \(maxAbs)")
}
// MARK: - 4. mix=0 → exact dry passthrough
@Test func mixZeroIsPassthrough() {
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.42),
ir: ir,
mix: 0.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i] - 0.42) < 1e-12,
"mix=0: dry passthrough; sample \(i) = \(out[0][i])")
}
}
// MARK: - 5. Unit-impulse IR is identity (mix=1, after one-partition latency)
@Test func unitImpulseIRPreservesInput() {
let partitionSize: Int = 64
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: partitionSize)
// Input = ramp 1, 2, 3, ..., scaled small.
let inputCount: Int = partitionSize * 6
var rampSamples: [Double] = [Double]()
for i: Int in 0..<inputCount { rampSamples.append(0.001 * Double(i + 1)) }
let src: ConvolutionReverbTests.SequenceSource = SequenceSource(rampSamples)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: src,
ir: ir,
partitionSize: partitionSize,
mix: 1.0
)
// Pull all output in one block.
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
// After partitionSize-sample latency, output should equal input.
for i: Int in partitionSize..<inputCount {
let expected: Double = rampSamples[i - partitionSize]
#expect(abs(out[0][i] - expected) < 1e-5,
"i=\(i) expected \(expected), got \(out[0][i])")
}
// First partitionSize samples must be silent (pre-latency).
for i: Int in 0..<partitionSize {
#expect(abs(out[0][i]) < 1e-9, "Pre-latency sample \(i) = \(out[0][i])")
}
}
// MARK: - 6. Delayed-impulse IR delays input by IR delay
@Test func delayedImpulseIRDelaysInput() {
let partitionSize: Int = 64
let irDelay: Int = 32
let irFrames: Int = partitionSize
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: irFrames, position: irDelay)
let inputCount: Int = partitionSize * 6
let src: ConvolutionReverbTests.SequenceSource = SequenceSource((0..<inputCount).map { Double($0 == 0 ? 1.0 : 0.0) })
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: src,
ir: ir,
partitionSize: partitionSize,
mix: 1.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
// Output[partitionSize + irDelay] should be the lone impulse (one-partition
// latency PLUS the IR delay). Other samples ~0.
let expectedSpike: Int = partitionSize + irDelay
#expect(abs(out[0][expectedSpike] - 1.0) < 1e-5,
"Impulse should appear at sample \(expectedSpike), got \(out[0][expectedSpike])")
for i: Int in 0..<inputCount where i != expectedSpike {
#expect(abs(out[0][i]) < 1e-5,
"Non-spike sample \(i) = \(out[0][i])")
}
}
// MARK: - 7. Multi-partition IR (length > partitionSize)
@Test func multiPartitionIRConvolves() {
// IR longer than one partition: impulse at frame 0 AND at frame 100 (across
// partition boundary at 64). Convolves dirac input → both echoes.
let partitionSize: Int = 64
let irFrames: Int = 200
let ir: LyrebirdBuffer = LyrebirdBuffer(count: irFrames, channelCount: 1)
ir.setValue(1.0, at: 0)
ir.setValue(0.5, at: 100)
let inputCount: Int = 512
let src: ConvolutionReverbTests.SequenceSource = SequenceSource([1.0] + Array(repeating: 0.0, count: inputCount - 1))
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: src,
ir: ir,
partitionSize: partitionSize,
mix: 1.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: inputCount)
// Echo at sample partitionSize + 0 = 64 with amplitude 1.0
// Echo at sample partitionSize + 100 = 164 with amplitude 0.5
#expect(abs(out[0][partitionSize] - 1.0) < 1e-4,
"First echo at \(partitionSize) = \(out[0][partitionSize])")
#expect(abs(out[0][partitionSize + 100] - 0.5) < 1e-4,
"Second echo at \(partitionSize + 100) = \(out[0][partitionSize + 100])")
}
// MARK: - 8. mulAdd applied
@Test func mulAddApplied() {
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 1024)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.0),
ir: ir,
mul: 2.0,
add: 1.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i] - 1.0) < 1e-12,
"Silent input + mul=2,add=1 → 1.0; got \(out[0][i]) at \(i)")
}
}
// MARK: - 9. Stereo IR produces two distinct channels
@Test func stereoIRProducesDistinctChannels() {
// Left = impulse at 0; right = impulse at 32. Mono dirac input.
let partitionSize: Int = 64
let irFrames: Int = partitionSize
let ir: LyrebirdBuffer = LyrebirdBuffer(count: irFrames, channelCount: 2)
ir.setValue(1.0, frame: 0, channel: 0)
ir.setValue(1.0, frame: 32, channel: 1)
let src: ConvolutionReverbTests.SequenceSource = SequenceSource([1.0] + Array(repeating: 0.0, count: 255))
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: src,
ir: ir,
partitionSize: partitionSize,
mix: 1.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 256)
#expect(abs(out[0][partitionSize] - 1.0) < 1e-4,
"Left echo at \(partitionSize) = \(out[0][partitionSize])")
#expect(abs(out[1][partitionSize + 32] - 1.0) < 1e-4,
"Right echo at \(partitionSize + 32) = \(out[1][partitionSize + 32])")
// Right channel should NOT have a spike at partitionSize.
#expect(abs(out[1][partitionSize]) < 1e-4,
"Right at \(partitionSize) = \(out[1][partitionSize]) (should be silent)")
}
// MARK: - 10. Fan-out: single evaluation per segment
@Test func fanOutSingleEvaluation() {
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 256)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.5),
ir: ir,
mix: 0.5
)
let out1: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
let out2: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(out1[0][i] == out2[0][i],
"Fan-out: identical samples at \(i)")
}
}
// MARK: - 11. .left/.right channel aliases
@Test func leftRightAliases() {
let ir: LyrebirdBuffer = makeMultiChannelImpulseIR(frames: 64, channels: 2)
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.0),
ir: ir
)
// Just verify they construct without trapping; the underlying ChannelSelect
// uses subscript indexing.
_ = verb.left
_ = verb.right
}
// MARK: - 12. partitionSize must be power of two ≥ 4
@Test func partitionSizeMustBePowerOfTwo() {
// Valid pow-of-two passes.
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: 4)
_ = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.0),
ir: ir,
partitionSize: 4
)
_ = ConvolutionReverb.Audio(
input: ConstantGeneratorInput(0.0),
ir: ir,
partitionSize: 1024
)
// Non-pow-of-two would trap; we don't exercise via #expect(throws:) since
// precondition aborts the process. The build-time check is sufficient.
}
// MARK: - 13. Energy preservation: convolution with normalised IR ≈ input energy
@Test func unitImpulseIRPreservesEnergy() {
// x convolved with δ[0] should equal x, so energy preserved exactly.
let partitionSize: Int = 128
let ir: LyrebirdBuffer = makeUnitImpulseIR(frames: partitionSize)
let blockSize: Int = 512
let blocks: Int = 8
let inputCount: Int = blockSize * blocks
let src: ConvolutionReverbTests.SequenceSource = SequenceSource((0..<inputCount).map { _ in
Double.random(in: -0.5...0.5)
})
let inputCopy: [Double] = src.samples
let verb: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: src,
ir: ir,
partitionSize: partitionSize,
mix: 1.0
)
// Pull block-by-block through the engine.
var allOutput: [Double] = [Double]()
allOutput.reserveCapacity(inputCount)
for _ in 0..<blocks {
let block: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
allOutput += block[0].prefix(blockSize)
advanceBlock(engine)
}
// Compare aligned ranges: output[partitionSize..] vs input[0..inputCount-partitionSize].
let alignedLen: Int = inputCount - partitionSize
var inEnergy: Double = 0.0
var outEnergy: Double = 0.0
for i: Int in 0..<alignedLen {
inEnergy += inputCopy[i] * inputCopy[i]
outEnergy += allOutput[i + partitionSize] * allOutput[i + partitionSize]
}
let ratio: Double = outEnergy / inEnergy
#expect(abs(ratio - 1.0) < 1e-3,
"Energy ratio out/in = \(ratio) (expected ~1.0)")
}
}
@@ -0,0 +1,204 @@
// FreeVerbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("FreeVerb — stereo reverb")
struct FreeVerbTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws {
try engine.start()
}
// MARK: - Output shape
@Test func outputIsStereo() {
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(0.5))
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "FreeVerb must produce exactly 2 channels")
#expect(out[0].count >= 64)
#expect(out[1].count >= 64)
}
// MARK: - Dry pass-through
@Test func mixZeroPassesDryThrough() {
let input: Double = 0.6
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(input), mix: 0.0)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i] - input) < 1e-10,
"L ch at mix=0 must equal dry input at sample \(i)")
#expect(abs(out[1][i] - input) < 1e-10,
"R ch at mix=0 must equal dry input at sample \(i)")
}
}
// MARK: - Wet output differs from dry
@Test func mixOneWetDiffersFromDry() {
// Run constant-input blocks until delay lines fill; wet output must differ from input.
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), roomSize: 0.8,
mix: 1.0, sampleRate: 44100)
for _ in 0..<10 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let anyDiffersL: Bool = out[0].prefix(512).contains { abs($0 - 1.0) > 1e-6 }
#expect(anyDiffersL, "Wet output must differ from dry input once delay lines are filled")
}
// MARK: - Impulse response decays
@Test func impulseResponseDecays() {
let impulse: ImpulseSource = ImpulseSource()
let verb: FreeVerb.Audio = FreeVerb.Audio(source: impulse, roomSize: 0.8, mix: 1.0, sampleRate: 44100)
// Block 0: inject impulse — writes into comb delay lines, output is 0 (nothing to
// read back yet; smallest comb size is 1116 > 512 samples/block).
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Blocks 1-2: advance until the first comb reflection wraps around.
// Smallest comb (1116 samples) first echoes at sample 1116 → block 2, offset 92.
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Capture early tail energy (block 2 — first reflections audible).
let earlyOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let earlyEnergy: Double = earlyOut[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
advanceBlock(engine)
// Advance 30 more blocks, then capture late tail.
// At roomSize=0.8, feedback ≈ 0.924; after 30 blocks each comb decays to ~34%.
var lateOut: [[Double]] = [[]]
for _ in 0..<30 {
lateOut = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let lateEnergy: Double = lateOut[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
#expect(earlyEnergy > 0, "Early tail must have non-zero energy after first reflections")
#expect(lateEnergy < earlyEnergy, "Reverb tail must decay over time")
}
// MARK: - Stereo channels are distinct
@Test func leftAndRightAreDistinct() {
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), roomSize: 0.5,
mix: 1.0, spread: 23, sampleRate: 44100)
for _ in 0..<5 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
.contains { abs($0 - $1) > 1e-8 }
#expect(anyDiff, "L and R channels must differ due to spread detuning")
}
// MARK: - roomSize affects decay rate
@Test func largerRoomSizeSlowerDecay() {
let impSml: ImpulseSource = ImpulseSource()
let impLrg: ImpulseSource = ImpulseSource()
let vSml: FreeVerb.Audio = FreeVerb.Audio(source: impSml, roomSize: 0.2, mix: 1.0, sampleRate: 44100)
let vLrg: FreeVerb.Audio = FreeVerb.Audio(source: impLrg, roomSize: 0.9, mix: 1.0, sampleRate: 44100)
// Both receive impulse on block 0.
_ = vSml.calculatedSamples(graph: graph, count: 512)
_ = vLrg.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Advance 30 blocks; capture late tail.
var tailSml: [[Double]] = [[]]
var tailLrg: [[Double]] = [[]]
for _ in 0..<30 {
tailSml = vSml.calculatedSamples(graph: graph, count: 512)
tailLrg = vLrg.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let energySml: Double = tailSml[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
let energyLrg: Double = tailLrg[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
#expect(energyLrg > energySml,
"Larger roomSize must produce more energy in the late tail")
}
// MARK: - Deterministic sample pin
@Test func firstCombEchoIsExact() {
// With roomSize=0 (feedback=0.7), damping=0 (LP transparent: damp1=0 → state=out),
// mix=1, spread=23 at 44100 Hz:
//
// Comb echo: smallest comb = 1116 samples. First echo at absolute sample 1116
// = block 2, index 92. Only that one comb has wrapped; others are larger → sumL = out0.
//
// Allpass chain: all 4 allpass buffers are still zero at index 92 (confirmed by
// tracing: each allpass size ≤ 556 samples; every position written before sample
// 1116 received apL=0 input, so all positions hold 0). With zero-filled buffers,
// each stage computes apOut = -input + 0 = -input. Four negations: (-1)^4 = +1.
// Net allpass effect is identity, value preserved exactly.
//
// Expected: comb[0] reads buf[0] = freeVerbFixedGain (0.015), LP state = 0.015
// (damp1=0 → no smoothing), sumL = 0.015, allpass identity → result = 0.015.
let impulse: ImpulseSource = ImpulseSource()
let verb: FreeVerb.Audio = FreeVerb.Audio(source: impulse, roomSize: 0.0, damping: 0.0,
mix: 1.0, spread: 23, sampleRate: 44100)
// Block 0: impulse at sample 0 written into comb delay positions.
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Block 1: no comb has wrapped yet (smallest comb = 1116 > 1023).
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Block 2: first comb wraps at sample 1116 = index 92 within this block.
let block2: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
#expect(abs(block2[0][92] - 0.015) < 1e-12,
"First echo from 1116-sample comb must equal freeVerbFixedGain at block-2 index 92")
}
// MARK: - Channel aliases
@Test func channelAliasesMatchSubscripts() {
// All three calls share the same segment; fan-out cache ensures FreeVerb
// computes once and left/right extract from the cached 2-channel result.
let verb: FreeVerb.Audio = FreeVerb.Audio(source: ConstantGeneratorInput(1.0), mix: 0.5, sampleRate: 44100)
let leftOut: [[Double]] = verb.left.calculatedSamples(graph: graph, count: 64)
let rightOut: [[Double]] = verb.right.calculatedSamples(graph: graph, count: 64)
let fullOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10)
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10)
}
}
}
// MARK: - Test helpers
/// Emits 1.0 at sample 0 of the first block; 0.0 on every subsequent block.
private final class ImpulseSource: 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, "ImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
// _fired is permanent — set on first _computeSamples call, never reset.
// advanceBlock() increments segment serial so subsequent blocks get fresh calls here.
_result[0][0] = _fired ? 0.0 : 1.0
for i: Int in 1..<count { _result[0][i] = 0.0 }
_fired = true
return _result
}
}
@@ -0,0 +1,305 @@
// GVerbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("GVerb — Griesinger algorithmic stereo reverb")
struct GVerbTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws {
try engine.start()
}
// MARK: - Output shape
@Test func outputIsStereo() {
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(0.5), sampleRate: 44100)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2, "GVerb must produce exactly 2 channels")
#expect(out[0].count >= 64)
#expect(out[1].count >= 64)
}
// MARK: - Dry pass-through at earlyLevel=tailLevel=0
@Test func zeroLevelsProduceSilence() {
let verb: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(0.8),
earlyLevel: 0.0,
tailLevel: 0.0,
sampleRate: 44100
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i]) < 1e-10,
"L ch must be silent when earlyLevel=tailLevel=0 (sample \(i))")
#expect(abs(out[1][i]) < 1e-10,
"R ch must be silent when earlyLevel=tailLevel=0 (sample \(i))")
}
}
// MARK: - Impulse RT60 within expected range at reverbTime=3.0
@Test func impulseRT60WithinRange() {
// Inject a single impulse, capture energy evolution over many blocks.
// With reverbTime=3.0 s, the tail energy should still be non-zero at 1 s
// and significantly decayed by 6 s.
let impulse: GVerbImpulseSource = GVerbImpulseSource()
let verb: GVerb.Audio = GVerb.Audio(
source: impulse,
roomSize: 10.0,
reverbTime: 3.0,
damping: 0.3,
earlyLevel: 0.0, // isolate late tail
tailLevel: 1.0,
sampleRate: 44100
)
// Drain enough blocks for early reflections to settle.
let blockSize: Int = 512
let blocksPerSecond: Int = 44100 / blockSize // ~86 blocks/s
// Warm up — inject impulse on block 0, advance.
_ = verb.calculatedSamples(graph: graph, count: blockSize)
advanceBlock(engine)
// Accumulate energy at ~1 s (expect significant tail).
var energyAt1s: Double = 0.0
let warmupBlocks: Int = blocksPerSecond
for _ in 0..<warmupBlocks {
let blk: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
energyAt1s += blk[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
advanceBlock(engine)
}
// Accumulate energy at ~5–6 s (expect substantially lower).
var energyAt5s: Double = 0.0
let laterBlocks: Int = blocksPerSecond * 4 // advance another 4 seconds
for _ in 0..<laterBlocks {
let blk: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
energyAt5s += blk[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
advanceBlock(engine)
}
// Reverb tail should have non-zero energy at 1 s.
#expect(energyAt1s > 0.0, "Late tail must have energy ~1 s after impulse (reverbTime=3.0)")
// And substantially less energy at 5 s (tail must decay).
#expect(energyAt5s < energyAt1s,
"Late tail must decay: energy at 5 s must be less than at 1 s")
}
// MARK: - roomSize change affects tail without crash
@Test func roomSizeChangeNoCrash() {
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(0.5), sampleRate: 44100)
// Warm up at default roomSize.
for _ in 0..<10 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
// Change roomSize mid-stream via a new ConstantGeneratorInput — no crash expected.
// (In practice roomSize is read each block via floatValue.)
let verbLarge: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(0.5),
roomSize: 80.0,
sampleRate: 44100
)
for _ in 0..<10 {
_ = verbLarge.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
// If we reach here without trap/crash the test passes.
#expect(Bool(true), "roomSize change must not crash or exceed buffer bounds")
}
// MARK: - Early and tail levels independently audible (NRT energy check)
@Test func earlyAndTailLevelsAreIndependent() {
let blockSize: Int = 512
let warmup: Int = 20
// Early only
let impulseE: GVerbImpulseSource = GVerbImpulseSource()
let verbEarly: GVerb.Audio = GVerb.Audio(
source: impulseE,
roomSize: 10.0, reverbTime: 3.0,
earlyLevel: 1.0, tailLevel: 0.0,
sampleRate: 44100
)
// Tail only
let impulseT: GVerbImpulseSource = GVerbImpulseSource()
let verbTail: GVerb.Audio = GVerb.Audio(
source: impulseT,
roomSize: 10.0, reverbTime: 3.0,
earlyLevel: 0.0, tailLevel: 1.0,
sampleRate: 44100
)
var earlyEnergy: Double = 0.0
var tailEnergy: Double = 0.0
for _ in 0..<warmup {
let blkE: [[Double]] = verbEarly.calculatedSamples(graph: graph, count: blockSize)
let blkT: [[Double]] = verbTail.calculatedSamples(graph: graph, count: blockSize)
earlyEnergy += blkE[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
tailEnergy += blkT[0].prefix(blockSize).reduce(0.0) { $0 + $1 * $1 }
advanceBlock(engine)
}
#expect(earlyEnergy > 0.0, "Early reflections must produce non-zero energy")
#expect(tailEnergy > 0.0, "Tail reverb must produce non-zero energy")
}
// MARK: - Stereo L/R are distinct
@Test func stereoLRDistinct() {
let verb: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(1.0),
roomSize: 15.0, reverbTime: 3.0,
earlyLevel: 0.5, tailLevel: 0.5,
sampleRate: 44100
)
// Warm up.
for _ in 0..<15 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let anyDiff: Bool = zip(out[0].prefix(512), out[1].prefix(512))
.contains { abs($0 - $1) > 1e-8 }
#expect(anyDiff, "L and R channels must differ (asymmetric post-sum allpass diffuser chains)")
}
// MARK: - Parameters update mid-stream (no RT alloc — no crash)
@Test func parametersUpdateMidStream() {
// Use ConstantGeneratorInput values — replaced by different instances each block
// to ensure parameter reads go through the protocol path every block.
let verb: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(0.3),
roomSize: ConstantGeneratorInput(10.0),
reverbTime: ConstantGeneratorInput(2.0),
damping: ConstantGeneratorInput(0.5),
sampleRate: 44100
)
for _ in 0..<5 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
// Create new verb with different params — simulates mid-stream param change.
let verb2: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(0.3),
roomSize: ConstantGeneratorInput(50.0),
reverbTime: ConstantGeneratorInput(5.0),
damping: ConstantGeneratorInput(0.8),
sampleRate: 44100
)
for _ in 0..<5 {
_ = verb2.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
#expect(Bool(true), "Parameter changes must not crash or allocate on the RT thread")
}
// MARK: - dryLevel passes direct signal at unity
@Test func dryLevelPassesDirectSignal() {
// With earlyLevel=0 and tailLevel=0, only the dry bypass path is active.
// dryLevel=1.0 on cold buffers: first output sample must equal the first input sample
// (after the one-pole input damper with inputBandwidth=1.0, which is pass-through).
let blockSize: Int = 64
let verb: GVerb.Audio = GVerb.Audio(
source: ConstantGeneratorInput(0.5),
inputBandwidth: 1.0,
earlyLevel: 0.0,
tailLevel: 0.0,
dryLevel: 1.0,
sampleRate: 44100
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: blockSize)
// All samples should equal 0.5 (dry bypass, no early/tail contribution).
for i: Int in 0..<blockSize {
#expect(abs(out[0][i] - 0.5) < 1e-10,
"L ch dry bypass must equal input 0.5 (sample \(i))")
#expect(abs(out[1][i] - 0.5) < 1e-10,
"R ch dry bypass must equal input 0.5 (sample \(i))")
}
}
// MARK: - Channel aliases match subscripts
@Test func channelAliasesMatchSubscripts() {
let verb: GVerb.Audio = GVerb.Audio(source: ConstantGeneratorInput(1.0), earlyLevel: 0.4, tailLevel: 0.4,
sampleRate: 44100)
let leftOut: [[Double]] = verb.left.calculatedSamples(graph: graph, count: 64)
let rightOut: [[Double]] = verb.right.calculatedSamples(graph: graph, count: 64)
let fullOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10,
"verb.left[i] must equal verb[0][i]")
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10,
"verb.right[i] must equal verb[1][i]")
}
}
/// Branchless ring-buffer wrap exercised across many wraps of the
/// tap delay (44000 samples ≈ 1 s) and 4 FDN delay lines. Drive a quiet
/// non-zero input over ~3 s and assert output stays finite + bounded.
/// Single shared engine; `advanceBlock` bumps `segmentSerial` so the
/// generator's fan-out cache does not freeze on the first block's output.
@Test func denormalLongTailStaysFinite() {
let drive: ConstantGeneratorInput = ConstantGeneratorInput(1e-3)
let verb: GVerb.Audio = GVerb.Audio(
source: drive, roomSize: 20.0, reverbTime: 5.0,
damping: 0.3, earlyLevel: 0.4, tailLevel: 0.5,
sampleRate: 44100)
let loopEngine: SynthesisEngine = makeTestEngine(blockSize: 64)
let blocks: Int = (Int(44100.0 * 3.0) / 64) + 1
var sawNonFinite: Bool = false
var maxAbs: Double = 0.0
for _: Int in 0..<blocks {
let g: SynthGraph = makeSynthGraph(engine: loopEngine)
let block: [[Double]] = verb.calculatedSamples(graph: g, count: 64)
for ch: Int in 0..<2 {
for v: Double in block[ch] {
if !v.isFinite { sawNonFinite = true }
let a: Double = abs(v)
if a > maxAbs { maxAbs = a }
}
}
advanceBlock(loopEngine)
}
#expect(!sawNonFinite, "GVerb output must remain finite across many ring wraps")
#expect(maxAbs < 1.0, "quiet-input output must remain bounded")
}
}
// MARK: - Test helpers
/// Emits 1.0 at sample 0 of the first block; 0.0 on every subsequent block.
private final class GVerbImpulseSource: 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, "GVerbImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
_result[0][0] = _fired ? 0.0 : 1.0
for i: Int in 1..<count { _result[0][i] = 0.0 }
_fired = true
return _result
}
}
@@ -0,0 +1,294 @@
// PlateReverbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("PlateReverb.Audio — Dattorro plate reverb")
struct PlateReverbTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws {
try engine.start()
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.0))
#expect(verb.rate == .audio)
}
// MARK: - 2. Output count
@Test func outputCountMatchesRequest() {
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.5))
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
#expect(Array(out[0].prefix(512)).count == 512)
}
// MARK: - 3. outputChannelCount is 2
@Test func outputChannelCountIsTwo() {
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.0))
#expect(verb.outputChannelCount == 2)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2)
}
// MARK: - 4. Silent input → silent output
@Test func silentInputProducesSilentOutput() {
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.0), mix: 1.0)
for _ in 0..<5 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let maxAbsL: Double = out[0].prefix(512).map { abs($0) }.max() ?? 0.0
let maxAbsR: Double = out[1].prefix(512).map { abs($0) }.max() ?? 0.0
#expect(maxAbsL < 1e-12, "Silent input must produce silent L output; got maxAbsL=\(maxAbsL)")
#expect(maxAbsR < 1e-12, "Silent input must produce silent R output; got maxAbsR=\(maxAbsR)")
}
// MARK: - 5. Mix=0 → passthrough (L and R both equal dry)
@Test func mixZeroIsPassthrough() {
let inputValue: Double = 0.6
let verb: PlateReverb.Audio = PlateReverb.Audio(
input: ConstantGeneratorInput(inputValue),
mix: 0.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i] - inputValue) < 1e-12,
"L ch at mix=0 must equal dry input at sample \(i)")
#expect(abs(out[1][i] - inputValue) < 1e-12,
"R ch at mix=0 must equal dry input at sample \(i)")
}
}
// MARK: - 6. First sample deterministic
@Test func firstSampleDeterministic() {
// Silent in, mix=0 → both channels should be exactly 0
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.0), mix: 0.0)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out[0][0] == 0.0, "L first sample must be 0 for silent input at mix=0")
#expect(out[1][0] == 0.0, "R first sample must be 0 for silent input at mix=0")
}
// MARK: - 7. Left/right aliases return individual channels
@Test func leftRightAliasesReturnIndividualChannels() {
let verb: PlateReverb.Audio = PlateReverb.Audio(
input: ConstantGeneratorInput(0.5),
mix: 0.5,
sampleRate: 44100
)
let leftOut: [[Double]] = verb.left.calculatedSamples(graph: graph, count: 64)
let rightOut: [[Double]] = verb.right.calculatedSamples(graph: graph, count: 64)
let fullOut: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(leftOut[0][i] - fullOut[0][i]) < 1e-10,
"left alias must match channel 0 at index \(i)")
#expect(abs(rightOut[0][i] - fullOut[1][i]) < 1e-10,
"right alias must match channel 1 at index \(i)")
}
}
// MARK: - 8. Decay produces a tail
@Test func decayProducesTail() {
let impulse: PlateImpulseSource = PlateImpulseSource()
let verb: PlateReverb.Audio = PlateReverb.Audio(
input: impulse,
decay: 0.7,
mix: 1.0,
sampleRate: 44100
)
// Block 0: inject impulse
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Accumulate energy over ~1 s post-impulse
let blocksFor1s: Int = Int(44100.0 / 512) + 1
var totalEnergy: Double = 0.0
for _ in 0..<blocksFor1s {
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let blockEnergy: Double = out[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
totalEnergy += blockEnergy
advanceBlock(engine)
}
#expect(totalEnergy > 1e-10,
"After an impulse, tail energy must remain > epsilon for 1 s; got \(totalEnergy)")
}
// MARK: - 9. Larger decay → longer tail
@Test func largerDecayMakesLongerTail() {
let impShort: PlateImpulseSource = PlateImpulseSource()
let impLong: PlateImpulseSource = PlateImpulseSource()
let vShort: PlateReverb.Audio = PlateReverb.Audio(input: impShort, decay: 0.3, mix: 1.0, sampleRate: 44100)
let vLong: PlateReverb.Audio = PlateReverb.Audio(input: impLong, decay: 0.85, mix: 1.0, sampleRate: 44100)
// Block 0: inject impulse
_ = vShort.calculatedSamples(graph: graph, count: 512)
_ = vLong.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Advance to ≈1 s post-impulse
let blocksFor1s: Int = Int(44100.0 / 512) + 1
var tailShort: [[Double]] = [[]]
var tailLong: [[Double]] = [[]]
for _ in 0..<blocksFor1s {
tailShort = vShort.calculatedSamples(graph: graph, count: 512)
tailLong = vLong.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let rmsShort: Double = rmsValue(Array(tailShort[0].prefix(512)))
let rmsLong: Double = rmsValue(Array(tailLong[0].prefix(512)))
#expect(rmsLong > rmsShort,
"Higher decay must produce larger RMS tail at 1 s; short=\(rmsShort), long=\(rmsLong)")
}
// MARK: - 10. Non-zero modulation breaks periodicity
@Test func nonZeroModProducesTimeVaryingTail() {
let imp1: PlateImpulseSource = PlateImpulseSource()
let imp2: PlateImpulseSource = PlateImpulseSource()
let vNoMod: PlateReverb.Audio = PlateReverb.Audio(
input: imp1, decay: 0.85, modDepth: 0.0, mix: 1.0, sampleRate: 44100
)
let vMod: PlateReverb.Audio = PlateReverb.Audio(
input: imp2, decay: 0.85, modDepth: 1.0, mix: 1.0, sampleRate: 44100
)
// Inject impulse on block 0
_ = vNoMod.calculatedSamples(graph: graph, count: 512)
_ = vMod.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Advance to let the tank fill — ~0.5 s
let blocksFor0_5s: Int = Int(44100.0 * 0.5 / 512) + 1
for _ in 0..<blocksFor0_5s {
_ = vNoMod.calculatedSamples(graph: graph, count: 512)
_ = vMod.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
// Capture two consecutive blocks for each
let noModA: [Double] = Array(vNoMod.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
let modA: [Double] = Array(vMod.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
advanceBlock(engine)
let noModB: [Double] = Array(vNoMod.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
let modB: [Double] = Array(vMod.calculatedSamples(graph: graph, count: 512)[0].prefix(512))
// Lag-1 autocorrelation: r = Σ x[i] * x[i-1] / Σ x[i]²
func lag1Autocorr(_ a: [Double], _ b: [Double]) -> Double {
guard a.count == b.count, !a.isEmpty else { return 0 }
var num: Double = 0.0
var den: Double = 0.0
for i: Int in 0..<a.count {
num += a[i] * b[i]
den += a[i] * a[i]
}
return den > 0 ? num / den : 0
}
let corrNoMod: Double = lag1Autocorr(noModA, noModB)
let corrMod: Double = lag1Autocorr(modA, modB)
// Modulated version should have lower block-to-block autocorrelation
// (modulation decorrelates consecutive blocks in the tail)
#expect(abs(corrMod - corrNoMod) > 1e-6,
"Modulated tail must differ from unmodulated in inter-block autocorrelation")
}
// MARK: - 11. Fan-out: single evaluation per segment
@Test func fanOutSingleEvaluation() {
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.5), mix: 0.5)
let out1: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
let out2: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(out1[0][i] == out2[0][i],
"Fan-out: both L calls in same segment must be identical at index \(i)")
#expect(out1[1][i] == out2[1][i],
"Fan-out: both R calls in same segment must be identical at index \(i)")
}
}
// MARK: - 12. mulAdd applied
@Test func mulAddApplied() {
// Silent in, mix=0 → output=0 before mulAdd; mul=2, add=1 → 1.0
let verb: PlateReverb.Audio = PlateReverb.Audio(input: ConstantGeneratorInput(0.0), mix: 0.0,
mul: 2.0, add: 1.0)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(abs(out[0][0] - 1.0) < 1e-12,
"mulAdd(2,1) on silent/passthrough must produce 1.0; got \(out[0][0])")
#expect(abs(out[1][0] - 1.0) < 1e-12,
"mulAdd(2,1) on silent/passthrough R must produce 1.0; got \(out[1][0])")
}
/// Branchless ring-buffer wrap exercised across many wraps of all
/// internal delay lines (preDelay + dl1L/R + dl2L/R + 4 input diffusers +
/// 2 modulated tank allpasses + 2 fixed tank allpasses). Drive a quiet
/// non-zero input over ~3 s and assert output stays finite + bounded.
/// Single shared engine; `advanceBlock` bumps `segmentSerial` so the
/// generator's fan-out cache does not freeze on the first block's output.
@Test func denormalLongTailStaysFinite() {
let drive: ConstantGeneratorInput = ConstantGeneratorInput(1e-3)
let verb: PlateReverb.Audio = PlateReverb.Audio(
input: drive, decay: 0.6, bandwidth: 0.99, damping: 0.3, mix: 0.5)
let loopEngine: SynthesisEngine = makeTestEngine(blockSize: 64)
let blocks: Int = (Int(44100.0 * 3.0) / 64) + 1
var sawNonFinite: Bool = false
var maxAbs: Double = 0.0
for _: Int in 0..<blocks {
let g: SynthGraph = makeSynthGraph(engine: loopEngine)
let block: [[Double]] = verb.calculatedSamples(graph: g, count: 64)
for ch: Int in 0..<2 {
for v: Double in block[ch] {
if !v.isFinite { sawNonFinite = true }
let a: Double = abs(v)
if a > maxAbs { maxAbs = a }
}
}
advanceBlock(loopEngine)
}
#expect(!sawNonFinite, "PlateReverb output must remain finite across many ring wraps")
#expect(maxAbs < 1.0, "quiet-input output must remain bounded")
}
}
// MARK: - Test helper — fires an impulse on first block only
private final class PlateImpulseSource: GeneratorBase, AudioGenerator {
private var _fired: Bool = false
func floatValue(graph: SynthGraph) -> Double { 0.0 }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count,
"PlateImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
_result[0][0] = _fired ? 0.0 : 1.0
for i: Int in 1..<count { _result[0][i] = 0.0 }
_fired = true
return _result
}
}
@@ -0,0 +1,228 @@
// SpringReverbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SpringReverb.Audio — spring-tank reverb")
struct SpringReverbTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws {
try engine.start()
}
// MARK: - 1. Rate
@Test func rateIsAudio() {
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0))
#expect(verb.rate == .audio)
}
// MARK: - 2. Output count
@Test func outputCountMatchesRequest() {
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.5))
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
#expect(Array(out[0].prefix(512)).count == 512)
}
// MARK: - 3. Mono output by default
@Test func monoOutputByDefault() {
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0), stereo: false)
#expect(verb.outputChannelCount == 1)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 1)
}
// MARK: - 4. Stereo output when flagged
@Test func stereoOutputWhenFlagged() {
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0), stereo: true)
#expect(verb.outputChannelCount == 2)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(out.count == 2)
}
// MARK: - 5. Silent input → silent output
@Test func silentInputProducesSilentOutput() {
// mix: 1.0, silent input → all wet, but wet is also silent (zero in → zero out)
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0), mix: 1.0)
// Advance a few blocks to ensure any transient settles
for _ in 0..<5 {
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let maxAbs: Double = out[0].prefix(512).map { abs($0) }.max() ?? 0.0
#expect(maxAbs < 1e-12, "Silent input must produce silent output; got maxAbs=\(maxAbs)")
}
// MARK: - 6. Mix=0 → passthrough
@Test func mixZeroIsPassthrough() {
let inputValue: Double = 0.75
let verb: SpringReverb.Audio = SpringReverb.Audio(
input: ConstantGeneratorInput(inputValue),
mix: 0.0
)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(abs(out[0][i] - inputValue) < 1e-12,
"At mix=0, output must equal dry input at sample \(i)")
}
}
// MARK: - 7. First sample deterministic
@Test func firstSampleDeterministic() {
// Silent input + identity mul/add → first sample is 0 (nothing in tank yet)
let v1: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0))
let out1: [[Double]] = v1.calculatedSamples(graph: graph, count: 64)
#expect(out1[0][0] == 0.0)
// With mul: 2.0, add: 1.0 and silent input:
// dry=0, wet=0, output = (1-mix)*0 + mix*0 = 0, then mul*0+add = 0*2+1 = 1
advanceBlock(engine)
let v2: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0), mul: 2.0, add: 1.0)
let out2: [[Double]] = v2.calculatedSamples(graph: graph, count: 64)
#expect(abs(out2[0][0] - 1.0) < 1e-12,
"mul=2, add=1 on silent source must give first sample 1.0, got \(out2[0][0])")
}
// MARK: - 8. Decay produces a tail
@Test func decayProducesTail() {
let impulse: SpringImpulseSource = SpringImpulseSource()
let verb: SpringReverb.Audio = SpringReverb.Audio(
input: impulse,
decay: 2.0,
mix: 1.0,
sampleRate: 44100
)
// Block 0: inject impulse
_ = verb.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Advance ~0.5 s (≈22 blocks at 512 samples/block) and accumulate energy
let blocksFor0_5s: Int = Int(44100.0 * 0.5 / 512) + 1
var totalEnergy: Double = 0.0
for _ in 0..<blocksFor0_5s {
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 512)
let blockEnergy: Double = out[0].prefix(512).reduce(0.0) { $0 + $1 * $1 }
totalEnergy += blockEnergy
advanceBlock(engine)
}
#expect(totalEnergy > 1e-10, "After an impulse, tail energy must remain > epsilon for at least 0.5 s; got \(totalEnergy)")
}
// MARK: - 9. Larger decay → longer tail
@Test func largerDecayMakesLongerTail() {
let impShort: SpringImpulseSource = SpringImpulseSource()
let impLong: SpringImpulseSource = SpringImpulseSource()
let vShort: SpringReverb.Audio = SpringReverb.Audio(input: impShort, decay: 0.5, mix: 1.0, sampleRate: 44100)
let vLong: SpringReverb.Audio = SpringReverb.Audio(input: impLong, decay: 4.0, mix: 1.0, sampleRate: 44100)
// Block 0: inject impulse in both
_ = vShort.calculatedSamples(graph: graph, count: 512)
_ = vLong.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
// Advance to ≈1 s post-impulse
let blocksFor1s: Int = Int(44100.0 / 512) + 1
var tailShort: [[Double]] = [[]]
var tailLong: [[Double]] = [[]]
for _ in 0..<blocksFor1s {
tailShort = vShort.calculatedSamples(graph: graph, count: 512)
tailLong = vLong.calculatedSamples(graph: graph, count: 512)
advanceBlock(engine)
}
let rmsShort: Double = rmsValue(Array(tailShort[0].prefix(512)))
let rmsLong: Double = rmsValue(Array(tailLong[0].prefix(512)))
#expect(rmsLong > rmsShort,
"Longer decay must produce larger RMS tail at 1 s; short=\(rmsShort), long=\(rmsLong)")
}
// MARK: - 10. Fan-out: single evaluation per segment
@Test func fanOutSingleEvaluation() {
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.5), mix: 0.5)
let out1: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
let out2: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
for i: Int in 0..<64 {
#expect(out1[0][i] == out2[0][i],
"Fan-out: both calls in same segment must return identical samples at index \(i)")
}
}
// MARK: - 11. mulAdd applied
@Test func mulAddApplied() {
// Silent input: output before mulAdd = 0. After mul=2, add=1 → 1.0
let verb: SpringReverb.Audio = SpringReverb.Audio(input: ConstantGeneratorInput(0.0), mul: 2.0, add: 1.0)
let out: [[Double]] = verb.calculatedSamples(graph: graph, count: 64)
#expect(abs(out[0][0] - 1.0) < 1e-12,
"mulAdd(2, 1) on silent input must produce 1.0; got \(out[0][0])")
}
/// Branchless ring-buffer wrap exercised across many wraps.
/// Render long enough that the main delay line (≈ 50 ms × 44100 ≈ 2205 samples)
/// wraps multiple times. Drive a quiet but non-zero input to keep ring values
/// non-trivial and verify output stays finite + bounded over the full render.
@Test func denormalLongTailStaysFinite() {
let drive: ConstantGeneratorInput = ConstantGeneratorInput(1e-3)
let verb: SpringReverb.Audio = SpringReverb.Audio(
input: drive, decay: 4.0, tension: 0.5, damping: 0.3,
mix: 0.5, preDelay: 0.005, sampleRate: 44100.0)
// ~3 s render — many wraps of the 50 ms main delay. Single shared engine;
// `advanceBlock` bumps `segmentSerial` so the generator's fan-out cache
// does not freeze on the first block's output.
let loopEngine: SynthesisEngine = makeTestEngine(blockSize: 64)
let blocks: Int = (Int(44100.0 * 3.0) / 64) + 1
var sawNonFinite: Bool = false
var maxAbs: Double = 0.0
for _: Int in 0..<blocks {
let g: SynthGraph = makeSynthGraph(engine: loopEngine)
let block: [[Double]] = verb.calculatedSamples(graph: g, count: 64)
for v: Double in block[0] {
if !v.isFinite { sawNonFinite = true }
let a: Double = abs(v)
if a > maxAbs { maxAbs = a }
}
advanceBlock(loopEngine)
}
#expect(!sawNonFinite, "SpringReverb output must remain finite across many ring wraps")
#expect(maxAbs < 1.0, "quiet-input output must remain bounded")
}
}
// MARK: - Test helper — fires an impulse on first block only
private final class SpringImpulseSource: GeneratorBase, AudioGenerator {
private var _fired: Bool = false
func floatValue(graph: SynthGraph) -> Double { 0.0 }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count,
"SpringImpulseSource: count \(count) exceeds buffer size \(_result[0].count)")
_result[0][0] = _fired ? 0.0 : 1.0
for i: Int in 1..<count { _result[0][i] = 0.0 }
_fired = true
return _result
}
}