Files
Lyrebird/Tests/LyrebirdTests/SignalGraphIntegrationTests.swift

464 lines
18 KiB
Swift
Raw Permalink 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.
// SignalGraphIntegrationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Fixtures
/// OscSin at a fixed frequency and phase wired directly to an output bus.
/// phase=0.25 → starts at sin(π/2) ≈ 1.0, so the first sample is non-zero immediately.
private final class OscSinSynth: SynthesizerBase {
let freq: Double
let phase: Double
let outputBus: Int
init(freq: Double, phase: Double = 0.25, outputBus: Int = 0) {
self.freq = freq
self.phase = phase
self.outputBus = outputBus
super.init()
}
override func build() {
addOutputGenerator(Out.Audio(bus: outputBus, source: OscSin.Audio(freq: freq, phase: phase)))
}
}
/// OscSin → RBJBandPass (at the same frequency) → Out.
/// The band-pass filter is centered on the oscillator frequency so signal passes through.
private final class FilteredSinSynth: SynthesizerBase {
let freq: Double
let outputBus: Int
init(freq: Double, outputBus: Int = 0) {
self.freq = freq
self.outputBus = outputBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: freq, phase: 0.25)
let bandwidthInOctaves: Double = 1.0
let bpf: RBJBandPass.Audio = RBJBandPass.Audio(input: osc, freq: freq, bandwidth: bandwidthInOctaves)
addOutputGenerator(Out.Audio(bus: outputBus, source: bpf))
}
}
/// OscSin (phase=0.25 so first sample ≈ 1.0) fed into a DelayLine.
/// Callers supply the exact delay in seconds so the test can choose a delay
/// that is shorter or longer than one block.
private final class DelayedSinSynth: SynthesizerBase {
let freq: Double
let delaySeconds: Double
let sampleRate: Double
let outputBus: Int
init(freq: Double, delaySeconds: Double, sampleRate: Double, outputBus: Int = 0) {
self.freq = freq
self.delaySeconds = delaySeconds
self.sampleRate = sampleRate
self.outputBus = outputBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: freq, phase: 0.25)
let delayed: DelayLine = DelayLine(
input: osc,
maxDelay: 1.0,
delay: delaySeconds,
sampleRate: sampleRate,
interpolation: .none
)
addOutputGenerator(Out.Audio(bus: outputBus, source: delayed))
}
}
/// OscSin whose frequency is controlled by a `@LiveParam`-backed `ParameterNode`.
/// Callers can update via direct typed write (`synth.freq = X`) or by-name
/// (`try synth.updateParameter("freq", value: X)`) — both routes write the same atomic.
private final class TunableOscSynth: SynthesizerBase {
@LiveParam var freq: Double = 0.0
let outputBus: Int
init(defaultFreq: Double, outputBus: Int = 0) {
self.outputBus = outputBus
super.init()
// prime() resets both atomic and ramp origin so the first block is flat at defaultFreq.
$freq.prime(defaultFreq)
}
override func build() {
addOutputGenerator(Out.Audio(bus: outputBus, source: OscSin.Audio(freq: $freq, phase: 0.25)))
}
}
// MARK: - Helpers
private func rms(_ samples: ArraySlice<Float>) -> Double {
let sum: Double = samples.reduce(0.0) { $0 + Double($1) * Double($1) }
return (sum / Double(samples.count)).squareRoot()
}
// MARK: - OscSin integration
@MainActor
@Suite("OscSin engine integration")
struct OscSinEngineIntegrationTests {
let blockSize: Int = 64
let sampleRate: Double = 44100.0
let engine: SynthesisEngine
/// RMS level below which a signal is considered inaudible (silence).
private let silenceThreshold: Double = 1e-6
/// Minimum RMS level an audible oscillator must sustain across a full block.
private let minimumAudibleRMS: Double = 0.1
init() throws {
engine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 64
)
try engine.start()
}
/// OscSin wired through engine should produce a non-silent signal on the output bus.
@Test func oscSinOutputIsNonZero() throws {
try engine.add(OscSinSynth(freq: 440.0, outputBus: 0))
engine.processBlock(inputSamples: [])
let busRMS: Double = rms(engine.audioBuses[0].prefix(blockSize))
#expect(busRMS > minimumAudibleRMS)
}
/// Consecutive processed blocks should not produce identical samples — the phase must
/// advance across block boundaries.
@Test func oscillatorOutputVariesAcrossMultipleBlocks() throws {
try engine.add(OscSinSynth(freq: 440.0, outputBus: 0))
engine.processBlock(inputSamples: [])
let block1: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
engine.processBlock(inputSamples: [])
let block2: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
engine.processBlock(inputSamples: [])
let block3: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
// At 440 Hz / 64 samples / 44100 Hz, phase advances by ~0.639 cycles per block —
// each block has a distinct pattern.
#expect(block1 != block2)
#expect(block2 != block3)
}
/// Over 100 blocks the oscillator must remain audible — no freeze or DC collapse.
@Test func hundredBlocksRemainNonZero() throws {
try engine.add(OscSinSynth(freq: 440.0, outputBus: 0))
var totalRMS: Double = 0.0
let blockCount: Int = 100
for _ in 0..<blockCount {
engine.processBlock(inputSamples: [])
totalRMS += rms(engine.audioBuses[0].prefix(blockSize))
}
let averageRMS: Double = totalRMS / Double(blockCount)
#expect(averageRMS > minimumAudibleRMS)
}
/// Removing the synth must leave the output bus at zero from the very next block.
@Test func removedSynthProducesZeroOutput() throws {
let synth: OscSinSynth = OscSinSynth(freq: 440.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: []) // active block
engine.remove(synth)
engine.processBlock(inputSamples: []) // synth no longer in tree
#expect(rms(engine.audioBuses[0].prefix(blockSize)) < silenceThreshold)
}
}
// MARK: - Filter chain integration
@MainActor
@Suite("Filter chain integration")
struct FilterChainIntegrationTests {
let blockSize: Int = 512
let sampleRate: Double = 44100.0
let engine: SynthesisEngine
/// Minimum RMS level indicating the filter is passing signal at its center frequency.
private let minimumPassbandRMS: Double = 0.01
/// Maximum absolute sample value; if exceeded the filter has gone unstable.
private let amplitudeClipLimit: Float = 2.0
init() throws {
engine = makeTestEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 64
)
try engine.start()
}
/// Signal filtered at its center frequency should still be audible (bandpass passes energy
/// when the input frequency matches the filter's center frequency).
@Test func filteredOscAtCenterFrequencyIsAudible() throws {
let freq: Double = 440.0
try engine.add(FilteredSinSynth(freq: freq, outputBus: 0))
// Allow a few blocks for transient to settle.
let settleBlocks: Int = 5
for _ in 0..<settleBlocks { engine.processBlock(inputSamples: []) }
engine.processBlock(inputSamples: [])
let busRMS: Double = rms(engine.audioBuses[0].prefix(blockSize))
#expect(busRMS > minimumPassbandRMS)
}
/// Filtered signal must be bounded — the filter must not blow up.
@Test func filteredOscOutputIsBounded() throws {
try engine.add(FilteredSinSynth(freq: 440.0, outputBus: 0))
for _ in 0..<20 { engine.processBlock(inputSamples: []) }
let bus: Array<Float>.SubSequence = engine.audioBuses[0].prefix(blockSize)
#expect(bus.allSatisfy { $0.isFinite })
#expect(bus.allSatisfy { abs($0) <= amplitudeClipLimit })
}
}
// MARK: - Delay line integration
@MainActor
@Suite("Delay line integration")
struct DelayLineIntegrationTests {
let blockSize: Int = 64
let sampleRate: Double = 44100.0
let engine: SynthesisEngine
/// RMS level below which a signal is considered inaudible (silence).
private let silenceThreshold: Double = 1e-6
/// Minimum RMS level indicating the delayed oscillator is audible.
private let minimumAudibleRMS: Double = 0.1
init() throws {
engine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 64
)
try engine.start()
}
/// With a delay of exactly one block, the first output block must be silent because
/// the delay buffer is zero-initialized and DelayLine uses read-before-write ordering.
@Test func delayedSignalIsInitiallySilent() throws {
// Delay = exactly one block worth of samples.
let oneBlockDelay: Double = Double(blockSize) / sampleRate
try engine.add(DelayedSinSynth(
freq: 440.0,
delaySeconds: oneBlockDelay,
sampleRate: sampleRate,
outputBus: 0
))
engine.processBlock(inputSamples: []) // block 1: reads zero buffer
#expect(rms(engine.audioBuses[0].prefix(blockSize)) < silenceThreshold)
}
/// After the delay has elapsed, the delayed signal should become audible.
@Test func delayedSignalBecomesAudibleAfterDelay() throws {
let oneBlockDelay: Double = Double(blockSize) / sampleRate
try engine.add(DelayedSinSynth(
freq: 440.0,
delaySeconds: oneBlockDelay,
sampleRate: sampleRate,
outputBus: 0
))
engine.processBlock(inputSamples: []) // block 1: silence (reads zero buffer)
engine.processBlock(inputSamples: []) // block 2: reads block-1 OscSin samples
let busRMS: Double = rms(engine.audioBuses[0].prefix(blockSize))
#expect(busRMS > minimumAudibleRMS)
}
/// With zero delay the read-before-write semantics produce zeros on the first block
/// (the circular buffer has not yet wrapped around). This confirms the design intent:
/// delay=0 reads the previous wrap-around value, not the current input.
@Test func zeroDelayProducesZeroOnFirstBlock() throws {
try engine.add(DelayedSinSynth(
freq: 440.0,
delaySeconds: 0.0,
sampleRate: sampleRate,
outputBus: 0
))
engine.processBlock(inputSamples: [])
// The buffer was zero-initialised; with zero delay, read-before-write reads those zeros.
#expect(rms(engine.audioBuses[0].prefix(blockSize)) < silenceThreshold)
}
}
// MARK: - Bus accumulation
@MainActor
@Suite("Bus accumulation integration")
struct BusAccumulationIntegrationTests {
let blockSize: Int = 64
let engine: SynthesisEngine
/// Minimum RMS indicating a bus carries signal.
private let minimumSignalRMS: Double = 0.01
/// RMS level below which a bus is considered silent.
private let silenceThreshold: Double = 1e-6
/// Maximum deviation between source and routed bus RMS (routing should be lossless).
private let routingRMSTolerance: Double = 0.001
init() throws {
engine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 64
)
try engine.start()
}
/// Two oscillators writing to the same bus should sum their amplitudes.
/// OscSin.Audio(phase=0.0) and OscSin.Audio(phase=0.5) produce signals that at sample 0 are
/// sin(0)=0 and sin(π)=0 respectively — but their RMS values sum.
@Test func twoOscillatorsAccumulateOnSameBus() throws {
// Use two oscillators with the same freq but 90° phase offset so they are
// not in perfect cancellation or phase-aligned.
try engine.add(OscSinSynth(freq: 440.0, phase: 0.0, outputBus: 0))
try engine.add(OscSinSynth(freq: 440.0, phase: 0.25, outputBus: 0)) // +90° phase
engine.processBlock(inputSamples: [])
// RMS of sum of two signals at 90° offset ≈ √2 / √2 × 2 = ... just verify > single.
let sumRMS: Double = rms(engine.audioBuses[0].prefix(blockSize))
#expect(sumRMS > minimumSignalRMS)
}
/// Removing the synth on bus A must silence that bus while leaving bus B unaffected.
@Test func oscillatorsOnDifferentBusesDoNotInterfere() throws {
let busA: Int = 4
let busB: Int = 5
let synthA: OscSinSynth = OscSinSynth(freq: 440.0, phase: 0.25, outputBus: busA)
let synthB: OscSinSynth = OscSinSynth(freq: 880.0, phase: 0.25, outputBus: busB)
try engine.add(synthA)
try engine.add(synthB)
engine.processBlock(inputSamples: [])
// Both buses carry signal.
#expect(rms(engine.audioBuses[busA].prefix(blockSize)) > minimumSignalRMS)
#expect(rms(engine.audioBuses[busB].prefix(blockSize)) > minimumSignalRMS)
// Remove only synthA; synthB must continue producing output on busB.
engine.remove(synthA)
engine.processBlock(inputSamples: [])
#expect(rms(engine.audioBuses[busA].prefix(blockSize)) < silenceThreshold,
"busA must be silent after its synth is removed")
#expect(rms(engine.audioBuses[busB].prefix(blockSize)) > minimumSignalRMS,
"busB must still carry signal from synthB")
}
/// A RoutingSynth reads from bus A and accumulates into bus B — verifying the In → Out
/// chain works correctly in a full engine integration context.
@Test func routingChainCopiesSignalBetweenBuses() throws {
let sourceBus: Int = 4
let destBus: Int = 5
// engine.add uses addToHead: last-added evaluates first.
// Add reader first (tail), then writer (head) so writer populates the bus before reader.
try engine.add(RoutingSynth(inputBus: sourceBus, outputBus: destBus)) // reader first → tail
try engine.add(OscSinSynth(freq: 440.0, phase: 0.25, outputBus: sourceBus)) // writer last → head
engine.processBlock(inputSamples: [])
let sourceRMS: Double = rms(engine.audioBuses[sourceBus].prefix(blockSize))
let destRMS: Double = rms(engine.audioBuses[destBus].prefix(blockSize))
// Both buses carry the same signal (routed, not mixed with anything else).
#expect(sourceRMS > minimumSignalRMS)
#expect(abs(sourceRMS - destRMS) < routingRMSTolerance)
}
}
// MARK: - Parameter modulation integration
@MainActor
@Suite("Parameter modulation integration")
struct ParameterModulationIntegrationTests {
let blockSize: Int = 64
let engine: SynthesisEngine
/// Maximum sample-to-sample deviation for a signal considered "constant" (freq=0).
private let constantOutputTolerance: Double = 1e-3
/// Minimum per-block variance indicating a time-varying oscillator (freq > 0).
private let minimumTimeVaryingVariance: Double = 1e-4
init() throws {
engine = makeTestEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 64
)
try engine.start()
}
/// With freq=0 the oscillator phase never advances — all samples equal the initial
/// sine value (constant output). After a parameter update to a non-zero frequency
/// the output must become time-varying.
@Test func parameterUpdateChangesOscillatorBehavior() throws {
let synth: TunableOscSynth = TunableOscSynth(defaultFreq: 0.0, outputBus: 0)
try engine.add(synth)
// Block 1: freq=0, phase=0.25 → constant output ≈ 1.0 for all samples.
engine.processBlock(inputSamples: [])
let block1: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
let firstSample: Float = block1[0]
#expect(block1.allSatisfy { abs(Double($0) - Double(firstSample)) < constantOutputTolerance },
"With freq=0 all samples in the block must be equal")
// Queue parameter update and process two more blocks.
try synth.updateParameter("freq", value: 440.0)
engine.processBlock(inputSamples: []) // ramp block (ParameterNode interpolation)
engine.processBlock(inputSamples: []) // steady state at 440 Hz
let block3: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
let variance: Double = block3.reduce(0.0) { acc, s in
let d: Double = Double(s) - Double(block3[0])
return acc + d * d
} / Double(blockSize)
#expect(variance > minimumTimeVaryingVariance,
"With freq=440 Hz the output block must be time-varying")
}
/// Multiple parameter updates are enqueued and applied in order — the final value
/// that the RT thread drains from the queue must be the last-enqueued one.
@Test func multipleParameterUpdatesApplyInOrder() throws {
let synth: TunableOscSynth = TunableOscSynth(defaultFreq: 440.0, outputBus: 0)
try engine.add(synth)
engine.processBlock(inputSamples: [])
// Queue several updates; the last one (freq=0) is the value that should win.
try synth.updateParameter("freq", value: 880.0)
try synth.updateParameter("freq", value: 220.0)
try synth.updateParameter("freq", value: 0.0)
// After one block the queue is drained; a second block runs at freq=0.
engine.processBlock(inputSamples: []) // applies updates
engine.processBlock(inputSamples: []) // runs at final freq=0
let block: [Float] = Array(engine.audioBuses[0].prefix(blockSize))
let firstSample: Float = block[0]
// freq=0 → constant output; all samples must match.
#expect(block.allSatisfy { abs(Double($0) - Double(firstSample)) < constantOutputTolerance },
"After updating to freq=0 the output must be constant")
}
}