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,396 @@
// TapeLooperPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A simple one-loop tape-style looper with the two classic tape tricks: **half-speed** (an octave
/// down, the loop twice as long) and **reverse**. Where the full ``LooperPedal`` is a synchronized
/// four-track overdub station, this is the single-knob stompbox: record a phrase, play it back, and
/// layer overdubs onto the one loop — then drop it to half speed or flip it backwards for the dubby,
/// Frippertronics-style wash.
///
/// Both speed tricks are **live** playback controls — flipping Reverse or Half-Speed re-reads the
/// same recorded loop at a new rate, with no rebuild. Recording and overdubbing always run at normal
/// forward speed (the write head can't stay aligned with a backward or slowed play-head), so
/// engaging overdub is ignored while Reverse or Half-Speed is on.
///
/// ## Transport (the Record footswitch, by state)
/// - **Empty**: press → record the loop.
/// - **Recording**: press → close the loop at its current length and start playing.
/// - **Playing**: press → toggle overdub onto the loop (forward normal speed only).
/// - **Stopped**: press → resume playback. Clear returns to empty.
///
/// The dry signal always passes through; the loop is added on top (so the wet/dry Mix knob is hidden
/// and the base `mix` stays fully wet).
public final class TapeLooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"A one-loop tape looper — record, overdub, then play it back half-speed or reversed."
}
/// Double-width card so the transport row and loop controls fit without scrolling.
public override var widthUnits: Int { 2 }
/// The looper passes the clean signal through and adds the loop on top, so the wet/dry Mix knob
/// is meaningless — hide it and keep `mix` fully wet.
public override var showsMixControl: Bool { false }
// MARK: - Knobs
/// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
/// layers indefinitely; lower values fade them for a decaying tape-echo loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Playback direction. `0` = forward, `1` = reverse.
@UIParam public var reverse: Double = 0.0
/// Playback speed. `0` = normal, `1` = half speed (an octave down, loop twice as long).
@UIParam public var halfSpeed: Double = 0.0
// MARK: - Internal live state (read by the audio graph)
/// `1` while the loop is playing, else `0`. Gates the player sum and the overdub recorder's run.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger. Pulsed `0 → 1` at play-start so the loop starts from frame 0.
@UIParam public var playTrigger: Double = 0.0
/// LED state for the Record footswitch: `1` while recording or overdubbing.
@UIParam public var recordIndicator: Double = 0.0
/// LED state for the Stop footswitch: `1` while stopped.
@UIParam public var stoppedIndicator: Double = 0.0
// MARK: - Constants
/// Maximum recordable loop length, in seconds. The buffer allocates this long (roughly
/// `maxDurationSeconds × sampleRate × 8 bytes` per instance).
private static let maxDurationSeconds: Double = 30.0
/// Fade time constant, in seconds, for the play/stop mute — smooths the loop in and out so a
/// stop or resume doesn't click.
private let playFadeTime: Double = 0.02
/// Forward playback rate.
private let forwardRate: Double = 1.0
/// Amount subtracted from the rate per unit of `reverse` — `2.0` flips `+1` to `−1`.
private let reverseRateSpan: Double = 2.0
/// Fraction the rate is reduced by at full `halfSpeed` — `0.5` turns `×1` into `×0.5`.
private let halfSpeedDrop: Double = 0.5
/// Smallest loop length in frames, so a zero-length take can't produce a degenerate buffer.
private static let minimumLoopFrames: Int = 1
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffers + generators
private var buffer: LyrebirdBuffer?
private var player: PlayBuffer.Audio?
private var masterRecorder: RecordBuffer.Audio?
private var overdubRecorder: RecordBuffer.Audio?
/// Overdub record gate (`1` = layering new input, `0` = passing existing content through).
private var overdubGate: ParameterNode = ParameterNode(0.0)
// MARK: - Transport state
private enum Phase {
case empty
case recording
case playing
case stopped
}
private var phase: Phase = .empty
private var overdubbing: Bool = false
/// Recorded loop length in frames (`0` until a loop is closed).
private var masterLength: Int = 0
// MARK: - Init
/// Creates a tape-looper pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Tape Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / switches / buttons
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Direction",
node: $reverse,
options: [
PedalSwitch.Option(title: "Fwd", value: 0.0),
PedalSwitch.Option(title: "Rev", value: 1.0),
]
),
PedalSwitch(
label: "Speed",
node: $halfSpeed,
options: [
PedalSwitch.Option(title: "Normal", value: 0.0),
PedalSwitch.Option(title: "Half", value: 1.0),
]
),
]
}
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(label: "Record", indicator: $recordIndicator,
dynamicLabel: { [weak self] in self?.recordButtonCaption ?? "Record" }) { [weak self] in self?.pressRecord() },
PedalButton(label: "Stop", indicator: $stoppedIndicator) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Clear") { [weak self] in self?.clearLoop() },
]
}
// MARK: - UI read-outs
/// Caption for the Record footswitch describing what the *next* press does.
public var recordButtonCaption: String {
switch phase {
case .empty: return "Record"
case .recording: return "Play"
case .stopped: return "Play"
case .playing: return overdubbing ? "Overdub Off" : "Overdub"
}
}
/// `true` once a loop has been recorded.
public var hasLoop: Bool { masterLength > 0 }
/// Recorded loop length in frames (`0` until a loop is closed).
public var loopFrameCount: Int { masterLength }
/// Recorded loop length in seconds.
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
/// `true` while the loop is being overdubbed.
public var isOverdubbing: Bool { overdubbing }
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `effect()` runs from `build()`, which the engine re-invokes on every add (including the
// re-adds a board edit performs on this same instance). Start clean so nothing references a
// discarded buffer and the transport returns to empty.
resetForRebuild()
let maxFrames: Int = Int(TapeLooperPedal.maxDurationSeconds * sampleRate)
let loopBuffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffer = loopBuffer
// Playback rate: direction × speed, both live. reverse 0→+1 / 1→−1; halfSpeed 0→×1 / 1→×0.5.
let directionRate: any ValidGeneratorInput = forwardRate - reverseRateSpan * $reverse
let speedScale: any ValidGeneratorInput = forwardRate - halfSpeedDrop * $halfSpeed
let playbackRate: any ValidGeneratorInput = directionRate * speedScale
// Non-looping master recorder for the length-defining first take.
let master: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: loopBuffer,
loop: false,
doneAction: .nothing
)
master.run = 0.0
masterRecorder = master
// Always-running overdub recorder (gated by play): layers new input only while the overdub
// gate is open, otherwise it passes existing content through (`preLevel = 1`). While
// overdubbing, prior content is retained at `feedback`.
let unity: Double = 1.0
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: loopBuffer,
loop: true,
doneAction: .nothing
)
// The effective record-enable also closes if Reverse or Half-Speed is engaged *after* an
// overdub is toggled on — the write head runs forward 1× and can't stay aligned with a
// backward or slowed play-head. `(1 − reverse)·(1 − halfSpeed)` is `1` only at forward normal
// speed; when it drops to `0`, `recLevel` is `0` and `preLevel` is `1` (existing content
// preserved), so the layers never misalign.
overdub.$run.source = $isPlaying
let forwardNormal: BinaryOpGenerator = (unity - $reverse) * (unity - $halfSpeed)
let effectiveGate: BinaryOpGenerator = overdubGate * forwardNormal
overdub.$recLevel.source = effectiveGate
overdub.$preLevel.source = (unity - effectiveGate) + effectiveGate * $feedback
overdubRecorder = overdub
let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: loopBuffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
player = loopPlayer
// Loop audible only while playing; smoothed to avoid clicks on stop/resume.
let smoothedGate: Lag.Control = Lag.Control(input: $isPlaying, time: playFadeTime)
// Dry always passes through; the loop is added on top, gated by play.
return dry + (loopPlayer * smoothedGate)
}
// MARK: - Transport
/// The smart Record press. Behaviour depends on the current phase.
public func pressRecord() {
switch phase {
case .empty: beginRecording()
case .recording: closeAndPlay()
case .playing: toggleOverdub()
case .stopped: resumePlayback()
}
}
private func beginRecording() {
guard let master: RecordBuffer.Audio = masterRecorder else { return }
master.requestReset()
master.run = 1.0
recordIndicator = 1.0
stoppedIndicator = 0.0
phase = .recording
}
private func closeAndPlay() {
guard phase == .recording, let master: RecordBuffer.Audio = masterRecorder,
let loopBuffer: LyrebirdBuffer = buffer else { return }
master.run = 0.0
// Nothing actually recorded (e.g. a double-press with no time between) — don't close a
// degenerate one-frame loop that would play as a DC buzz; drop back to empty.
let recorded: Int = master.recordedFrameCount
guard recorded > 0 else {
clearLoop()
return
}
masterLength = max(TapeLooperPedal.minimumLoopFrames, recorded)
loopBuffer.setLoopLength(masterLength)
recordIndicator = 0.0
startPlayback()
}
/// Toggles overdub onto the loop. Overdub records forward at normal speed, so it is blocked while
/// Reverse or Half-Speed is engaged (the write head can't follow a backward or slowed play-head).
private func toggleOverdub() {
guard phase == .playing else { return }
if overdubbing {
overdubbing = false
} else {
guard reverse < 0.5, halfSpeed < 0.5 else { return }
overdubbing = true
}
updateOverdubGate()
}
private func startPlayback() {
overdubRecorder?.requestReset() // realign the write head to the top
isPlaying = 1.0
stoppedIndicator = 0.0
overdubbing = false
phase = .playing // set before updateOverdubGate so the LED reads "playing"
updateOverdubGate()
playTrigger = 1.0 // rising edge resets the play-head to frame 0
}
/// Resumes playback from the stopped state.
private func resumePlayback() {
guard phase == .stopped, masterLength > 0 else { return }
startPlayback()
}
/// Halts playback; recorded content is retained (resume via Record).
public func stopPlayback() {
guard phase == .playing else { return }
overdubbing = false
updateOverdubGate()
isPlaying = 0.0
playTrigger = 0.0 // rearm the play-head reset edge
recordIndicator = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// Clears the recorded loop and returns to the empty state.
public func clearLoop() {
masterRecorder?.run = 0.0
masterRecorder?.requestReset()
overdubRecorder?.requestReset()
isPlaying = 0.0
if let loopBuffer: LyrebirdBuffer = buffer {
loopBuffer.clear()
loopBuffer.setLoopLength(loopBuffer.count)
}
masterLength = 0
overdubbing = false
playTrigger = 0.0
recordIndicator = 0.0
stoppedIndicator = 0.0
updateOverdubGate()
phase = .empty
}
/// Resets to the empty state when the engine stops — a stopped engine can't keep a loop running.
public override func engineDidStop() {
clearLoop()
}
/// Resets before this instance is discarded on a rig teardown.
public override func rigWillTeardown() {
clearLoop()
}
// MARK: - Helpers
private func updateOverdubGate() {
overdubGate.value = overdubbing ? 1.0 : 0.0
recordIndicator = (phase == .recording || overdubbing) ? 1.0 : 0.0
}
/// Clears the generator references and returns the transport to empty, so a graph rebuild
/// (`build()` re-run) starts fresh. Called at the top of ``effect(_:)``.
private func resetForRebuild() {
buffer = nil
player = nil
masterRecorder = nil
overdubRecorder = nil
overdubGate = ParameterNode(0.0)
phase = .empty
overdubbing = false
masterLength = 0
isPlaying = 0.0
playTrigger = 0.0
recordIndicator = 0.0
stoppedIndicator = 0.0
}
}