Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift
T
josh d1f823e54c feat(pedals): add Karplus Resonator, Tape Looper, and DL4 delay
Three new pedals, each wired at all four points (PedalType, PedalRegistry,
PedalCategory, README) and covered by a dedicated test suite.

Karplus Resonator (texture): a bank of four tuned KarplusStrong strings
plucked by an amplitude-envelope → Schmitt-trigger gate off the note onset,
ringing sympathetically in the tail. Tune / Sustain / Tone / Sensitivity
knobs plus a Voicing selector (Drone / Octaves / Shimmer). Bank summed at
1/stringCount so a full-scale pluck stays at or below unity.

Tape Looper (texture): a simple single-track looper (RecordBuffer /
PlayBuffer) with record / overdub / play and the two classic tape tricks —
half-speed (octave down) and reverse — as live playback-rate controls.
Overdub is gated to forward-normal speed both at engage time and in the
graph, so flipping Reverse/Half-Speed mid-overdub can't misalign layers.

DL4 (delay): an umbrella multi-model delay with a Model selector dispatching
to eight per-model builders — Tube, Tape, Analog, Analog Mod, Multi-Head,
Sweep, Lo-Res, Reverse — over shared Time / Repeats / Tone / Mod controls,
Time tempo-syncable. Multi-Head tap sum gain-staged to 1.0.

Passed /lyrebird_external_review (RT-safety + caveman sweep); all blocking
findings fixed. Full suite 791 tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 14:47:51 -08:00

387 lines
16 KiB
Swift

// KarplusResonatorPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A single decaying pluck: a sine whose amplitude ramps from full to zero over `burstDur`, then
/// holds silent. Lets a test see the resonator bank ring on in the silence after the note has gone.
@MainActor
private final class TestPluckSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
private let amp: Double
private let burstDur: Double
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
self.targetBus = targetBus
self.freq = freq
self.amp = amplitude
self.burstDur = burstDur
super.init()
}
override func build() {
// Line 1→0 over burstDur, holding 0 after — a pluck that decays to silence, so the pedal's
// gate opens during the note and closes once it has faded, letting the strings ring.
let env: Line.Control = Line.Control(start: amp, end: 0.0, dur: burstDur)
output(bus: targetBus, source: OscSin.Audio(freq: freq) * env)
}
}
/// A steady sine source for the bypass click test — a stable tone with no silence, so the transition
/// step can be compared against a real steady-state slope.
@MainActor
private final class TestSineSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
private let amp: Double
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
self.targetBus = targetBus
self.freq = freq
self.amp = amplitude
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
}
}
@MainActor
@Suite("KarplusResonatorPedal")
struct KarplusResonatorPedalTests {
private let sampleRate: Double = 44_100.0
private let pluckHz: Double = 110.0
private let burstDur: Double = 0.4
/// Minimum RMS to count a tail as an audible, sustained ring.
private let tailRmsFloor: Double = 1.0e-3
// MARK: - Render
private func renderPluck(
duration: Double = 2.0,
amplitude: Double = 0.7,
configure: (KarplusResonatorPedal) -> Void
) throws -> [Float] {
try render(duration: duration, pluck: true, amplitude: amplitude, configure: configure)
}
private func render(
duration: Double,
pluck: Bool,
amplitude: Double = 0.7,
configure: (KarplusResonatorPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: SynthesizerBase = pluck
? TestPluckSource(targetBus: srcBus.index, freq: pluckHz, amplitude: amplitude, burstDur: burstDur)
: TestSineSource(targetBus: srcBus.index, freq: pluckHz)
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
// MARK: - Analysis
/// RMS of the left channel over an interleaved-frame range `[loFrame, hiFrame)`.
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
let a: Int = max(0, loFrame)
let b: Int = min(hiFrame, samples.count / 2)
guard b > a else { return 0.0 }
var sum: Double = 0.0
for i: Int in a ..< b {
let v: Double = Double(samples[2 * i])
sum += v * v
}
return (sum / Double(b - a)).squareRoot()
}
/// Autocorrelation fundamental of the left channel over `[skip, skip + window)`, searching
/// `[minHz, maxHz]`.
private func fundamentalHz(
_ samples: [Float],
skip: Int,
window: Int,
minHz: Double,
maxHz: Double
) -> Double {
let needed: Int = skip + window
guard samples.count >= 2 * needed else { return 0.0 }
var x: [Double] = []
x.reserveCapacity(window)
for i: Int in skip ..< needed {
x.append(Double(samples[2 * i]))
}
let mean: Double = x.reduce(0.0, +) / Double(x.count)
for i: Int in x.indices { x[i] -= mean }
let minLag: Int = Int(sampleRate / maxHz)
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
guard maxLag > minLag else { return 0.0 }
var bestLag: Int = minLag
var bestCorr: Double = -Double.infinity
for lag: Int in minLag ... maxLag {
var c: Double = 0.0
for i: Int in 0 ..< (x.count - lag) {
c += x[i] * x[i + lag]
}
if c > bestCorr {
bestCorr = c
bestLag = lag
}
}
return sampleRate / Double(bestLag)
}
/// RMS of the sample-by-sample difference between two renders' left channels over `[loFrame, hiFrame)`.
private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double {
let lo: Int = max(0, loFrame)
let hi: Int = min(hiFrame, min(a.count, b.count) / 2)
guard hi > lo else { return 0.0 }
var sum: Double = 0.0
for i: Int in lo ..< hi {
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
sum += d * d
}
return (sum / Double(hi - lo)).squareRoot()
}
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
let a: Int = max(1, lo)
let b: Int = min(hi, x.count)
guard b > a else { return 0.0 }
var m: Double = 0.0
for i: Int in a ..< b {
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
if d > m { m = d }
}
return m
}
/// Start of the tail-analysis window, in frames — well past the pluck's decay to silence, so only
/// the ringing resonator bank remains.
private var tailSkipFrames: Int { Int(0.7 * sampleRate) }
/// Tail-analysis window length in frames (~0.37 s).
private var tailWindowFrames: Int { 16_384 }
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try renderPluck { _ in }
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "resonator output was silent")
}
@Test func ringsAfterNoteDecays() throws {
// The pluck decays to silence by burstDur (0.4 s). A plain effect would then be silent; the
// sympathetic strings keep ringing, so the tail well past the note is non-trivial.
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
}
let tail: Double = rms(out, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
#expect(tail > tailRmsFloor, "expected a sustained sympathetic ring after the note, tail RMS \(tail)")
}
@Test func tailIsPitchedToTuneRoot() throws {
// Drone voicing tunes the strings to root/5th/oct/oct+5th, which all share the root's period,
// so the ringing tail's fundamental sits at the Tune root (not the 110 Hz pluck pitch).
let tune: Double = 82.41
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 0.0
}
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 40.0, maxHz: 400.0)
let tolerance: Double = 0.1
#expect(abs(f - tune) / tune < tolerance,
"tail fundamental \(f) Hz should sit near the Tune root \(tune) Hz")
}
@Test func sustainLengthensTheTail() throws {
// More sustain = higher string feedback = a louder ring at the same point in the tail.
let low: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.1; pedal.sensitivity = 0.6
}
let high: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.95; pedal.sensitivity = 0.6
}
let tailLow: Double = rms(low, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
let tailHigh: Double = rms(high, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
#expect(tailHigh > tailLow,
"higher sustain should ring louder in the tail: high \(tailHigh) vs low \(tailLow)")
}
@Test func voicingRetunesTheRing() throws {
// Each voicing tunes the strings to a different chord, so the ringing tail differs
// substantially between two voicings at the same Tune root.
let tune: Double = 82.41
let drone: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 0.0
}
let octaves: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 1.0
}
let diff: Double = rmsDiff(drone, octaves, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
let droneTail: Double = rms(drone, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
// The difference should be a real fraction of the ring, not analysis noise.
#expect(diff > droneTail * 0.25,
"two voicings should ring differently: tail diff \(diff) vs drone tail \(droneTail)")
}
@Test func renderIsDeterministic() throws {
// Every node in the bank is deterministic (no RNG), so two identical renders are bit-identical.
let a: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
let b: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
#expect(a == b, "deterministic resonator renders of the same setting should be bit-identical")
}
@Test func fullScaleBankStaysBelowClipping() throws {
// A full-scale pluck at max sustain, fully wet. The bank is scaled by 1/stringCount, so even
// when a voicing's strings align (shared periods) the summed output must stay near unity —
// no clipping without a limiter. Checked across all three voicings.
let ceiling: Double = 1.05
for voicingIndex: Int in 0 ..< 3 {
let out: [Float] = try renderPluck(amplitude: 1.0) { pedal in
pedal.mix = 1.0; pedal.sustain = 1.0; pedal.sensitivity = 0.8
pedal.voicing = Double(voicingIndex)
}
var peak: Double = 0.0
for i: Int in 0 ..< (out.count / 2) {
let v: Double = abs(Double(out[2 * i]))
if v > peak { peak = v }
}
#expect(peak <= ceiling, "voicing \(voicingIndex) peaked at \(peak), above the \(ceiling) ceiling")
}
}
// MARK: - Bypass
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] {
let numAudioBuses: Int = 64
let numControlBuses: Int = 512
let driver: OfflineDriver = OfflineDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: pluckHz)
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.sustain = 0.7
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let noInput: [[Float]] = []
var left: [Float] = []
left.reserveCapacity(totalFrames)
var frame: Int = 0
var flipped: Bool = false
while frame < totalFrames {
if !flipped, frame >= flipFrame {
pedal.bypass = 1.0
flipped = true
}
engine.processBlock(inputSamples: noInput)
left.append(contentsOf: engine.audioBuses[0])
frame += blockSize
}
engine.stop()
return left
}
@Test func bypassSwitchIsClickFree() throws {
let blockSize: Int = 512
let totalFrames: Int = 26_460
let flipFrame: Int = 15_435
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
let fadeFrames: Int = Int(0.03 * sampleRate)
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Wiring
@Test func exposesKnobsAndVoicingSelector() throws {
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"])
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
#expect(selectors.map { $0.label } == ["Voicing"])
#expect(selectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"])
}
@Test func presetRoundTripPreservesControls() throws {
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
pedal.tune = 123.4
pedal.sustain = 0.85
pedal.tone = 0.6
pedal.sensitivity = 0.3
pedal.voicing = 2.0
let state: PedalState = pedal.captureState()
let restored: KarplusResonatorPedal = KarplusResonatorPedal()
restored.applyState(state)
#expect(restored.tune == 123.4)
#expect(restored.sustain == 0.85)
#expect(restored.tone == 0.6)
#expect(restored.sensitivity == 0.3)
#expect(restored.voicing == 2.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Karplus Resonator")
#expect(pedal is KarplusResonatorPedal)
}
}