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>
This commit is contained in:
2026-11-24 14:47:51 -08:00
parent 75de04160b
commit d1f823e54c
10 changed files with 2070 additions and 3 deletions
@@ -0,0 +1,435 @@
// TapeLooperPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("TapeLooperPedal")
struct TapeLooperPedalTests {
private let sampleRate: Double = 44_100.0
private let toneHz: Double = 220.0
// MARK: - Fixtures
/// A constant-frequency sine with a live-settable amplitude, so a test can silence the live input
/// at an exact time and attribute any remaining output to the loop.
private final class ToneSource: SynthesizerBase {
let ampNode: ParameterNode = ParameterNode(0.4)
var amplitude: Double {
get { ampNode.value }
set { ampNode.value = newValue }
}
private let targetBus: Int
private let toneFreq: Double
init(targetBus: Int, freq: Double) {
self.targetBus = targetBus
self.toneFreq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
}
}
/// Posts a `TriggerEvent` at an exact time within a single NRT render, so a test can flip a
/// transport action mid-render.
private final class TimedTrigger: SynthesizerBase {
private let fireTime: Double
private let triggerID: Int32
private static let minRampDuration: Double = 0.001
init(fireTime: Double, id: Int32) {
self.fireTime = fireTime
self.triggerID = id
super.init()
}
override func build() {
let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0
let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration)
_ = SendTrigger.Control(trig: ramp, id: triggerID)
}
}
// MARK: - Render
private func render(
totalDuration: Double,
toneFreq: Double = 220.0,
configure: (
_ engine: SynthesisEngine,
_ source: ToneSource,
_ pedal: TapeLooperPedal,
_ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void
) throws -> Void
) throws -> [Float] {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
defer { try? FileManager.default.removeItem(at: url) }
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let listener: TriggerListener = TriggerListener(engine: engine)
driver.triggerListener = listener
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: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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))
var nextTriggerID: Int32 = 0
let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in
nextTriggerID += 1
let id: Int32 = nextTriggerID
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
try engine.add(trigger)
listener.addHandler(id: id) { _, _ in
MainActor.assumeIsolated { action() }
}
}
try configure(engine, source, pedal, scheduleAction)
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
// MARK: - Analysis
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()
}
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)
}
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
}
// Record a loop from 0 → recordDur, then close + play; the caller may tweak the pedal at play.
private let recordDur: Double = 0.15
private let totalDur: Double = 0.7
/// Tail window (loop-only, after the live input is silenced), in interleaved frames.
private var tailSkip: Int { Int(0.45 * sampleRate) }
private var tailWindow: Int { 8_192 }
/// Builds an offline engine driving a steady tone into the looper, records a real loop (so
/// `masterLength > 0`), closes it, and leaves the pedal in the playing state. Returns the engine
/// (kept alive by the caller) and the pedal for state-machine assertions.
private func makePlayingLooper(recordBlocks: Int = 8) throws -> (SynthesisEngine, TapeLooperPedal) {
let blockSize: Int = 512
let driver: OfflineDriver = OfflineDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz)
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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]] = []
pedal.pressRecord() // begin recording
for _: Int in 0 ..< recordBlocks { engine.processBlock(inputSamples: noInput) }
pedal.pressRecord() // close + play (frames recorded)
engine.processBlock(inputSamples: noInput)
return (engine, pedal)
}
// MARK: - Controls
@Test func exposesTapeLooperControls() throws {
let pedal: TapeLooperPedal = TapeLooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Playback", "Feedback"])
#expect(pedal.effectSwitches.map { $0.label } == ["Direction", "Speed"])
#expect(pedal.effectTransportButtons.map { $0.label } == ["Record", "Stop", "Clear"])
}
@Test func isDoubleWidthAndHidesMix() throws {
#expect(TapeLooperPedal().widthUnits == 2)
#expect(TapeLooperPedal().showsMixControl == false)
}
@Test func rebuildWipesTheRecordedLoop() throws {
// effect() runs from build(), re-invoked on every add (a board edit re-adds this instance).
// A rebuild must start clean — a previously recorded loop must not survive it.
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
#expect(pedal.hasLoop, "fixture should have recorded a loop")
_ = pedal.effect(OscSin.Audio(freq: 100.0)) // simulate a second build()
#expect(pedal.hasLoop == false, "a rebuild must wipe the recorded loop")
#expect(pedal.loopFrameCount == 0)
}
// MARK: - Audio behaviour
@Test func clearStatePassesDryThrough() throws {
let out: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(out), "an empty looper should pass the dry signal through")
}
@Test func recordedLoopPlaysBackAfterInputSilenced() throws {
// Record a tone, close + play, then silence the live input. The loop must keep sounding.
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
pedal.pressRecord() // begin recording at t = 0
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
}
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
#expect(tail > 1.0e-3, "recorded loop should keep playing after the input is silenced, tail RMS \(tail)")
}
@Test func clearSilencesTheLoop() throws {
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
pedal.pressRecord()
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
try scheduleAction(0.35) { pedal.clearLoop() } // wipe the loop
}
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
#expect(tail < 1.0e-3, "after Clear with the input silenced the output should be silent, tail RMS \(tail)")
}
@Test func halfSpeedLowersLoopPitch() throws {
// Record a 220 Hz loop, then play it at half speed: the loop-only tail should drop an octave.
let normal: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
pedal.pressRecord()
try scheduleAction(recordDur) { pedal.pressRecord() }
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
}
let half: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
pedal.pressRecord()
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.halfSpeed = 1.0 }
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
}
let fNormal: Double = fundamentalHz(normal, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
let fHalf: Double = fundamentalHz(half, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
#expect(abs(fNormal - toneHz) / toneHz < 0.1, "normal loop should sound at the recorded pitch, got \(fNormal) Hz")
#expect(abs(fHalf - toneHz * 0.5) / (toneHz * 0.5) < 0.12,
"half-speed loop should sound an octave down (~\(toneHz * 0.5) Hz), got \(fHalf) Hz")
}
@Test func reversePlaybackStillRunsTheLoop() throws {
// A reversed loop still plays (non-silent after the input is silenced).
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
pedal.pressRecord()
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.reverse = 1.0 }
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
}
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
#expect(tail > 1.0e-3, "reversed loop should keep playing, tail RMS \(tail)")
}
@Test func overdubBlockedWhileReversedOrHalfSpeed() throws {
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
#expect(pedal.hasLoop)
#expect(pedal.isOverdubbing == false)
// Forward normal speed: overdub engages.
pedal.pressRecord()
#expect(pedal.isOverdubbing == true)
pedal.pressRecord() // toggle it back off
#expect(pedal.isOverdubbing == false)
// Reversed: overdub is blocked at engage time.
pedal.reverse = 1.0
pedal.pressRecord()
#expect(pedal.isOverdubbing == false, "overdub must be blocked while reversed")
// Half speed: overdub is blocked at engage time.
pedal.reverse = 0.0
pedal.halfSpeed = 1.0
pedal.pressRecord()
#expect(pedal.isOverdubbing == false, "overdub must be blocked at half speed")
}
@Test func recordLedTracksTransportState() throws {
// Regression: closing a loop must not leave the Record LED stuck lit for the whole playback.
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
#expect(pedal.recordIndicator == 0.0, "Record LED should be off while just playing")
#expect(pedal.stoppedIndicator == 0.0)
pedal.pressRecord() // engage overdub
#expect(pedal.recordIndicator == 1.0, "Record LED should light while overdubbing")
pedal.pressRecord() // disengage
#expect(pedal.recordIndicator == 0.0, "Record LED should clear when overdub ends")
pedal.stopPlayback()
#expect(pedal.stoppedIndicator == 1.0, "Stop LED should light when stopped")
#expect(pedal.recordIndicator == 0.0)
}
// MARK: - Bypass
private final class TestSineSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
init(targetBus: Int, freq: Double) {
self.targetBus = targetBus
self.freq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
}
}
@Test func bypassSwitchIsClickFree() throws {
let blockSize: Int = 512
let totalFrames: Int = 26_460
let flipFrame: Int = 15_435
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: toneHz)
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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()
#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 presetRoundTripPreservesControls() throws {
let pedal: TapeLooperPedal = TapeLooperPedal()
pedal.playbackLevel = -6.0
pedal.feedback = 0.75
pedal.reverse = 1.0
pedal.halfSpeed = 1.0
let state: PedalState = pedal.captureState()
let restored: TapeLooperPedal = TapeLooperPedal()
restored.applyState(state)
#expect(restored.playbackLevel == -6.0)
#expect(restored.feedback == 0.75)
#expect(restored.reverse == 1.0)
#expect(restored.halfSpeed == 1.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Tape Looper")
#expect(pedal is TapeLooperPedal)
}
}