f8878324fd
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release: fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/ DelayLineFeedback under a modulated delay) and lands the internal code-quality consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical output). No public API removed or changed. See RELEASES.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
262 lines
9.6 KiB
Swift
262 lines
9.6 KiB
Swift
// TestHelpers.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
func makeTestEngine(
|
|
blockSize: Int = 512,
|
|
sampleRate: Double = 44100,
|
|
numOutputChannels: Int = 2,
|
|
numInputChannels: Int = 2,
|
|
numAudioBuses: Int = 128,
|
|
numControlBuses: Int = 4096,
|
|
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
|
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock
|
|
) -> SynthesisEngine {
|
|
SynthesisEngine(
|
|
blockSize: blockSize,
|
|
sampleRate: sampleRate,
|
|
numOutputChannels: numOutputChannels,
|
|
numInputChannels: numInputChannels,
|
|
numAudioBuses: numAudioBuses,
|
|
numControlBuses: numControlBuses,
|
|
eventQueueCapacity: eventQueueCapacity,
|
|
maxEventsPerBlock: maxEventsPerBlock,
|
|
driver: OfflineDriver()
|
|
)
|
|
}
|
|
|
|
/// Create a started engine suitable for step-sequencer tests (small blockSize for fine timing).
|
|
func makeSeqEngine() throws -> SynthesisEngine {
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
|
try engine.start()
|
|
return engine
|
|
}
|
|
|
|
func makeSynthGraph(engine: SynthesisEngine, busOffset: Int = 0) -> SynthGraph {
|
|
SynthGraph(engine: engine, busOffset: busOffset)
|
|
}
|
|
|
|
// MARK: - Synthesizer test fixtures
|
|
|
|
/// Writes a constant value to an audio bus every block.
|
|
final class ConstantSynth: SynthesizerBase {
|
|
let value: Double
|
|
let outputBus: Int
|
|
|
|
init(value: Double, outputBus: Int = 0) {
|
|
self.value = value
|
|
self.outputBus = outputBus
|
|
super.init()
|
|
}
|
|
|
|
override func build() {
|
|
addOutputGenerator(Out.Audio(bus: outputBus, source: value))
|
|
}
|
|
}
|
|
|
|
/// Reads from one audio bus and accumulates into another — for ordering tests.
|
|
final class RoutingSynth: SynthesizerBase {
|
|
let inputBus: Int
|
|
let outputBus: Int
|
|
|
|
init(inputBus: Int, outputBus: Int) {
|
|
self.inputBus = inputBus
|
|
self.outputBus = outputBus
|
|
super.init()
|
|
}
|
|
|
|
override func build() {
|
|
addOutputGenerator(Out.Audio(bus: outputBus, source: In.Audio(bus: inputBus)))
|
|
}
|
|
}
|
|
|
|
/// Counts build() invocations. Does not subclass SynthesizerBase so evaluate() is freely
|
|
/// implementable — SynthesizerBase.evaluate is final (by design), so overriding it in a
|
|
/// test subclass would be a compile error.
|
|
final class TrackingSynth: Synthesizer {
|
|
var buildCallCount: Int = 0
|
|
var evaluateCallCount: Int = 0
|
|
|
|
func build() {
|
|
buildCallCount += 1
|
|
}
|
|
|
|
func evaluate(graph: SynthGraph, count: Int) {
|
|
evaluateCallCount += 1
|
|
}
|
|
}
|
|
|
|
/// Drive a generator for `blocks` blocks and return exactly `blockSize` samples per block.
|
|
func collectBlocks(
|
|
_ gen: any Generator,
|
|
engine: SynthesisEngine,
|
|
blocks: Int
|
|
) -> [Double] {
|
|
let bs: Int = engine.blockSize
|
|
var out: [Double] = []
|
|
out.reserveCapacity(blocks * bs)
|
|
for _ in 0..<blocks {
|
|
let g: SynthGraph = makeSynthGraph(engine: engine)
|
|
let block: [Double] = gen.calculatedSamples(graph: g, count: bs)[0]
|
|
out += block.prefix(bs)
|
|
advanceBlock(engine)
|
|
}
|
|
return out
|
|
}
|
|
|
|
/// Advances the fan-out cache serial as if `evaluateSegment` had been called.
|
|
///
|
|
/// Use between multiple `calculatedSamples` calls in a single test to simulate block
|
|
/// boundaries. Tests that call the same generator instance twice within one test function
|
|
/// would otherwise receive a cache hit on the second call because `engine.segmentSerial`
|
|
/// is only incremented by `evaluateSegment`, which is not invoked directly by unit tests.
|
|
func advanceBlock(_ engine: SynthesisEngine) {
|
|
engine.advanceSegmentSerial()
|
|
}
|
|
|
|
/// Root-mean-square of a sample buffer. Returns 0 for empty input.
|
|
func rmsValue(_ samples: [Double]) -> Double {
|
|
guard !samples.isEmpty else { return 0 }
|
|
var sumSq: Double = 0.0
|
|
for s: Double in samples { sumSq += s * s }
|
|
return (sumSq / Double(samples.count)).squareRoot()
|
|
}
|
|
|
|
/// Largest absolute sample-to-sample difference in a buffer — a click/discontinuity
|
|
/// proxy. Returns 0 for buffers shorter than two samples.
|
|
func maxAbsDelta(_ samples: [Double]) -> Double {
|
|
guard samples.count > 1 else { return 0 }
|
|
var maxDelta: Double = 0.0
|
|
for i: Int in 1..<samples.count {
|
|
maxDelta = max(maxDelta, abs(samples[i] - samples[i - 1]))
|
|
}
|
|
return maxDelta
|
|
}
|
|
|
|
/// Test-only audio-rate generator that plays back a precomputed per-sample delay
|
|
/// timeline (delay expressed in **samples**), advancing one entry per output sample
|
|
/// across blocks and emitting each entry divided by `sampleRate` (so the consuming
|
|
/// delay line's `delaySecs · sampleRate` recovers the sample count). Entries past the
|
|
/// end of the timeline repeat the last value.
|
|
///
|
|
/// With a power-of-two `sampleRate` and integer (or `1/2^k`-fraction) sample-delay
|
|
/// entries, the samples↔seconds round-trip is exact, so a delay line's `frac == 0`
|
|
/// interpolation branch is hit deterministically — the condition needed to exercise
|
|
/// fractional-delay state handling across integer boundaries.
|
|
final class TimelineDelayGenerator: GeneratorBase, AudioGenerator {
|
|
private let delaySamples: [Double]
|
|
private let sr: Double
|
|
private var pos: Int = 0
|
|
|
|
init(
|
|
delaySamples: [Double],
|
|
sampleRate: Double
|
|
) {
|
|
self.delaySamples = delaySamples
|
|
self.sr = sampleRate
|
|
super.init()
|
|
}
|
|
|
|
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
|
_checkCount(count)
|
|
let lastIndex: Int = delaySamples.count - 1
|
|
for i: Int in 0..<count {
|
|
let index: Int = min(pos, lastIndex)
|
|
_result[0][i] = (index >= 0 ? delaySamples[index] : 0) / sr
|
|
pos += 1
|
|
}
|
|
return _result
|
|
}
|
|
}
|
|
|
|
// MARK: - Modulated-delay click-regression harness
|
|
|
|
/// Power-of-two sample rate so a delay-in-samples value divided by it, then multiplied
|
|
/// back by the engine rate, recovers the exact integer — letting a delay line's
|
|
/// `frac == 0` branch be hit deterministically.
|
|
let delaySweepSampleRate: Double = 32768
|
|
let delaySweepBlockSize: Int = 64
|
|
/// Dropped from the front of a rendered timeline before measuring (buffer-fill transient).
|
|
let delaySweepWarmupSamples: Int = 256
|
|
/// Headroom in samples added above the timeline's peak delay when sizing the ring buffer.
|
|
let delaySweepMaxDelayHeadroom: Double = 8
|
|
private let delaySweepToneHz: Double = 1234.0
|
|
private let delaySweepToneAmp: Double = 0.5
|
|
|
|
/// Builds a delay-in-samples timeline that **dwells on an exact integer** (`frac == 0`,
|
|
/// the interpolator bypass branch) for a stretch, then ramps a fractional delay back out.
|
|
/// The dwell lets the recursive allpass state settle; the ramp-out's first fractional
|
|
/// sample then reveals how the bypass branch left that state. Recording the integer-delayed
|
|
/// output as the interpolator's previous output stays click-free; freezing the pre-dwell
|
|
/// value emits a transient (it is now stale), and for the two-history Schroeder allpass
|
|
/// zeroing the state also emits one. A power-of-two engine rate keeps the integer delay
|
|
/// exact so the bypass branch is hit deterministically.
|
|
func modulatedDelayDwellTimeline() -> [Double] {
|
|
let holdSamples: Int = 1024
|
|
let rampOutSamples: Int = 1024
|
|
let holdDelay: Double = 56.0 // exact integer; exact on a power-of-two rate
|
|
let incPerSample: Double = 1.0 / 64.0
|
|
|
|
var timeline: [Double] = []
|
|
timeline.reserveCapacity(holdSamples + rampOutSamples)
|
|
for _: Int in 0..<holdSamples {
|
|
timeline.append(holdDelay)
|
|
}
|
|
for i: Int in 0..<rampOutSamples {
|
|
timeline.append(holdDelay + incPerSample * Double(i))
|
|
}
|
|
return timeline
|
|
}
|
|
|
|
/// Renders a delay-family generator over a delay-in-samples timeline and returns the
|
|
/// output with the warm-up transient trimmed. `makeNode` builds the node under test from
|
|
/// the shared steady-tone input, the timeline modulator, and the ring-buffer `maxDelay`
|
|
/// (seconds) sized to cover the timeline's peak.
|
|
@MainActor
|
|
func renderModulatedDelay(
|
|
delaySamples: [Double],
|
|
sampleRate: Double = delaySweepSampleRate,
|
|
blockSize: Int = delaySweepBlockSize,
|
|
makeNode: (_ input: OscSin.Audio, _ modulator: TimelineDelayGenerator, _ maxDelay: Double) -> any Generator
|
|
) throws -> [Double] {
|
|
let engine: SynthesisEngine = makeTestEngine(blockSize: blockSize, sampleRate: sampleRate)
|
|
try engine.start()
|
|
defer { engine.stop() }
|
|
|
|
let input: OscSin.Audio = OscSin.Audio(freq: delaySweepToneHz, mul: delaySweepToneAmp)
|
|
let modulator: TimelineDelayGenerator = TimelineDelayGenerator(
|
|
delaySamples: delaySamples,
|
|
sampleRate: sampleRate
|
|
)
|
|
let peakDelaySamples: Double = (delaySamples.max() ?? 1) + delaySweepMaxDelayHeadroom
|
|
let node: any Generator = makeNode(input, modulator, peakDelaySamples / sampleRate)
|
|
|
|
var out: [Double] = []
|
|
let blockCount: Int = Int((Double(delaySamples.count) / Double(blockSize)).rounded(.up))
|
|
for _: Int in 0..<blockCount {
|
|
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
|
out += Array(node.calculatedSamples(graph: graph, count: blockSize)[0].prefix(blockSize))
|
|
advanceBlock(engine)
|
|
}
|
|
return Array(out.dropFirst(delaySweepWarmupSamples))
|
|
}
|
|
|
|
/// Minimal Synthesizer conformer for Group isolation tests (no engine startup needed).
|
|
/// Records how many times evaluate() is called and what count was passed.
|
|
final class TrackingNode: Synthesizer {
|
|
var evaluateCallCount: Int = 0
|
|
var lastCount: Int = 0
|
|
|
|
func build() {}
|
|
|
|
func evaluate(graph: SynthGraph, count: Int) {
|
|
evaluateCallCount += 1
|
|
lastCount = count
|
|
}
|
|
}
|