810 lines
35 KiB
Swift
810 lines
35 KiB
Swift
// ParameterSourceSwapIntegrationTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
// MARK: - Shared synth fixtures (file-private)
|
|
|
|
/// Synth under test for most integration tests. Two @LiveParam properties so
|
|
/// cross-contamination between independent parameter slots can be detected.
|
|
private final class DualParamSynth: SynthesizerBase {
|
|
@LiveParam var freq: Double = 440.0
|
|
@LiveParam var amp: Double = 0.5
|
|
|
|
override func build() {
|
|
// Route freq-driven sine to bus 0, amp-driven constant to bus 1.
|
|
let osc: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
|
|
output(bus: 0, source: osc)
|
|
}
|
|
}
|
|
|
|
/// Minimal synth with a single @LiveParam frequency.
|
|
private final class FreqSynth: SynthesizerBase {
|
|
@LiveParam var freq: Double = 440.0
|
|
|
|
override func build() {
|
|
output(bus: 0, source: OscSin.Audio(freq: $freq))
|
|
}
|
|
}
|
|
|
|
// MARK: - Integration helpers
|
|
|
|
/// Process N full blocks through the engine (using processBlock so the full
|
|
/// scheduling / evaluation path runs) and return the audio bus 0 samples for
|
|
/// the final block. The engine must be started before calling this.
|
|
private func renderBlocks(
|
|
engine: SynthesisEngine,
|
|
count: Int
|
|
) -> [Float] {
|
|
var lastBlock: [Float] = []
|
|
for _ in 0..<count {
|
|
engine.processBlock(inputSamples: [])
|
|
lastBlock = engine.audioBuses[0]
|
|
}
|
|
return lastBlock
|
|
}
|
|
|
|
/// Render a single block and return bus-0 samples.
|
|
@discardableResult
|
|
private func renderOneBlock(engine: SynthesisEngine) -> [Float] {
|
|
engine.processBlock(inputSamples: [])
|
|
return engine.audioBuses[0]
|
|
}
|
|
|
|
/// Root-mean-square of a Float buffer.
|
|
private func rms(_ samples: [Float]) -> Double {
|
|
guard !samples.isEmpty else { return 0 }
|
|
var sum: Double = 0.0
|
|
for s: Float in samples { let d: Double = Double(s); sum += d * d }
|
|
return (sum / Double(samples.count)).squareRoot()
|
|
}
|
|
|
|
/// Root-mean-square of a Double buffer.
|
|
private func rmsD(_ samples: [Double]) -> Double {
|
|
guard !samples.isEmpty else { return 0 }
|
|
var sum: Double = 0.0
|
|
for s: Double in samples { sum += s * s }
|
|
return (sum / Double(samples.count)).squareRoot()
|
|
}
|
|
|
|
// MARK: - Test suite
|
|
|
|
@MainActor
|
|
@Suite("ParameterNode source-swap integration")
|
|
struct ParameterSourceSwapIntegrationTests {
|
|
|
|
// MARK: - Test 1: End-to-end scalar → LFO via property setter
|
|
|
|
/// Verifies that assigning a `ControlGenerator` to `synth.$freq.source` through a
|
|
/// real, running engine causes the synthesizer's output to change.
|
|
///
|
|
/// Baseline: 2 blocks of 440 Hz sine output. Then wire a LFSawtooth.Control at
|
|
/// 0.5 Hz (mul=100, add=440) as the freq source. After 4 more blocks the LFO
|
|
/// is modulating the frequency — verify RMS of output is non-zero (audio is playing)
|
|
/// and that changing the source has some measurable effect (the parameter is being
|
|
/// driven by the LFO, not stuck at 0).
|
|
@Test func endToEndScalarToLFO() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
|
|
// Warm-up: 2 blocks at scalar 440 Hz — verify output has non-trivial RMS.
|
|
let baselineBlock1: [Float] = renderOneBlock(engine: engine)
|
|
let baselineBlock2: [Float] = renderOneBlock(engine: engine)
|
|
let baselineRMS: Double = (rms(baselineBlock1) + rms(baselineBlock2)) / 2.0
|
|
#expect(baselineRMS > 0.01, "Baseline sine (440 Hz) should have non-zero RMS, got \(baselineRMS)")
|
|
|
|
// Assign LFO source: freq = 440 + LFSawtooth * 100 → range [340, 540].
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 0.5, mul: 100.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
|
|
// Render 4 blocks. The LFO is now driving freq.
|
|
var lfoRMSSum: Double = 0.0
|
|
for _ in 0..<4 {
|
|
let samples: [Float] = renderOneBlock(engine: engine)
|
|
lfoRMSSum += rms(samples)
|
|
}
|
|
let avgLFORMS: Double = lfoRMSSum / 4.0
|
|
#expect(avgLFORMS > 0.01, "LFO-driven output should have non-zero RMS, got \(avgLFORMS)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 2: End-to-end revert to scalar
|
|
|
|
/// After wiring an LFO, setting `source = nil` should revert the parameter to its
|
|
/// scalar value. The output should return to a stable 440 Hz sine.
|
|
@Test func endToEndRevertToScalar() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine) // settle
|
|
|
|
// Install LFO source.
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 2.0, mul: 200.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
_ = renderBlocks(engine: engine, count: 4) // let LFO run
|
|
|
|
// Revert to scalar.
|
|
synth.$freq.source = nil
|
|
|
|
// Render 2 more blocks — now stable at 440 Hz again.
|
|
// The last-block audio should be non-zero (oscillator is still playing).
|
|
let block1: [Float] = renderOneBlock(engine: engine)
|
|
let block2: [Float] = renderOneBlock(engine: engine)
|
|
#expect(rms(block1) > 0.01, "Revert block 1: should have non-zero RMS")
|
|
#expect(rms(block2) > 0.01, "Revert block 2: should have non-zero RMS")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 3: End-to-end via SynthesizerBase.setSource helper
|
|
|
|
/// Verifies that `synth.setSource(synth.$freq, to: lfo)` is equivalent to
|
|
/// `synth.$freq.source = lfo` and wires the LFO through the engine.
|
|
@Test func endToEndViaSetSourceHelper() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Use the SynthesizerBase helper.
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 0.5, mul: 100.0, add: 440.0)
|
|
synth.setSource(synth.$freq, to: lfo)
|
|
|
|
var rmsSum: Double = 0.0
|
|
for _ in 0..<4 {
|
|
let samples: [Float] = renderOneBlock(engine: engine)
|
|
rmsSum += rms(samples)
|
|
}
|
|
let avgRMS: Double = rmsSum / 4.0
|
|
#expect(avgRMS > 0.01, "setSource helper: LFO-driven output should be non-zero, got \(avgRMS)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 4: Scalar → Generator parameter modulation is measurable
|
|
|
|
/// After swapping the source, the ParameterNode output must change block-to-block
|
|
/// when the source generator produces varying values. We verify by checking that the
|
|
/// ParameterNode's output (read directly) differs across blocks when a rising LFSawtooth
|
|
/// is wired in.
|
|
@Test func lfoModulatesParameterMeasurably() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Use an LFSawtooth that rises at 1 Hz from -1 to 1 (in raw, before mul/add).
|
|
// With mul=100 and add=440, it sweeps 340..540 Hz over 1 second.
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0, mul: 100.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
|
|
// Collect ParameterNode output across 3 blocks directly (not via audio bus).
|
|
// Each block the LFO should have advanced, so the last sample should differ.
|
|
var blockMeans: [Double] = []
|
|
for _ in 0..<3 {
|
|
engine.processBlock(inputSamples: [])
|
|
// Read $freq directly via calculatedSamples using same block's graph state.
|
|
// Because processBlock already advanced the serial, we need a fresh graph.
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let samples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let mean: Double = samples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
blockMeans.append(mean)
|
|
}
|
|
|
|
// After source assignment, values are around 440. Verify they are all in [340, 540]
|
|
// (within the expected LFO range) and non-trivially non-zero.
|
|
for (i, m) in blockMeans.enumerated() {
|
|
#expect(m >= 339.0 && m <= 541.0, "Block \(i) mean \(m) should be in LFO range [340, 540]")
|
|
}
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 5: Multiple parameter slots swap independently
|
|
|
|
/// Two @LiveParam properties on the same synth can have different sources without
|
|
/// cross-contamination. After swapping both, each delivers its own source's output.
|
|
@Test func multipleParamSlotsSwapIndependently() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: DualParamSynth = DualParamSynth()
|
|
synth.freq = 440.0
|
|
synth.amp = 0.5
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Swap freq with a sawtooth LFO producing values near 440.
|
|
let freqLFO: LFSawtooth.Control = LFSawtooth.Control(freq: 0.5, mul: 50.0, add: 440.0)
|
|
synth.$freq.source = freqLFO
|
|
|
|
// Swap amp with a constant source (simulating amp modulation).
|
|
// Use a simple ConstantParamSource implemented below.
|
|
let ampSource: ConstantIntegrationSource = ConstantIntegrationSource(0.3)
|
|
synth.$amp.source = ampSource
|
|
|
|
// Render 2 blocks to let both sources settle into the slots.
|
|
renderOneBlock(engine: engine)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Now read each ParameterNode directly to verify independence.
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
|
|
let freqSamples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let ampSamples: [Double] = synth.$amp.calculatedSamples(graph: g, count: blockSize)[0]
|
|
|
|
// freq should be around 440 ± 50 (LFO range).
|
|
let freqMean: Double = freqSamples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(freqMean >= 389.0 && freqMean <= 491.0,
|
|
"freq slot mean \(freqMean) should be in LFO range ~[390, 490]")
|
|
|
|
// amp should be exactly 0.3 (constant source).
|
|
for (i, s) in ampSamples.prefix(blockSize).enumerated() {
|
|
#expect(abs(s - 0.3) < 1e-10, "amp slot sample \(i): expected 0.3, got \(s)")
|
|
}
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 6: Source-graph chain (compound generator as source)
|
|
|
|
/// A compound generator (`LFSawtooth.Control * 50 + 440`) passed as the source
|
|
/// evaluates its own sub-graph correctly inside `_sourceSlot.calculatedSamples`.
|
|
@Test func sourceGraphChainEvaluatesCorrectly() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Build a compound source: raw LFSawtooth in [-1, 1] → scaled to [390, 490].
|
|
let rawLFO: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0)
|
|
let compoundSource: BinaryOpGenerator = rawLFO * 50.0 + 440.0
|
|
synth.$freq.source = compoundSource
|
|
|
|
// Render 2 blocks to install the source.
|
|
renderOneBlock(engine: engine)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Verify ParameterNode output is within expected range.
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let samples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let freqMean: Double = samples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(freqMean >= 388.0 && freqMean <= 492.0,
|
|
"Compound source mean \(freqMean) should be in expected range ~[390, 490]")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 7: Source generator with its own scalar parameter (documentation of limitation)
|
|
|
|
/// A source generator constructed with fixed scalar parameters works correctly. The
|
|
/// *source generator's own parameters* are fixed at construction time — they cannot be
|
|
/// updated via `updateParameter` on the *consuming synth* after the source is installed.
|
|
///
|
|
/// This is a known design limitation: `synth.$freq.source = lfo` wires `lfo` as a
|
|
/// source for `freq`. `lfo`'s own `freq` parameter is baked in at `LFSawtooth.Control`
|
|
/// init time and is not reachable via `synth.updateParameter("freq", ...)`.
|
|
///
|
|
/// If you need to change the source generator's parameters at runtime, keep a direct
|
|
/// reference to the source generator and modify it via its own `@LiveParam` (if it is
|
|
/// a `SynthesizerBase`), or reconstruct and reassign the source entirely.
|
|
@Test func sourceGeneratorWithFixedScalarParametersWorks() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// LFSawtooth at 1 Hz with mul=200 add=440 → range [240, 640] Hz.
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 1.0, mul: 200.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
|
|
// Render 2 blocks to install.
|
|
renderOneBlock(engine: engine)
|
|
renderOneBlock(engine: engine)
|
|
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let samples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let freqMean: Double = samples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
// Range [240, 640] Hz. The mean should be roughly mid-range (but LFO phase varies).
|
|
#expect(freqMean >= 239.0 && freqMean <= 641.0,
|
|
"Source with fixed scalar params: mean \(freqMean) should be in LFO range [240, 640]")
|
|
|
|
// KNOWN LIMITATION (documented): calling synth.updateParameter("freq", 880) would
|
|
// update $freq's scalar target, but when a source is active the scalar ramp is
|
|
// bypassed — the update to synth.freq has no immediate effect on audio output.
|
|
// Only removing the source (synth.$freq.source = nil) restores scalar control.
|
|
// This is intentional: the source overrides the scalar completely.
|
|
synth.freq = 880.0
|
|
renderOneBlock(engine: engine) // still LFO-driven
|
|
advanceBlock(engine)
|
|
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
|
let samplesAfterScalarWrite: [Double] = synth.$freq.calculatedSamples(graph: g2, count: blockSize)[0]
|
|
let meanAfterScalarWrite: Double = samplesAfterScalarWrite.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
// Still LFO-driven: should remain in [240, 640], NOT jump to 880.
|
|
#expect(meanAfterScalarWrite >= 239.0 && meanAfterScalarWrite <= 641.0,
|
|
"Scalar write while source is active should not override LFO; mean=\(meanAfterScalarWrite)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 8: Engine stop/play cycle preserves the source slot after rebuild
|
|
|
|
/// When a synth is removed, its @LiveParam ParameterNode instances persist (they are
|
|
/// `let` properties on the wrapper). When the synth is re-added, `rebuildGraph()` is
|
|
/// called, which reinitializes `outputGenerators` but re-registers the same `ParameterNode`
|
|
/// instances. The `_sourceQueue` and `_mainThreadSourceMirror` survive across the cycle
|
|
/// because they live on the `ParameterNode` (a heap object), not in `outputGenerators`.
|
|
///
|
|
/// However, `_sourceSlot` is RT-thread-owned and lives inside `calculatedSamples` state —
|
|
/// it is NOT reset by `rebuildGraph`. The source remains installed after re-add.
|
|
///
|
|
/// Policy: the source survives a remove+add cycle. Document this here.
|
|
@Test func engineStopPlayCyclePreservesSource() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Install source before removal.
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 0.5, mul: 80.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
|
|
// Let the source install itself (one block so _sourceSlot is populated).
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Source should be wired: verify ParameterNode mirror is non-nil.
|
|
#expect(synth.$freq.source != nil, "Source must be set before remove+add cycle")
|
|
|
|
// Remove and re-add.
|
|
engine.remove(synth)
|
|
renderOneBlock(engine: engine) // drain the remove event
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine) // drain the add event (and re-run build())
|
|
|
|
// The source property (mirror) is preserved across rebuild — the same ParameterNode
|
|
// is re-registered, its _mainThreadSourceMirror still points to lfo.
|
|
#expect(synth.$freq.source != nil, "Source mirror must survive remove+add cycle")
|
|
|
|
// Render 2 more blocks — the LFO should still be driving freq.
|
|
renderOneBlock(engine: engine)
|
|
renderOneBlock(engine: engine)
|
|
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let samples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let freqMean: Double = samples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(freqMean >= 359.0 && freqMean <= 521.0,
|
|
"After stop/play: freq mean \(freqMean) should still be in LFO range ~[360, 520]")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 9: Crossfade end-to-end (no click smoke test)
|
|
|
|
/// Swap with `crossfadeBlocks=8` between silence (amp=0.0 const source) and a
|
|
/// 0.9-amplitude constant source. The crossfade should produce monotonically rising
|
|
/// RMS across the 8 blocks — no abrupt spikes or drops.
|
|
@Test func crossfadeEndToEndNoClick() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
// Use DualParamSynth. Drive amp via ParameterNode source, freq fixed at 440.
|
|
let synth: DualParamSynth = DualParamSynth()
|
|
synth.freq = 440.0
|
|
synth.amp = 0.0 // start silent via scalar
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Install a "silence" constant source on the amp slot (output = 0.0).
|
|
let silenceSource: ConstantIntegrationSource = ConstantIntegrationSource(0.0)
|
|
synth.$amp.source = silenceSource
|
|
renderOneBlock(engine: engine) // install silence source
|
|
|
|
// Now crossfade from silence → 0.9 amplitude over 8 blocks.
|
|
let loudSource: ConstantIntegrationSource = ConstantIntegrationSource(0.9)
|
|
synth.$amp.setSource(loudSource, crossfadeBlocks: 8)
|
|
|
|
let crossfadeBlockCount: Int = 8
|
|
var blockRMS: [Double] = []
|
|
for _ in 0..<crossfadeBlockCount {
|
|
let samples: [Float] = renderOneBlock(engine: engine)
|
|
blockRMS.append(rms(samples))
|
|
}
|
|
|
|
// Verify RMS generally increases (within a loose tolerance of ±0.02 per step).
|
|
// This is a smoke test — we just verify no abrupt spikes or silence gaps.
|
|
for i: Int in 1..<blockRMS.count {
|
|
let delta: Double = blockRMS[i] - blockRMS[i - 1]
|
|
let msg: String = "Crossfade block \(i): RMS should not drop abruptly "
|
|
+ "(delta=\(delta), prev=\(blockRMS[i-1]), curr=\(blockRMS[i]))"
|
|
#expect(delta > -0.02, Comment(rawValue: msg))
|
|
}
|
|
|
|
// After crossfade, output should be non-trivially loud.
|
|
let postCrossfadeBlock: [Float] = renderOneBlock(engine: engine)
|
|
let postRMS: Double = rms(postCrossfadeBlock)
|
|
#expect(postRMS > 0.1, "Post-crossfade: should be loud (RMS>0.1), got \(postRMS)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 10: Stress — 100 rapid swaps
|
|
|
|
/// Loop 100 times: assign a new source to `synth.$freq`, render one block.
|
|
/// Verify engine never crashes, kill queue drains correctly, final source is last assigned.
|
|
@Test func stressOneHundredRapidSwaps() throws {
|
|
let blockSize: Int = 64
|
|
let swapCount: Int = 100
|
|
// Must use a smaller event queue to avoid pre-allocating a huge pending queue.
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Build a pool of sources with distinct outputs so the "last assigned" is detectable.
|
|
// Each source outputs its index value + 200 Hz (so range 200..299 Hz).
|
|
var sources: [ConstantIntegrationSource] = (0..<swapCount).map {
|
|
ConstantIntegrationSource(Double($0) + 200.0)
|
|
}
|
|
|
|
// Execute 100 swaps — one per block render.
|
|
var totalDrained: Int = 0
|
|
for i: Int in 0..<swapCount {
|
|
// Hard swap to the i-th source.
|
|
synth.$freq.source = sources[i]
|
|
|
|
// Render one block. The block's ParameterNode drain installs sources[i].
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Drain kill queue frequently to prevent overflow.
|
|
if i % 10 == 0 {
|
|
totalDrained += engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// Verify engine audio buses are finite (no NaN from bad pointer dereference).
|
|
let busSamples: [Float] = engine.audioBuses[0]
|
|
for (j, s) in busSamples.enumerated() {
|
|
#expect(s.isFinite, "Block \(i) sample \(j): must be finite during rapid swaps")
|
|
}
|
|
}
|
|
|
|
// Final drain.
|
|
totalDrained += engine.drainParameterSourceKillQueue()
|
|
|
|
// Overflow flag must be clear — the frequent drains should have prevented overflow.
|
|
let stressOverflowed: Bool = engine._killQueueOverflowed.load(ordering: .relaxed)
|
|
#expect(!stressOverflowed, "Kill queue must not have permanently overflowed during 100-swap stress test")
|
|
|
|
// Verify the last (99th) source is active: direct ParameterNode read.
|
|
advanceBlock(engine)
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let freqSamples: [Double] = synth.$freq.calculatedSamples(graph: g, count: blockSize)[0]
|
|
let freqMean: Double = freqSamples.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
// Last source: value = 99 + 200 = 299.0
|
|
let expectedFreq: Double = 299.0
|
|
#expect(abs(freqMean - expectedFreq) < 2.0,
|
|
"After 100 swaps, freq mean should be last-source value (\(expectedFreq)), got \(freqMean)")
|
|
|
|
// We need sources to stay alive until the test is done (they're class objects,
|
|
// but Swift ARC will keep them around as long as the array is alive).
|
|
sources.removeAll()
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 11: Generator-to-generator swap via property setter
|
|
|
|
/// Swap from one ControlGenerator source to a different one. Verify the transition
|
|
/// at the block boundary and that the old source is released.
|
|
@Test func generatorToGeneratorSwap() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Install first source: constant 300 Hz.
|
|
let src1: ConstantIntegrationSource = ConstantIntegrationSource(300.0)
|
|
synth.$freq.source = src1
|
|
renderOneBlock(engine: engine) // src1 installed in slot
|
|
|
|
// Verify src1 is active.
|
|
advanceBlock(engine)
|
|
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
|
let afterSrc1: [Double] = synth.$freq.calculatedSamples(graph: g1, count: blockSize)[0]
|
|
let meanSrc1: Double = afterSrc1.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(abs(meanSrc1 - 300.0) < 1.0, "src1 active: mean should be ~300 Hz, got \(meanSrc1)")
|
|
|
|
// Install second source: constant 700 Hz.
|
|
let src2: ConstantIntegrationSource = ConstantIntegrationSource(700.0)
|
|
synth.$freq.source = src2
|
|
renderOneBlock(engine: engine) // src2 installed, src1 pushed to kill queue
|
|
|
|
advanceBlock(engine)
|
|
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
|
let afterSrc2: [Double] = synth.$freq.calculatedSamples(graph: g2, count: blockSize)[0]
|
|
let meanSrc2: Double = afterSrc2.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(abs(meanSrc2 - 700.0) < 1.0, "src2 active: mean should be ~700 Hz, got \(meanSrc2)")
|
|
|
|
// Kill queue should contain src1.
|
|
let drained: Int = engine.drainParameterSourceKillQueue()
|
|
#expect(drained >= 1, "Kill queue must have src1 after generator-to-generator swap, got \(drained)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 12: Output is non-zero while source is active
|
|
|
|
/// A basic correctness check: with an LFO driving freq across 440 ± 100 Hz, the
|
|
/// synthesizer must produce audio (non-silent bus 0).
|
|
@Test func outputIsNonZeroWhileSourceIsActive() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
|
|
let lfo: LFSawtooth.Control = LFSawtooth.Control(freq: 0.5, mul: 100.0, add: 440.0)
|
|
synth.$freq.source = lfo
|
|
|
|
var anyBlockNonZero: Bool = false
|
|
for _ in 0..<8 {
|
|
let samples: [Float] = renderOneBlock(engine: engine)
|
|
if rms(samples) > 0.001 { anyBlockNonZero = true }
|
|
}
|
|
#expect(anyBlockNonZero, "At least one block should have non-zero audio while LFO source is active")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 13: Kill queue drains to zero after source is removed
|
|
|
|
/// After a source is removed (either by swap or nil), draining the kill queue must
|
|
/// eventually bring the count back to zero.
|
|
///
|
|
/// Note: The engine's background freeQueueTimer also calls `drainParameterSourceKillQueue`
|
|
/// periodically on a background thread while the engine is running. The test therefore
|
|
/// uses a DeinitSentinel to verify that the OLD source is eventually released, rather
|
|
/// than relying on an exact kill-queue item count (which may vary depending on timer
|
|
/// fire timing relative to block renders).
|
|
@Test func killQueueDrainsToZeroAfterRemoval() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 440.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Use a sentinel to detect ARC release of an installed + displaced source.
|
|
let sentinel: SourceSwapDeinitSentinel = SourceSwapDeinitSentinel()
|
|
do {
|
|
let sentinelSource: SentinelIntegrationSource = SentinelIntegrationSource(300.0, sentinel: sentinel)
|
|
synth.$freq.source = sentinelSource
|
|
renderOneBlock(engine: engine) // install sentinelSource into slot
|
|
|
|
// Displace sentinelSource by swapping in a new source.
|
|
let replacingSource: ConstantIntegrationSource = ConstantIntegrationSource(440.0)
|
|
synth.$freq.source = replacingSource
|
|
renderOneBlock(engine: engine) // sentinelSource pushed to kill queue
|
|
// sentinelSource local ref drops here at end of `do` scope.
|
|
}
|
|
|
|
// Now only the kill queue holds the retained pointer to sentinelSource.
|
|
// engine.stop() does a synchronous drain on the freeWorker queue, releasing it.
|
|
engine.stop()
|
|
#expect(sentinel.released, "sentinelSource must be released after engine.stop() drain")
|
|
|
|
// Re-start is needed because defer calls stop() again, but stop() is idempotent.
|
|
try engine.start()
|
|
}
|
|
|
|
// MARK: - Test 14: Crossfade via setSource helper wires through the engine
|
|
|
|
/// `synth.setSource(synth.$freq, to: src, crossfadeBlocks: 4)` must produce a
|
|
/// crossfade that is observable in the engine's output.
|
|
@Test func crossfadeViaSetSourceHelperIsObservable() throws {
|
|
let blockSize: Int = 256
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
// Use amp slot for easier crossfade observation (amplitude domain).
|
|
let synth: DualParamSynth = DualParamSynth()
|
|
synth.freq = 440.0
|
|
synth.amp = 0.0
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Install amp = 0 (silence) as the initial source.
|
|
let silentAmp: ConstantIntegrationSource = ConstantIntegrationSource(0.0)
|
|
synth.$amp.source = silentAmp
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Crossfade amp → 0.8 over 4 blocks.
|
|
let loudAmp: ConstantIntegrationSource = ConstantIntegrationSource(0.8)
|
|
synth.setSource(synth.$amp, to: loudAmp, crossfadeBlocks: 4)
|
|
|
|
// Collect the 4 crossfade block RMS values.
|
|
var blockRMS: [Double] = []
|
|
for _ in 0..<4 {
|
|
let samples: [Float] = renderOneBlock(engine: engine)
|
|
blockRMS.append(rms(samples))
|
|
}
|
|
|
|
// The amplitude envelope during crossfade should be rising.
|
|
// Block 0: ~12.5% loud, block 3: ~87.5% loud.
|
|
#expect(blockRMS.count == 4)
|
|
#expect(blockRMS[3] > blockRMS[0],
|
|
"Last crossfade block RMS (\(blockRMS[3])) should exceed first (\(blockRMS[0]))")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
|
|
// MARK: - Test 15: Scalar target survives across source swap and revert
|
|
|
|
/// The scalar target set via `synth.freq = 880.0` must be preserved while a source
|
|
/// is active and resume control after the source is removed.
|
|
@Test func scalarTargetSurvivesSourceSwapAndRevert() throws {
|
|
let blockSize: Int = 64
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: 44100)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let synth: FreqSynth = FreqSynth()
|
|
synth.freq = 880.0 // scalar target
|
|
try engine.add(synth)
|
|
renderOneBlock(engine: engine)
|
|
|
|
// Install a constant source at 200 Hz (overrides the scalar).
|
|
let src: ConstantIntegrationSource = ConstantIntegrationSource(200.0)
|
|
synth.$freq.source = src
|
|
renderOneBlock(engine: engine)
|
|
|
|
// While the source is active, read $freq directly — should be 200.0.
|
|
advanceBlock(engine)
|
|
let g1: SynthGraph = makeSynthGraph(engine: engine)
|
|
let while_src: [Double] = synth.$freq.calculatedSamples(graph: g1, count: blockSize)[0]
|
|
let meanWhileSrc: Double = while_src.prefix(blockSize).reduce(0.0, +) / Double(blockSize)
|
|
#expect(abs(meanWhileSrc - 200.0) < 1.0,
|
|
"While source is active, output should be 200 Hz, got \(meanWhileSrc)")
|
|
|
|
// Revert to scalar — scalar target is 880.0.
|
|
synth.$freq.source = nil
|
|
renderOneBlock(engine: engine) // drain the revert packet
|
|
|
|
// The next block should be ramping toward 880.0 from 200.0 (previousOutputValue).
|
|
advanceBlock(engine)
|
|
let g2: SynthGraph = makeSynthGraph(engine: engine)
|
|
let afterRevert: [Double] = synth.$freq.calculatedSamples(graph: g2, count: blockSize)[0]
|
|
let lastSample: Double = afterRevert[blockSize - 1]
|
|
// After one ramp block: last sample = scalar target (880 Hz).
|
|
#expect(abs(lastSample - 880.0) < 1.0,
|
|
"After revert, last sample should converge to scalar 880 Hz, got \(lastSample)")
|
|
|
|
engine.drainParameterSourceKillQueue()
|
|
}
|
|
}
|
|
|
|
// MARK: - File-private ControlGenerator helpers
|
|
|
|
/// A constant-output `ControlGenerator` for integration tests. Produces a flat block at
|
|
/// `outputValue` regardless of inputs.
|
|
///
|
|
/// Declared `@unchecked Sendable` per the convention for test helpers (output is immutable
|
|
/// after init; only one thread evaluates `calculatedSamples` at a time — the RT thread).
|
|
private final class ConstantIntegrationSource: GeneratorBase, ControlGenerator, @unchecked Sendable {
|
|
|
|
let outputValue: Double
|
|
var previousOutputValue: Double
|
|
|
|
init(_ value: Double) {
|
|
outputValue = value
|
|
previousOutputValue = value
|
|
super.init()
|
|
_setupSubBlockBuffer()
|
|
}
|
|
|
|
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
|
precondition(count <= _result[0].count,
|
|
"ConstantIntegrationSource: count \(count) exceeds buffer")
|
|
for i: Int in 0..<count { _result[0][i] = outputValue }
|
|
return _result
|
|
}
|
|
|
|
func floatValue(graph: SynthGraph) -> Double { outputValue }
|
|
}
|
|
|
|
/// Observable flag set by `SentinelIntegrationSource.deinit` — used to verify ARC release.
|
|
private final class SourceSwapDeinitSentinel {
|
|
var released: Bool = false
|
|
}
|
|
|
|
/// A constant-output `ControlGenerator` that sets its sentinel flag when dealloc'd.
|
|
private final class SentinelIntegrationSource: GeneratorBase, ControlGenerator, @unchecked Sendable {
|
|
|
|
let outputValue: Double
|
|
var previousOutputValue: Double
|
|
private let _sentinel: SourceSwapDeinitSentinel
|
|
|
|
init(_ value: Double, sentinel: SourceSwapDeinitSentinel) {
|
|
outputValue = value
|
|
previousOutputValue = value
|
|
_sentinel = sentinel
|
|
super.init()
|
|
_setupSubBlockBuffer()
|
|
}
|
|
|
|
deinit { _sentinel.released = true }
|
|
|
|
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
|
precondition(count <= _result[0].count,
|
|
"SentinelIntegrationSource: count \(count) exceeds buffer")
|
|
for i: Int in 0..<count { _result[0][i] = outputValue }
|
|
return _result
|
|
}
|
|
|
|
func floatValue(graph: SynthGraph) -> Double { outputValue }
|
|
}
|