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
+2 -2
View File
@@ -48,9 +48,9 @@ signal (no hardware needed) or on live guitar through an audio input.
| EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant |
| Modulation | Tremolo, Phaser, Script Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay, DL4 |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Looper |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Karplus Resonator, Looper, Tape Looper |
| Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim |
| Cabinet | Cabinet (speaker-voice + microphone modeling) |
+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,
]
}
@@ -0,0 +1,314 @@
// DL4PedalTests.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 so a test can hear the delay repeats in the silence after the note.
@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() {
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 for the bypass click test.
@MainActor
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))
}
}
@MainActor
@Suite("DL4Pedal")
struct DL4PedalTests {
private let sampleRate: Double = 44_100.0
private let pluckHz: Double = 180.0
private let burstDur: Double = 0.08
private let renderDiffEpsilon: Double = 1.0e-3
private let modelCount: Int = 8
// MARK: - Render
private func render(
duration: Double = 1.2,
pluck: Bool = true,
amplitude: Double = 0.7,
configure: (DL4Pedal) -> 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: DL4Pedal = DL4Pedal(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
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 rmsDiff(_ a: [Float], _ b: [Float]) -> Double {
let n: Int = min(a.count, b.count) / 2
guard n > 0 else { return 0.0 }
var sum: Double = 0.0
for i: Int in 0 ..< n {
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
sum += d * d
}
return (sum / Double(n)).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
}
/// Tail window (after the pluck has decayed), in interleaved frames.
private var tailSkip: Int { Int(0.5 * sampleRate) }
private var tailWindow: Int { 16_384 }
// MARK: - Behaviour
@Test func everyModelProducesEchoesAfterTheNote() throws {
// The pluck decays by burstDur (0.08 s). Every model must still produce audible repeats well
// into the tail at a long Time / Repeats.
for index: Int in 0 ..< modelCount {
let out: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = Double(index)
pedal.time = 0.25; pedal.repeats = 4.0; pedal.mod = 0.5
}
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
#expect(tail > 1.0e-3, "model index \(index) produced no echo tail, RMS \(tail)")
}
}
@Test func modelsRenderDifferently() throws {
// Two different models at the same settings should produce substantially different output.
let tube: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.25; pedal.repeats = 3.0
}
let reverse: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 7.0; pedal.time = 0.25; pedal.repeats = 3.0
}
#expect(rmsDiff(tube, reverse) > renderDiffEpsilon,
"Tube and Reverse models should differ substantially, diff \(rmsDiff(tube, reverse))")
}
@Test func timeChangesTheEcho() throws {
let short: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.1; pedal.repeats = 3.0
}
let long: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.5; pedal.repeats = 3.0
}
#expect(rmsDiff(short, long) > renderDiffEpsilon,
"different delay times should render differently, diff \(rmsDiff(short, long))")
}
@Test func repeatsChangesTheTailLength() throws {
// More feedback (longer decay time) = a louder tail at the same point.
let few: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 0.3
}
let many: [Float] = try render { pedal in
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 6.0
}
let tailFew: Double = rms(few, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
let tailMany: Double = rms(many, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
#expect(tailMany > tailFew,
"more repeats should ring louder in the tail: many \(tailMany) vs few \(tailFew)")
}
@Test func multiHeadStaysBelowClipping() throws {
// The Multi-Head tap sum (3 taps + a feedback repeat) is gain-staged to total 1.0, so a
// full-scale input, fully wet, must not clip even where the taps align.
let out: [Float] = try render(amplitude: 1.0) { pedal in
pedal.mix = 1.0; pedal.model = 4.0; pedal.time = 0.15; pedal.repeats = 4.0
}
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 <= 1.05, "Multi-Head peaked at \(peak), above the 1.05 ceiling")
}
@Test func renderIsDeterministic() throws {
// Every model's node graph is deterministic (no RNG), so two identical renders are identical.
for index: Int in 0 ..< modelCount {
let a: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
let b: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
#expect(a == b, "model index \(index) should render bit-identically")
}
}
// 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: DL4Pedal = DL4Pedal(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()
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 exposesKnobsAndModelSelector() throws {
let pedal: DL4Pedal = DL4Pedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Repeats", "Tone", "Mod"])
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
#expect(selectors.map { $0.label } == ["Model"])
#expect(selectors.first?.stops.count == modelCount)
#expect(selectors.first?.stops.map { $0.title } ==
["Tube", "Tape", "Analog", "Analog Mod", "Multi-Head", "Sweep", "Lo-Res", "Reverse"])
}
@Test func timeIsTempoSyncable() throws {
let pedal: DL4Pedal = DL4Pedal()
#expect(pedal.tempoSyncableParams.map { $0.key } == ["time"])
}
@Test func presetRoundTripPreservesControls() throws {
let pedal: DL4Pedal = DL4Pedal()
pedal.time = 0.33
pedal.repeats = 2.2
pedal.tone = 4000.0
pedal.mod = 0.7
pedal.model = 5.0
let state: PedalState = pedal.captureState()
let restored: DL4Pedal = DL4Pedal()
restored.applyState(state)
#expect(restored.time == 0.33)
#expect(restored.repeats == 2.2)
#expect(restored.tone == 4000.0)
#expect(restored.mod == 0.7)
#expect(restored.model == 5.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "DL4")
#expect(pedal is DL4Pedal)
}
}
@@ -0,0 +1,386 @@
// 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)
}
}
@@ -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)
}
}