v2.1.1 release: delay-click fix + internal consolidation

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>
This commit is contained in:
2026-10-07 21:20:49 -07:00
parent 844dc4d9cd
commit f8878324fd
212 changed files with 1386 additions and 2549 deletions
@@ -0,0 +1,68 @@
// BlockRateControlGeneratorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BlockRateControlGenerator")
struct BlockRateControlGeneratorTests {
/// A `BlockRateControlGenerator` must resolve `calculatedSamples` to the block-rate
/// gateway (the marker's protocol-extension default), NOT the `ControlGenerator`
/// sub-block path — even when `controlBlockSize < blockSize`. These generators drop
/// the `_setupSubBlockBuffer()` allocation, so if the sub-block path were wrongly
/// selected it would trap on the empty `_subBlockBuffer`. No trap + correct output
/// proves the marker default won the `ValidGeneratorInput.calculatedSamples` witness.
@Test func markedControlDoesNotEnterSubBlockPath() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, controlBlockSize: 64, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
numAudioBuses: 128, numControlBuses: 4096,
driver: OfflineDriver())
try engine.start()
defer { engine.stop() }
#expect(engine.controlBlockSize < engine.blockSize)
// Lag with time 0 is transparent; a unit input settles to ~1.0 within the block.
let lag: Lag.Control = Lag.Control(input: ConstantAudioGen(1.0), time: 0.0)
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [Double] = lag.calculatedSamples(graph: g, count: engine.blockSize)[0]
#expect(out.count >= engine.blockSize)
#expect(out.prefix(engine.blockSize).allSatisfy { $0.isFinite })
#expect(abs(out[engine.blockSize - 1] - 1.0) < 1e-6, "got \(out[engine.blockSize - 1])")
// The real graph calls through `any ValidGeneratorInput`, which resolves via the
// witness table (not concrete-type overload ranking). Exercise that path too: a
// wrong witness (the ControlGenerator sub-block gateway) would still trap here.
let erased: any ValidGeneratorInput = lag
let g2: SynthGraph = makeSynthGraph(engine: engine)
advanceBlock(engine)
let out2: [Double] = erased.calculatedSamples(graph: g2, count: engine.blockSize)[0]
#expect(out2.prefix(engine.blockSize).allSatisfy { $0.isFinite })
#expect(abs(out2[engine.blockSize - 1] - 1.0) < 1e-6, "got \(out2[engine.blockSize - 1])")
}
/// Same guarantee through a `BlockRateControlGenerator` conformer that INHERITS the
/// conformance from a non-final base (`SpectralFeatureControlBase`) rather than
/// declaring it directly — the witness must still resolve to the block-rate default.
@Test func inheritedMarkerConformanceDoesNotSubBlock() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512, controlBlockSize: 64, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
numAudioBuses: 128, numControlBuses: 4096,
driver: OfflineDriver())
try engine.start()
defer { engine.stop() }
let buffer: SpectralBuffer = SpectralBuffer(fftSize: 1024)
let centroid: any ValidGeneratorInput = SpectralCentroid.Control(spectral: buffer, sampleRate: 44100)
let g: SynthGraph = makeSynthGraph(engine: engine)
let out: [Double] = centroid.calculatedSamples(graph: g, count: engine.blockSize)[0]
#expect(out.prefix(engine.blockSize).allSatisfy { $0.isFinite })
}
}
@@ -0,0 +1,47 @@
// DelayLineAllpassModulationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - DelayLineAllpassModulationTests
/// Regression guard for the allpass fractional-delay interpolator's recursive-state
/// handling. When the delay lands on an exact integer sample (`frac == 0`) the interpolator
/// bypasses to the integer-delayed sample; its recursive state must record that sample as
/// the previous output. Leaving it stale (freezing the pre-bypass value) clicks when the
/// delay dwells on an integer and then moves off. The timeline dwells on an exact integer
/// then ramps a fractional delay out, and the allpass step is compared against the same
/// modulation through `.linear` interpolation, which has no recursive state and stays smooth.
@MainActor
@Suite("DelayLine allpass modulation")
struct DelayLineAllpassModulationTests {
/// Allpass-vs-linear sample-step ratio tolerated. Correct state handling keeps this
/// ~1×; freezing the stale state drives it past 3× for DelayLine.
let clickRatioLimit: Double = 2.0
@Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws {
let timeline: [Double] = modulatedDelayDwellTimeline()
let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
DelayLine(input: input, maxDelay: maxDelay, delay: modulator,
sampleRate: delaySweepSampleRate, interpolation: .linear)
}
let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
DelayLine(input: input, maxDelay: maxDelay, delay: modulator,
sampleRate: delaySweepSampleRate, interpolation: .allpass)
}
#expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite")
let linearStep: Double = maxAbsDelta(linear)
let allpassStep: Double = maxAbsDelta(allpass)
#expect(linearStep > 0, "linear reference should have non-zero motion")
#expect(
allpassStep < clickRatioLimit * linearStep,
"modulated allpass delay clicks at integer dwell/crossing: allpass maxΔ \(allpassStep) vs linear \(linearStep)"
)
}
}
@@ -0,0 +1,48 @@
// DelayLineFeedbackAllpassModulationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - DelayLineFeedbackAllpassModulationTests
/// Regression guard for the allpass fractional-delay interpolator's recursive-state
/// handling in `DelayLineFeedback` under delay modulation. On an exact integer delay
/// (`frac == 0`) the interpolator must record the integer-delayed sample as its previous
/// output; freezing the stale value clicks when the delay moves back off the integer. Measured against
/// the same modulation through `.linear` interpolation. See
/// `DelayLineAllpassModulationTests` for the timeline rationale.
@MainActor
@Suite("DelayLineFeedback allpass modulation")
struct DelayLineFeedbackAllpassModulationTests {
let clickRatioLimit: Double = 2.0
/// Moderate feedback — high feedback rings enough to mask the click in the global metric.
let feedbackDecayTime: Double = 0.012
@Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws {
let timeline: [Double] = modulatedDelayDwellTimeline()
let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
DelayLineFeedback(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .linear)
}
let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
DelayLineFeedback(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .allpass)
}
#expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite")
let linearStep: Double = maxAbsDelta(linear)
let allpassStep: Double = maxAbsDelta(allpass)
#expect(linearStep > 0, "linear reference should have non-zero motion")
#expect(
allpassStep < clickRatioLimit * linearStep,
"modulated allpass feedback delay clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)"
)
}
}
@@ -0,0 +1,50 @@
// AllpassFilterModulationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - AllpassFilterModulationTests
/// Regression guard for the allpass fractional-delay interpolator's recursive-state
/// handling in `AllpassFilter` under delay modulation. The Schroeder allpass reads both an
/// input- and an output-history buffer through the interpolator; at an exact integer delay
/// (`frac == 0`) each interpolator must record its integer-delayed read as the previous
/// output. This two-history form clicks both if the state is zeroed and if the stale
/// pre-bypass value is frozen across an integer dwell. Measured against
/// the same modulation through `.linear` interpolation. See
/// `DelayLineAllpassModulationTests` for the timeline rationale.
@MainActor
@Suite("AllpassFilter allpass modulation")
struct AllpassFilterModulationTests {
let clickRatioLimit: Double = 2.0
/// Moderate feedback — high feedback rings enough to mask the click in the global metric.
let feedbackDecayTime: Double = 0.012
@Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws {
let timeline: [Double] = modulatedDelayDwellTimeline()
let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
AllpassFilter(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .linear)
}
let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
AllpassFilter(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .allpass)
}
#expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite")
let linearStep: Double = maxAbsDelta(linear)
let allpassStep: Double = maxAbsDelta(allpass)
#expect(linearStep > 0, "linear reference should have non-zero motion")
#expect(
allpassStep < clickRatioLimit * linearStep,
"modulated allpass filter clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)"
)
}
}
@@ -0,0 +1,50 @@
// CombFilterAllpassModulationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - CombFilterAllpassModulationTests
/// Regression guard for the allpass fractional-delay interpolator's recursive-state
/// handling in `CombFilter` under delay modulation. On an exact integer delay
/// (`frac == 0`) the interpolator must record the integer-delayed sample as its previous
/// output; freezing the stale value clicks when the delay moves back off the integer. Measured against
/// the same modulation through `.linear` interpolation. See
/// `DelayLineAllpassModulationTests` for the timeline rationale.
@MainActor
@Suite("CombFilter allpass modulation")
struct CombFilterAllpassModulationTests {
let clickRatioLimit: Double = 2.0
/// Moderate feedback. High feedback rings strongly enough to mask the state-handling
/// click in the global step metric; this level keeps the stale-state (frozen) click well
/// above the linear-interpolation reference while the fix stays ~1×.
let feedbackDecayTime: Double = 0.012
@Test func modulatedAllpassDelayStaysClickFreeThroughIntegerDwell() throws {
let timeline: [Double] = modulatedDelayDwellTimeline()
let linear: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
CombFilter(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .linear)
}
let allpass: [Double] = try renderModulatedDelay(delaySamples: timeline) { input, modulator, maxDelay in
CombFilter(input: input, maxDelay: maxDelay, delay: modulator,
decayTime: feedbackDecayTime, sampleRate: delaySweepSampleRate,
interpolation: .allpass)
}
#expect(allpass.allSatisfy { $0.isFinite }, "allpass output must be finite")
let linearStep: Double = maxAbsDelta(linear)
let allpassStep: Double = maxAbsDelta(allpass)
#expect(linearStep > 0, "linear reference should have non-zero motion")
#expect(
allpassStep < clickRatioLimit * linearStep,
"modulated allpass comb clicks at integer dwell exit: allpass maxΔ \(allpassStep) vs linear \(linearStep)"
)
}
}
+50
View File
@@ -243,4 +243,54 @@ struct MulAddSpecChannelAwareTests {
// 4-row generator as `mul:` to a 2-channel `Pan2` traps with "MulAddSpec: mul has
// 4 channels but output has 2. mul/add must be mono (broadcast) or match the
// output channel count."
// MARK: - applyScalar (Math.Control scalar fold)
@Test func applyScalarIdentityReturnsTargetUnchanged() {
let spec: MulAddSpec = MulAddSpec(mul: 1.0, add: 0.0)
#expect(spec.isIdentity)
#expect(spec.applyScalar(0.42, graph: graph) == 0.42)
}
@Test func applyScalarFoldsScalarMulAdd() {
let spec: MulAddSpec = MulAddSpec(mul: 2.0, add: 1.0)
#expect(!spec.isIdentity)
// 3.0 × 2.0 + 1.0 = 7.0
#expect(abs(spec.applyScalar(3.0, graph: graph) - 7.0) < 1e-12)
}
@Test func applyScalarReadsGeneratorValuedMulAdd() {
let spec: MulAddSpec = MulAddSpec(mul: ConstantAudioGen(2.0), add: ConstantAudioGen(1.0))
#expect(!spec.isIdentity)
#expect(abs(spec.applyScalar(3.0, graph: graph) - 7.0) < 1e-12)
}
// MARK: - fillHeldResult (held-constant Control fill)
@Test func fillHeldResultFillsConstantAndSetsPrevious() {
var result: [[Double]] = [[Double](repeating: 0.0, count: 8)]
var prev: Double = -1.0
fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev,
mulAdd: .identity, graph: graph, count: 8)
#expect(result[0].allSatisfy { $0 == 0.5 })
#expect(prev == 0.5)
}
@Test func fillHeldResultAppliesMulAdd() {
var result: [[Double]] = [[Double](repeating: 0.0, count: 4)]
var prev: Double = 0.0
let spec: MulAddSpec = MulAddSpec(mul: 2.0, add: 1.0) // 0.5 × 2 + 1 = 2.0
fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev,
mulAdd: spec, graph: graph, count: 4)
#expect(result[0].allSatisfy { abs($0 - 2.0) < 1e-12 })
#expect(abs(prev - 2.0) < 1e-12)
}
@Test func fillHeldResultCountZeroLeavesStateUntouched() {
var result: [[Double]] = [[Double](repeating: 9.0, count: 4)]
var prev: Double = 7.0
fillHeldResult(into: &result, value: 0.5, previousOutputValue: &prev,
mulAdd: .identity, graph: graph, count: 0)
#expect(prev == 7.0)
}
}
+119
View File
@@ -127,6 +127,125 @@ func rmsValue(_ samples: [Double]) -> Double {
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 {