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
+3
View File
@@ -101,6 +101,7 @@ public extension PedalType {
static let bitcrusher = PedalType("Bitcrusher")
static let granulator = PedalType("Granulator")
static let autoGranulator = PedalType("Auto Granulator")
static let karplusResonator = PedalType("Karplus Resonator")
// Dynamics (additional)
static let sustainer = PedalType("Sustainer")
@@ -114,6 +115,7 @@ public extension PedalType {
static let multiTapDelay = PedalType("Multi-Tap Delay")
static let pingPong = PedalType("Ping-Pong")
static let reverseDelay = PedalType("Reverse Delay")
static let dl4 = PedalType("DL4")
static let reverb = PedalType("Reverb")
static let shimmerReverb = PedalType("Shimmer Reverb")
static let plateReverb = PedalType("Plate Reverb")
@@ -131,4 +133,5 @@ public extension PedalType {
// Looper
static let looper = PedalType("Looper")
static let tapeLooper = PedalType("Tape Looper")
}
@@ -0,0 +1,296 @@
// DL4Pedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// An umbrella multi-model delay in the mould of the classic green four-knob delay modeller: one
/// pedal, a **Model** selector, and four shared controls (**Time**, **Repeats**, **Tone**, **Mod**)
/// whose character changes with the chosen model. This is the delay-models side only — no looper.
///
/// Each model is a distinct delay recipe built from Lyrebird primitives:
/// - **Tube** — a driven, warm echo (soft-clipped input into a filtered delay).
/// - **Tape** — a tape echo with slow wow modulating the delay time and a tape-style HF rolloff.
/// - **Analog** — a dark bucket-brigade voice (heavily low-passed, gently saturated repeats).
/// - **Analog Mod** — the analog voice with a chorus-rate wobble on the delay time.
/// - **Multi-Head** — three fixed delay taps plus a feedback repeat, à la a multi-head tape unit.
/// - **Sweep** — a delay fed through a sweeping all-pass for a phased, resonant echo.
/// - **Lo-Res** — a down-sampled, gritty lo-fi delay.
/// - **Reverse** — backward echo segments (the ``ReverseDelay`` generator).
///
/// `effect` returns the pure wet signal; the base `Pedal` `mix` sets the wet/dry blend.
///
/// ## Knobs
/// - `time`: Delay time in seconds. Range `[0.02, 2.0]`. Tempo-syncable.
/// - `repeats`: Feedback, as the decay time in seconds for echoes to fall to −60 dB. Range `[0.05, 8.0]`.
/// - `tone`: Repeat brightness — a low-pass cutoff in Hz. Range `[500, 12000]`.
/// - `mod`: Modulation amount in `[0, 1]` for the models that modulate — delay-time wow depth for
/// Tape and Analog Mod, and the sweep rate for Sweep; inert for the others.
///
/// ## Selectors
/// - `model`: The delay model (rebuilds on change).
public final class DL4Pedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-model delay: tube, tape, analog, multi-head, sweep, lo-res, and reverse voices."
}
// MARK: - Parameters
/// Delay time in seconds. Range `[0.02, 2.0]`.
@UIParam public var time: Double = 0.4
/// Feedback as decay time in seconds (−60 dB). Range `[0.05, 8.0]`.
@UIParam public var repeats: Double = 1.5
/// Repeat brightness — low-pass cutoff in Hz. Range `[500, 12000]`.
@UIParam public var tone: Double = 6000.0
/// Modulation amount in `[0, 1]` — Tape wow depth, Analog Mod wobble depth, or Sweep rate.
@UIParam public var mod: Double = 0.3
/// Selected model index into ``models``. A knob-picker selector; rebuilds on change.
@UIParam public var model: Double = 0.0
// MARK: - Models
/// The ordered model list. The index is written to ``model`` by the selector and read at build
/// time by ``effect(_:)`` to pick the recipe.
private static let models: [String] = [
"Tube", "Tape", "Analog", "Analog Mod", "Multi-Head", "Sweep", "Lo-Res", "Reverse",
]
// MARK: - Constants
/// Default wet/dry blend — a partial mix so dry and echoes coexist.
private static let defaultMix: Double = 0.35
/// Maximum delay time in seconds. Sizes every delay line; kept above `timeRange.upperBound` so
/// the modulated models can push the delay time a little past the knob maximum without wrapping.
private let maxDelayTime: Double = 2.2
/// Amplitude target for the feedback `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
/// Butterworth Q (no resonant peak) for the tone low-pass.
private let filterQ: Double = 0.707
// Tube
private let tubeDrive: Double = 2.0
// Tape
private let tapeWowRate: Double = 0.7 // Hz
private let tapeWowDepth: Double = 0.003 // seconds at mod = 1
private let tapeToneScale: Double = 0.8 // tape HF rolloff
// Analog
private let analogToneScale: Double = 0.5 // dark BBD voice
private let analogDrive: Double = 1.3
// Analog Mod
private let analogModRate: Double = 1.6 // Hz
private let analogModDepth: Double = 0.0025 // seconds at mod = 1
// Multi-Head
private let headBFraction: Double = 0.5 // second tap at half the time
private let headCFraction: Double = 0.75 // third tap at three-quarters
private let headGain: Double = 0.2 // per-tap level (3 taps → 0.6)
private let repeatGain: Double = 0.4 // feedback-repeat level (sum 3·0.2 + 0.4 = 1.0)
// Sweep
private let sweepRateMin: Double = 0.05 // Hz at mod = 0
private let sweepRateSpan: Double = 1.45 // + span at mod = 1 → up to 1.5 Hz
private let sweepDepth: Double = 0.8
private let sweepCenterFreq: Double = 900.0
private let sweepFeedback: Double = 0.3
private let sweepStages: Int = 4
private let sweepInternalMix: Double = 1.0
// Lo-Res
private let loResDownsample: Double = 4.0 // hold length in samples
private let loResToneScale: Double = 0.6
// Reverse
private let reverseFeedbackScale: Double = 0.95 / 8.0 // maps repeats (≤ 8 s) → [0, 0.95]
private let reverseFeedbackMax: Double = 0.95
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.02 ... 2.0
private let repeatsRange: ClosedRange<Double> = 0.05 ... 8.0
private let toneRange: ClosedRange<Double> = 500.0 ... 12000.0
private let modRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Repeats", node: $repeats, range: repeatsRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
PedalKnob(label: "Mod", node: $mod, range: modRange),
]
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
// MARK: - Selectors
public override var effectSelectors: [PedalSelectorKnob] {
let stops: [PedalSelectorKnob.Stop] = DL4Pedal.models.enumerated().map { index, name in
PedalSelectorKnob.Stop(title: name, value: Double(index))
}
return [
// Each model is a different delay topology read at build time, so switching rebuilds.
PedalSelectorKnob(label: "Model", node: $model, stops: stops, rebuildsOnChange: true),
]
}
// MARK: - Init
/// Creates a multi-model delay 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: "DL4",
inputBus: inputBus,
outputBus: outputBus,
initialMix: DL4Pedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `model` is read as a plain value at build time; the board rebuilds when it changes (each
// model is a different delay topology). Time / Repeats / Tone / Mod stay live.
let index: Int = min(max(0, Int(model.rounded())), DL4Pedal.models.count - 1)
switch index {
case 0: return makeTube(dry: dry)
case 1: return makeTape(dry: dry)
case 2: return makeAnalog(dry: dry)
case 3: return makeAnalogMod(dry: dry)
case 4: return makeMultiHead(dry: dry)
case 5: return makeSweep(dry: dry)
case 6: return makeLoRes(dry: dry)
default: return makeReverse(dry: dry)
}
}
// MARK: - Model builders
/// A feedback delay line on `input` at the current Time / Repeats.
private func feedbackDelay(input: any ValidGeneratorInput, delay: any ValidGeneratorInput) -> DelayLineFeedback {
DelayLineFeedback(
input: input,
maxDelay: maxDelayTime,
delay: delay,
decayTime: $repeats,
targetAmp: targetAmp,
sampleRate: sampleRate,
interpolation: .linear
)
}
/// Tone low-pass at the given cutoff.
private func toned(_ input: any ValidGeneratorInput, cutoff: any ValidGeneratorInput) -> RBJLowPass.Audio {
RBJLowPass.Audio(input: input, freq: cutoff, q: filterQ)
}
/// Tube: soft-clipped input into a filtered feedback delay — a driven, warm echo.
private func makeTube(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let driven: SoftClip.Audio = SoftClip.Audio(dry, drive: tubeDrive)
let fb: DelayLineFeedback = feedbackDelay(input: driven, delay: $time)
return toned(fb, cutoff: $tone)
}
/// Tape: slow wow modulates the delay time, with a tape-style HF rolloff.
private func makeTape(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let wow: OscSin.Audio = OscSin.Audio(freq: tapeWowRate, mul: $mod * tapeWowDepth)
let delay: any ValidGeneratorInput = $time + wow
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: delay)
return toned(fb, cutoff: $tone * tapeToneScale)
}
/// Analog: dark, gently saturated bucket-brigade voice.
private func makeAnalog(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
let dark: RBJLowPass.Audio = toned(fb, cutoff: $tone * analogToneScale)
return SoftClip.Audio(dark, drive: analogDrive)
}
/// Analog Mod: the analog voice with a chorus-rate wobble on the delay time.
private func makeAnalogMod(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let wobble: OscSin.Audio = OscSin.Audio(freq: analogModRate, mul: $mod * analogModDepth)
let delay: any ValidGeneratorInput = $time + wobble
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: delay)
return toned(fb, cutoff: $tone * analogToneScale)
}
/// Multi-Head: three fixed delay taps plus a feedback repeat, like a multi-head tape unit.
private func makeMultiHead(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let tapA: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time, sampleRate: sampleRate)
let tapB: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time * headBFraction, sampleRate: sampleRate)
let tapC: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time * headCFraction, sampleRate: sampleRate)
let repeatsTap: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
let sum: any ValidGeneratorInput =
(tapA * headGain) + (tapB * headGain) + (tapC * headGain) + (repeatsTap * repeatGain)
return toned(sum, cutoff: $tone)
}
/// Sweep: a filtered delay fed through a sweeping all-pass for a phased, resonant echo.
private func makeSweep(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
let base: RBJLowPass.Audio = toned(fb, cutoff: $tone)
let sweepRate: any ValidGeneratorInput = ($mod * sweepRateSpan) + sweepRateMin
return Phaser.Audio(
input: base,
rate: sweepRate,
depth: sweepDepth,
centerFreq: sweepCenterFreq,
feedback: sweepFeedback,
stages: sweepStages,
mix: sweepInternalMix,
sampleRate: sampleRate
)
}
/// Lo-Res: a down-sampled, gritty lo-fi delay.
private func makeLoRes(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
let crushed: SampleRateDecimate = SampleRateDecimate(input: fb, downsample: loResDownsample)
return toned(crushed, cutoff: $tone * loResToneScale)
}
/// Reverse: backward echo segments at the current Time, with Repeats mapped to the reverse-trail
/// feedback factor.
private func makeReverse(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let revFeedback: Clip.Audio = Clip.Audio(
$repeats * reverseFeedbackScale,
lo: 0.0,
hi: reverseFeedbackMax
)
let rev: ReverseDelay = ReverseDelay(
input: dry,
maxDelay: maxDelayTime,
delay: $time,
feedback: revFeedback,
sampleRate: sampleRate
)
return toned(rev, cutoff: $tone)
}
}
@@ -0,0 +1,233 @@
// KarplusResonatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sympathetic-string resonator — a bank of tuned Karplus-Strong strings the guitar excites.
///
/// A sitar's or a sarangi's sympathetic strings are always coupled to the played note: pluck, and
/// a fixed set of tuned strings sing along, ringing on after each note. This pedal models that with
/// four `KarplusStrong` strings tuned to a chord above a **Tune** root. An amplitude envelope of
/// your playing drives a Schmitt gate whose rising edge plucks the whole bank — capturing the loud
/// note onset — and the strings then ring on at their own tuned pitches with their own decay: the
/// sympathetic shimmer blooming out of the note's tail.
///
/// Distinct from a reverb or a delay: the tails are **pitched** to the Tune root's chord, not a
/// diffuse wash or a repeat of what you played. Distinct from the ``PolyOctavePedal`` (which pitch-
/// shifts your note in real time): here the resonators have their own fixed tuning and their own
/// decay, so holding a drone root under a moving line is the whole point.
///
/// Wraps Lyrebird's `KarplusStrong` run fully wet; the base `Pedal` `mix` sets the blend of the
/// ringing bank against the dry note (an even mix by default).
///
/// ## Knobs
/// - `tune`: Root frequency of the string bank in Hz. Range `[40, 400]`.
/// - `sustain`: Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`.
/// - `tone`: Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic.
/// - `sensitivity`: How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger
/// threshold, so quieter notes still excite the bank.
///
/// ## Selectors
/// - `voicing`: Chord the four strings are tuned to (rebuilds on change): Drone, Octaves, Shimmer.
public final class KarplusResonatorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"A bank of tuned strings that ring along with your note — sympathetic sitar shimmer."
}
// MARK: - Parameters
/// Root frequency of the string bank in Hz. Range `[40, 400]`.
@UIParam public var tune: Double = 82.41
/// Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`.
@UIParam public var sustain: Double = 0.7
/// Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic.
@UIParam public var tone: Double = 0.4
/// How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger threshold.
@UIParam public var sensitivity: Double = 0.5
/// Selected voicing index into ``voicings``. A knob-picker selector; rebuilds on change.
@UIParam public var voicing: Double = 0.0
// MARK: - Voicings
/// A named chord the four strings are tuned to, as frequency ratios of the Tune root.
private struct Voicing {
let title: String
let ratios: [Double]
}
/// Fixed string tunings. Each has exactly ``stringCount`` ratios of the Tune root.
/// - Drone: root, fifth, octave, octave+fifth — the classic sympathetic drone.
/// - Octaves: two octaves down through two up — a wide octave stack.
/// - Shimmer: two octave pairs detuned a few cents apart — slow beating for a chorused ring.
private static let voicings: [Voicing] = [
Voicing(title: "Drone", ratios: [1.0, 1.5, 2.0, 3.0]),
Voicing(title: "Octaves", ratios: [0.5, 1.0, 2.0, 4.0]),
Voicing(title: "Shimmer", ratios: [1.0, 1.005, 2.0, 1.99]),
]
/// Number of strings in the bank — fixed, so the delay-line allocation is structural.
private static let stringCount: Int = 4
// MARK: - Constants
/// Pedal returns the bank fully wet; the base `mix` blends it against the dry note. An even mix
/// so the sympathetic ring sits under the dry signal rather than replacing it.
private static let defaultMix: Double = 0.5
/// Maximum delay time for each string, in seconds — sizes the Karplus delay line. Covers the
/// lowest resonator (`tune.min × voicing.min = 40 × 0.5 = 20 Hz`, a 0.05 s period) with margin.
private let maxStringDelayTime: Double = 0.06
/// Feedback (ring length) mapped from `sustain = 0`: a short, plucky decay.
private let feedbackMin: Double = 0.9
/// Feedback mapped from `sustain = 1`: a very long, near-infinite ring. Kept just under `1.0`
/// so the bank always decays rather than running away.
private let feedbackMax: Double = 0.999
/// One-pole coefficient mapped from `tone = 0`: classic Karplus averaging — dark and woody.
private let coefDark: Double = 0.5
/// One-pole coefficient mapped from `tone = 1`: negative, for a bright, metallic sitar-like
/// timbre. Kept well inside `|coef| < 1` so the feedback path never grows.
private let coefBright: Double = -0.2
/// Schmitt switch-on threshold on the input envelope at `sensitivity = 0` — the least sensitive
/// setting, where only loud notes feed the strings.
private let gateHiThresholdLow: Double = 0.25
/// Schmitt switch-on threshold at `sensitivity = 1` — the most sensitive setting, where even
/// quiet notes feed the strings.
private let gateHiThresholdHigh: Double = 0.01
/// Fraction of the switch-on threshold used for the switch-off threshold, giving the gate
/// hysteresis so it doesn't chatter around a single level.
private let gateLoFactor: Double = 0.5
/// Envelope-follower attack for the gate detector, in seconds — fast, to catch note onsets.
private let envAttackTime: Double = 0.005
/// Envelope-follower release for the gate detector, in seconds — slow enough that the gate holds
/// through a note and only drops once it has genuinely decayed, at which point the bank rings.
private let envReleaseTime: Double = 0.08
/// Output scale on the summed four-string bank — `1/stringCount`, the fully-coherent-sum bound.
/// The Octaves and Shimmer voicings share string periods, so a full-scale pluck can momentarily
/// align all four; this ceiling keeps the summed bank at or below the dry peak with no limiter.
private let bankGain: Double = 0.25
// MARK: - Ranges
private let tuneRange: ClosedRange<Double> = 40.0 ... 400.0
private let unitRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Tune", node: $tune, range: tuneRange),
PedalKnob(label: "Sustain", node: $sustain, range: unitRange),
PedalKnob(label: "Tone", node: $tone, range: unitRange),
PedalKnob(label: "Sensitivity", node: $sensitivity, range: unitRange),
]
}
// MARK: - Selectors
public override var effectSelectors: [PedalSelectorKnob] {
let stops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.voicings.enumerated().map { index, voicing in
PedalSelectorKnob.Stop(title: voicing.title, value: Double(index))
}
return [
// Each voicing tunes the strings to a different chord — a build-time structural choice
// (the ratios set each string's delay length), so switching it must rebuild the board.
PedalSelectorKnob(label: "Voicing", node: $voicing, stops: stops, rebuildsOnChange: true),
]
}
// MARK: - Init
/// Creates a Karplus-Strong sympathetic-resonator 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: "Karplus Resonator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: KarplusResonatorPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `voicing` is read as a plain value at build time; the board rebuilds when it changes (the
// ratios size each string's delay line). All other controls stay live.
let index: Int = min(max(0, Int(voicing.rounded())), KarplusResonatorPedal.voicings.count - 1)
let ratios: [Double] = KarplusResonatorPedal.voicings[index].ratios
// Pluck trigger: track the input envelope, then a Schmitt trigger turns it into a 0/1 play
// detector. Its rising edge (you start a note) plucks the whole bank — Karplus fills each
// delay line from the loud onset — and the strings then ring on at their tuned pitches. The
// hysteresis means the gate must fall back below the off-threshold before the next note can
// re-pluck, so a single sustained note plucks once rather than chattering.
let env: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: envAttackTime,
releaseTime: envReleaseTime
)
// sensitivity [0, 1] → switch-on threshold [gateHiThresholdLow, gateHiThresholdHigh]
// (higher sensitivity = lower threshold); switch-off threshold is a fixed fraction below it.
let hiSpan: Double = gateHiThresholdHigh - gateHiThresholdLow
let hiThreshold: any ValidGeneratorInput = ($sensitivity * hiSpan) + gateHiThresholdLow
let loThreshold: any ValidGeneratorInput = hiThreshold * gateLoFactor
let trigger: Schmidt.Audio = Schmidt.Audio(input: env, lo: loThreshold, hi: hiThreshold)
// sustain [0, 1] → feedback [feedbackMin, feedbackMax]; tone [0, 1] → coef [coefDark, coefBright].
let feedbackSpan: Double = feedbackMax - feedbackMin
let voicedFeedback: any ValidGeneratorInput = ($sustain * feedbackSpan) + feedbackMin
let coefSpan: Double = coefBright - coefDark
let voicedCoef: any ValidGeneratorInput = ($tone * coefSpan) + coefDark
// Four tuned strings, each a KarplusStrong plucked by the shared trigger from the dry onset.
var bank: any ValidGeneratorInput = KarplusStrong.Audio(
exciter: dry,
trigger: trigger,
freq: $tune * ratios[0],
feedback: voicedFeedback,
coef: voicedCoef,
sampleRate: sampleRate,
maxDelayTime: maxStringDelayTime
)
for stringIndex: Int in 1 ..< KarplusResonatorPedal.stringCount {
let string: KarplusStrong.Audio = KarplusStrong.Audio(
exciter: dry,
trigger: trigger,
freq: $tune * ratios[stringIndex],
feedback: voicedFeedback,
coef: voicedCoef,
sampleRate: sampleRate,
maxDelayTime: maxStringDelayTime
)
bank = bank + string
}
return bank * bankGain
}
}
@@ -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
}
}
@@ -84,6 +84,7 @@ public enum PedalRegistry {
"Poly Octave": { PolyOctavePedal() },
"Ping-Pong": { PingPongDelayPedal() },
"Reverse Delay": { ReverseDelayPedal() },
"DL4": { DL4Pedal() },
"Shimmer Reverb": { ShimmerReverbPedal() },
"Plate Reverb": { PlateReverbPedal() },
"Room Reverb": { RoomReverbPedal() },
@@ -105,7 +106,9 @@ public enum PedalRegistry {
"Bitcrusher": { BitcrusherPedal() },
"Granulator": { GranulatorPedal() },
"Auto Granulator": { AutoGranulatorPedal() },
"Karplus Resonator": { KarplusResonatorPedal() },
"Looper": { LooperPedal() },
"Tape Looper": { TapeLooperPedal() },
]
/// Maps a pedal `displayName` that has since been renamed to its current registry key, so rigs
@@ -57,10 +57,11 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, "Whammy": .pitch,
"Poly Octave": .pitch,
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
"Reverse Delay": .delay,
"Reverse Delay": .delay, "DL4": .delay,
"Reverb": .reverb, "Shimmer Reverb": .reverb,
"Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb,
"Reverse Reverb": .reverb, "Granular Reverb": .reverb,
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
"Karplus Resonator": .texture, "Tape Looper": .texture,
]
}