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

344 lines
13 KiB
Swift

// ConvolutionReverbTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@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)")
}
}