4 Commits

Author SHA1 Message Date
josh 75de04160b feat(script-phaser): one-knob four-stage phaser (orange script voicing)
Add ScriptPhaserPedal, modeled on the classic one-knob four-stage orange
phaser. A single Speed knob sweeps a fixed four-stage all-pass cascade
(Phaser.Audio with stages: 4), and a Voicing two-state switch picks
Script (smoother, lower feedback) or Block (more resonant, higher
feedback). The voicing maps to the feedback amount through a live linear
expression — no rebuild, since feedback is a live Phaser parameter — and
a short Lag glides the coefficient so a Script↔Block toggle doesn't step
audibly. Distinct from the general-purpose Phaser (six stages, with rate
and feedback knobs).

Named to avoid the trademark (per the amp convention) and the bare
"Phase <n>" the code-style rule bans. Wire into PedalType, the registry,
and the modulation category; add to the README modulation catalog.
8 tests: voicing and speed each change the output by a magnitude (RMS
difference), determinism (bit-identical, no RNG), a click-free bypass
flip at the 512-sample block, knob/switch exposure, preset round-trip,
registry presence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 12:34:16 -08:00
josh 74227400ad feat(granular-reverb): pitch-scattered grain-cloud reverb
Add GranularReverbPedal: a diffuse, blooming wash built from an
InputGrain cloud — short grains sprayed from a rolling capture at a
chosen density, each smeared in time and given a random pitch offset
(scatter) around a center pitch — then reverberated through a GVerb tank,
folded stereo→mono. Deliberately unlike Shimmer Reverb: an incoherent
random-scatter grain cloud, not a tuned coherent feedback octave tail.
At pitch 0 / scatter 0 it tracks the input's pitch; raising scatter
smears it into a broadband haze.

The cloud is power-normalized by sqrt(grain overlap = density·grain), so
turning density up thickens the texture at a roughly constant level and
the peak stays bounded below clipping even at max overlap with correlated
grains (no downstream limiter). Scatter is scaled by the center ratio so
the per-grain spread stays proportional and a down-shifted cloud never
reaches a negative (reverse) ratio.

Knobs: Decay/Damp (GVerb tail), Density, Grain (duration), Pitch
(semitones), Scatter (the defining control). Wire into PedalType, the
registry, and the reverb category; add to the README reverb catalog.
10 tests: scatter smears pitch (normalized-autocorrelation tonalness),
density normalization bounds the peak at the worst overlap corner (decay
12 s, near-full-scale input), density changes texture, tail persistence,
determinism, a click-free bypass flip at the 512-sample block, knob
labels, preset round-trip, registry presence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 11:23:30 -08:00
josh 243be726ea feat(reverse-reverb): backwards-swelling reverb pedal
Add ReverseReverbPedal: the "sucked-in" pre-verb of ambient/shoegaze
records. The dry signal runs through the existing segmented ReverseDelay
generator — notes are captured in fixed segments and played back
reversed, so a decay becomes a swell rising into the note — then feeds a
GVerb room tank, folded stereo→mono, so the backwards swell arrives
wrapped in a diffuse wash. Distinct from the plain Reverse Delay (no
reverb) and a forward Room Reverb (energy follows the note instead of
swelling up to it).

Knobs: Time (reverse segment length / swell pre-delay, tempo-syncable),
Decay/Size/Damp (GVerb tail). GVerb dry/tail/early levels kept modest for
output headroom, and early reflections trimmed since they fire forward,
against the backwards character. Latency is one segment.

Wire into PedalType, the registry, and the reverb category; add to the
README reverb catalog. 9 tests: pre-delay (energy arrives after one
segment), a rising-swell-shape assertion across the reversed segment,
reverb tail persistence, determinism, a click-free bypass flip at the
512-sample block, knob labels, preset round-trip, registry presence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 10:14:58 -08:00
josh 20b2034fed feat(poly-octave): EHX POG-style polyphonic octave pedal
Add PolyOctavePedal: a fixed-interval polyphonic octave generator. Four
PitchShift voices at exact power-of-two ratios — −2, −1, +1, +2 octaves,
each single-stage within PitchShift's [0.25, 4.0] clamp — stacked under a
dry voice, each with its own level. Because the ratios need no pitch
tracking, chords stack as cleanly as single notes.

A Tone low-pass shapes the shifted voices (dry stays clean). An Attack
knob adds the POG's volume swell via a "slow-gear" gain: the ratio of a
slow envelope follower to a fast one, clamped to [0, 1] and guarded
against divide-by-zero — unity (instant) at Attack 0, blooming in as it
rises, independent of playing level. The five voice levels sum without an
internal limiter (as with BassOctaver); the level knob and board master
set final gain.

Wire into PedalType, the registry, and the pitch category; add to the
README pitch catalog. 12 tests: per-voice pitch (±1/±2 oct + unison) by
autocorrelation, swell neutral-vs-bloom, seeded determinism, a click-free
bypass flip at the real 512-sample block, knob labels, preset round-trip,
registry presence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 09:53:43 -08:00
13 changed files with 2132 additions and 3 deletions
+1
View File
@@ -23,3 +23,4 @@ review.diff
# Local working plan (not shared)
docs/plans/amp-expansion-plan.md
docs/plans/pedal-expansion-plan.md
+3 -3
View File
@@ -46,10 +46,10 @@ signal (no hardware needed) or on live guitar through an audio input.
| Gain | Overdrive, Distortion, Fuzz, Sustain Fuzz |
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate, Volume |
| EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant |
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy |
| 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 |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, 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) |
+4
View File
@@ -96,6 +96,7 @@ public extension PedalType {
static let vibe = PedalType("Vibe")
static let rotary = PedalType("Rotary")
static let ringModulator = PedalType("Ring Modulator")
static let scriptPhaser = PedalType("Script Phaser")
static let diffuser = PedalType("Diffuser")
static let bitcrusher = PedalType("Bitcrusher")
static let granulator = PedalType("Granulator")
@@ -118,12 +119,15 @@ public extension PedalType {
static let plateReverb = PedalType("Plate Reverb")
static let roomReverb = PedalType("Room Reverb")
static let springReverb = PedalType("Spring Reverb")
static let reverseReverb = PedalType("Reverse Reverb")
static let granularReverb = PedalType("Granular Reverb")
// Pitch & octave
static let octaveSplitter = PedalType("Octave Splitter")
static let bassOctaver = PedalType("Bass Octaver")
static let harmonizer = PedalType("Harmonizer")
static let whammy = PedalType("Whammy")
static let polyOctave = PedalType("Poly Octave")
// Looper
static let looper = PedalType("Looper")
@@ -0,0 +1,208 @@
// GranularReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Granular-cloud reverb — a diffuse, blooming wash built from a cloud of pitch-scattered grains,
/// then reverberated.
///
/// The dry signal feeds an `InputGrain` cloud: short grains are sprayed from a rolling capture of
/// the input at a chosen `density`, each smeared slightly in time and given a random pitch offset
/// (`scatter`) around a center `pitch`. That cloud then drives a `GVerb` room tank, folded
/// stereo→mono, so the grains bloom into a reverberant pad.
///
/// This is deliberately **unlike** the ``ShimmerReverbPedal``: Shimmer is a tuned feedback tank
/// regenerating a clean, coherent octave-up tail; this is an incoherent grain cloud whose defining
/// control is the **random** per-grain pitch `scatter`. At `pitch = 0, scatter = 0` the cloud
/// tracks the input's pitch; raising `scatter` smears it into a broadband haze — a grain cloud, not
/// an ascending shimmer. Set `pitch` for a tuned (e.g. octave-up) cloud, or leave it at `0` for an
/// untuned ambient bloom.
///
/// The base `Pedal` `mix` sets the wet/dry blend.
///
/// ## Knobs
/// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`.
/// - `density`: Grain cloud density in grains per second. Range `[5, 80]`.
/// - `grain`: Grain duration in seconds. Range `[0.02, 0.3]`.
/// - `pitch`: Cloud center pitch in semitones. Range `[-24, 24]`; `0` = unpitched (tracks input).
/// - `scatter`: Random per-grain pitch spread (± ratio around center). Range `[0, 0.5]`.
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
public final class GranularReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"A cloud of pitch-scattered grains blooming into reverb — a diffuse, incoherent wash."
}
// MARK: - Parameters
/// GVerb reverb time (T60) in seconds. Range [0.2, 12.0].
@UIParam public var decay: Double = 4.0
/// Grain cloud density in grains per second. Range [5, 80].
@UIParam public var density: Double = 25.0
/// Grain duration in seconds. Range [0.02, 0.3].
@UIParam public var grain: Double = 0.12
/// Cloud center pitch in semitones. Range [-24, 24]; 0 = unpitched (tracks input).
@UIParam public var pitch: Double = 0.0
/// Random per-grain pitch spread, as a fraction of the center ratio (`0.5` = ±50% of the shifted
/// speed), added bipolar per grain. Range [0, 0.5]. Scaling by the center keeps the spread
/// proportional, so a down-shifted cloud doesn't send grains to a negative (reverse) ratio. The
/// defining control — higher = more smeared and incoherent.
@UIParam public var scatter: Double = 0.15
/// High-frequency damping in [0, 1]. Higher = darker tail.
@UIParam public var damp: Double = 0.5
// MARK: - Constants
/// Default wet/dry blend — the cloud wash sits under the dry note.
private static let defaultMix: Double = 0.4
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio` to turn
/// the `pitch` knob into a `pitchRatio` for the grain cloud.
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
/// Grain read position in the rolling capture, `[0, 1]` (0 = newest). Slightly into the past so
/// each grain has recorded material to read even at the lowest density.
private let cloudPosition: Double = 0.1
/// Random spread applied to the read position per grain — a small time smear that keeps the
/// cloud diffuse rather than a tight repeat.
private let cloudPositionSpread: Double = 0.1
/// Reference output gain on the grain cloud before the tank, applied after density
/// normalisation (see ``effect(_:)``). `InputGrain` sums every active grain, so the raw cloud
/// level scales with the grain overlap (`density · grain`); without normalisation the extremes
/// of those knobs (and correlated grains at low scatter) could sum to several times the input
/// and clip. The cloud is divided by `sqrt(overlap)` (power normalisation), so turning density
/// up thickens the texture at a roughly constant level instead of raising the peak toward
/// clipping.
private let cloudGain: Double = 0.5
/// Lower bound on the overlap estimate (`density · grain`) before the `sqrt` normalisation, so a
/// sparse cloud (overlap < 1) is not boosted by dividing by a fraction.
private let minOverlap: Double = 1.0
/// Fixed PRNG seed for the grain scheduling and pitch scatter, so a given setting renders
/// identically every time (reproducible audio and tests).
private let cloudSeed: UInt64 = 0x3C6E_F372_FE94_F82B
/// GVerb room size in metres (fixed; the grain/reverb controls shape the character instead).
private let roomSizeMeters: Double = 40.0
/// GVerb early-reflection level. Low, so the wash favours the diffuse grain tail over discrete
/// reflections.
private let reverbEarlyLevel: Double = 0.2
/// GVerb late-reverb (tail) level.
private let reverbTailLevel: Double = 0.6
/// GVerb dry level — how much of the grain cloud passes through the tank's dry path, keeping the
/// grain texture itself present under its reverb.
private let reverbDryLevel: Double = 0.3
/// Gain folding a decorrelated stereo pair to mono. A conservative trim leaving output headroom.
private let stereoSumGain: Double = 0.5
// MARK: - Ranges
private let decayRange: ClosedRange<Double> = 0.2 ... 12.0
private let densityRange: ClosedRange<Double> = 5.0 ... 80.0
private let grainRange: ClosedRange<Double> = 0.02 ... 0.3
private let pitchRange: ClosedRange<Double> = -24.0 ... 24.0
private let scatterRange: ClosedRange<Double> = 0.0 ... 0.5
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Density", node: $density, range: densityRange),
PedalKnob(label: "Grain", node: $grain, range: grainRange),
PedalKnob(label: "Pitch", node: $pitch, range: pitchRange),
PedalKnob(label: "Scatter", node: $scatter, range: scatterRange),
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
]
}
// MARK: - Init
/// Creates a granular-reverb 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: "Granular Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: GranularReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Center pitch (semitones → ratio); per-grain scatter is added bipolar around it inside
// InputGrain.
let centerRatio: Exp.Audio = Exp.Audio($pitch * semitoneToRatioScale)
// Density normalisation: divide the cloud by sqrt(grain overlap = density·grain), clamped so
// a sparse cloud isn't boosted. Keeps the level roughly constant across the density/grain
// knobs and bounds the peak away from clipping even with correlated grains at low scatter.
let overlap: any ValidGeneratorInput = Max.Audio($density * $grain, minOverlap)
let cloudNormGain: any ValidGeneratorInput = Reciprocal.Audio(Sqrt.Audio(overlap)) * cloudGain
// Scatter scaled by the center ratio, so the per-grain spread is proportional (±scatter of
// the shifted speed). This keeps a down-shifted cloud off a negative/reverse ratio, which an
// absolute offset would reach at low pitch + high scatter.
let scaledScatter: any ValidGeneratorInput = centerRatio * $scatter
// The grain cloud (native stereo via per-grain pan).
let cloud: InputGrain = InputGrain(
input: dry,
position: cloudPosition,
positionSpread: cloudPositionSpread,
duration: $grain,
pitchRatio: centerRatio,
pitchDispersion: scaledScatter,
density: $density,
seed: cloudSeed,
mul: cloudNormGain
)
// Fold the cloud to mono for the tank source.
let cloudMono: SumChannels.Audio = SumChannels.Audio(
input: cloud,
mul: stereoSumGain
)
// Reverberate the cloud (native stereo); `dryLevel` keeps the grain texture present.
let stereoVerb: GVerb.Audio = GVerb.Audio(
source: cloudMono,
roomSize: roomSizeMeters,
reverbTime: $decay,
damping: $damp,
earlyLevel: reverbEarlyLevel,
tailLevel: reverbTailLevel,
dryLevel: reverbDryLevel,
sampleRate: sampleRate
)
// Fold the reverb output stereo → mono.
return SumChannels.Audio(
input: stereoVerb,
mul: stereoSumGain
)
}
}
@@ -0,0 +1,242 @@
// PolyOctavePedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Polyphonic octave generator in the EHX POG mould.
///
/// Stacks four fixed pitch-shifted voices — two octaves down, one octave down, one octave up, two
/// octaves up — under the dry note, each with its own level, so a single note becomes an
/// organ-like chord of octaves. Unlike the ``WhammyPedal`` (one voice swept by an expression
/// pedal), every voice sounds at once at a **fixed** interval, and because the ratios are exact
/// powers of two the shifter needs no pitch tracking — chords shift as cleanly as single notes.
///
/// Each voice is a `PitchShift` — Lyrebird's four-head SOLA shifter, whose `pitchRatio` clamps to
/// `[0.25, 4.0]`, i.e. exactly ±2 octaves, so every voice here is a single stage (no cascade).
///
/// The five voice levels sum without an internal limiter (as with the OC-2-style
/// ``BassOctaverPedal``), so driving several to full can push the sum above unity; the pedal's
/// `level` knob and the board output master set the final gain, like a real mixer's channel sum.
///
/// A low-pass **Tone** control tames the shifted voices (the dry stays untouched), and an
/// **Attack** control adds the POG's signature volume **swell**: turned up, the octave voices fade
/// in after each note instead of sounding instantly, for a bowed / synth-pad bloom. The swell is a
/// "slow-gear" gain — the ratio of a slow envelope follower to a fast one — so at `Attack = 0` the
/// two followers are identical and the gain is unity (voices respond instantly), and the swell
/// never depends on how loud you play.
///
/// ## Knobs
/// - `subTwo`: −2 octave voice level in `[0, 1]`.
/// - `subOne`: −1 octave voice level in `[0, 1]`.
/// - `upOne`: +1 octave voice level in `[0, 1]`.
/// - `upTwo`: +2 octave voice level in `[0, 1]`.
/// - `dry`: Dry (direct) signal level in `[0, 1]`.
/// - `attack`: Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom.
/// - `tone`: Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
public final class PolyOctavePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Stacks fixed octave voices under your note — organ-like, with a volume swell."
}
// MARK: - Parameters
/// −2 octave voice level in `[0, 1]`.
@UIParam public var subTwo: Double = 0.0
/// −1 octave voice level in `[0, 1]`.
@UIParam public var subOne: Double = 0.0
/// +1 octave voice level in `[0, 1]`.
@UIParam public var upOne: Double = 0.5
/// +2 octave voice level in `[0, 1]`.
@UIParam public var upTwo: Double = 0.0
/// Dry (direct) signal level in `[0, 1]`.
@UIParam public var dry: Double = 1.0
/// Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom after each note.
@UIParam public var attack: Double = 0.0
/// Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
@UIParam public var tone: Double = 8000.0
// MARK: - Constants
/// Pedal blends everything internally via the level knobs, so the base wet/dry stays fully wet.
private static let defaultMix: Double = 1.0
/// Fixed `PitchShift` playback ratios for the four voices (exact powers of two).
private let subTwoRatio: Double = 0.25 // −2 octaves
private let subOneRatio: Double = 0.5 // −1 octave
private let upOneRatio: Double = 2.0 // +1 octave
private let upTwoRatio: Double = 4.0 // +2 octaves
/// Grain window for each `PitchShift`, in seconds. A touch over the shifter's `0.1` default to
/// soften the periodic four-head comb without adding audible lag.
private let voiceWindowSize: Double = 0.11
/// Per-head timing jitter for each `PitchShift`, in seconds. Breaks the fixed-grid comb; kept
/// small so the voices stay tight.
private let voiceTimeDispersion: Double = 0.02
/// Fixed PRNG seeds, one per voice, so a given setting renders identically every time
/// (reproducible audio and exact-pitch tests). Distinct per voice so their grain dispersion
/// sequences decorrelate instead of jittering in lockstep.
private let subTwoSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
private let subOneSeed: UInt64 = 0xC2B2_AE3D_27D4_EB4F
private let upOneSeed: UInt64 = 0x1656_67B1_9E37_79F9
private let upTwoSeed: UInt64 = 0x2545_F491_4F6C_DD1D
/// Fast envelope-follower attack for the swell's denominator, in seconds — near-instant, so it
/// tracks note onsets tightly. Also the floor of the mapped slow attack, so `attack = 0` makes
/// the two followers identical and the swell gain unity (neutral).
private let swellFastAttack: Double = 0.005
/// Slowest envelope-follower attack the `attack` knob maps to, in seconds (at `attack = 1`).
private let swellMaxAttack: Double = 1.5
/// Shared release time for both swell followers, in seconds. Equal on both so only the attack
/// differs between them.
private let swellRelease: Double = 0.15
/// Floor added to the swell denominator before the reciprocal, so a silent input (both
/// followers near zero) cannot divide by zero. Kept well below any real signal level
/// (`1e-6` ≈ −120 dB) so the neutral gain stays ~1 across the whole playing range — a larger
/// floor would pull the `attack = 0` gain toward `0.5` for quiet input.
private let swellDenomFloor: Double = 1.0e-6
/// Clamp bounds for the swell gain. With equal release times the two followers track in
/// lockstep once settled, so the ratio stays `≤ 1` in normal use (it dips below `1` only during
/// the attack ramp, when the slow follower lags); the ceiling is a defensive guard against a
/// transient overshoot from the reciprocal, and the floor keeps the gain non-negative.
private let swellGainFloor: Double = 0.0
private let swellGainCeil: Double = 1.0
/// Butterworth Q (no resonant peak) for the tone low-pass.
private let toneQ: Double = 0.707
// MARK: - Ranges
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
private let attackRange: ClosedRange<Double> = 0.0 ... 1.0
private let toneRange: ClosedRange<Double> = 500.0 ... 12000.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "-2 Oct", node: $subTwo, range: levelRange),
PedalKnob(label: "-1 Oct", node: $subOne, range: levelRange),
PedalKnob(label: "+1 Oct", node: $upOne, range: levelRange),
PedalKnob(label: "+2 Oct", node: $upTwo, range: levelRange),
PedalKnob(label: "Dry", node: $dry, range: levelRange),
PedalKnob(label: "Attack", node: $attack, range: attackRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a polyphonic octave pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Poly Octave",
inputBus: inputBus,
outputBus: outputBus,
initialMix: PolyOctavePedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Four fixed-ratio voices. Each ratio is within PitchShift's ±2-octave clamp, so a single
// stage suffices (no cascade, unlike the Whammy's 3-octave Dive Bomb).
let subTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subTwoRatio, seed: subTwoSeed)
let subOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subOneRatio, seed: subOneSeed)
let upOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upOneRatio, seed: upOneSeed)
let upTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upTwoRatio, seed: upTwoSeed)
// Octave bus: each voice scaled by its level knob.
let octaveBus: any ValidGeneratorInput =
(subTwoVoice * $subTwo)
+ (subOneVoice * $subOne)
+ (upOneVoice * $upOne)
+ (upTwoVoice * $upTwo)
// Swell: a "slow-gear" gain applied to the octave bus only (the dry stays immediate).
let swelled: any ValidGeneratorInput = octaveBus * swellGain(dry: dry)
// Tone shapes the shifted voices, not the dry.
let octaveToned: RBJLowPass.Audio = RBJLowPass.Audio(
input: swelled,
freq: $tone,
q: toneQ
)
return (dry * $dry) + octaveToned
}
/// Builds one fixed-ratio octave voice.
///
/// - Parameters:
/// - dry: Dry input to shift.
/// - ratio: Fixed playback ratio (power of two) within PitchShift's `[0.25, 4.0]` clamp.
/// - seed: Per-voice PRNG seed for reproducible grain dispersion.
/// - Returns: The pitch-shifted voice (pre-level).
private func makeVoice(
dry: any ValidGeneratorInput,
ratio: Double,
seed: UInt64
) -> PitchShift.Audio {
PitchShift.Audio(
input: dry,
pitchRatio: ratio,
windowSize: voiceWindowSize,
timeDispersion: voiceTimeDispersion,
seed: seed
)
}
/// Builds the octave-voice swell gain: the ratio of a slow envelope follower to a fast one,
/// clamped to `[0, 1]`. Unity when `attack = 0` (both followers identical), dipping and then
/// recovering as `attack` rises, so the voices bloom in after each onset independent of level.
///
/// - Parameter dry: Dry input the swell tracks.
/// - Returns: A `[0, 1]` gain to multiply the octave bus by.
private func swellGain(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// attack [0, 1] → slow-follower attack [swellFastAttack, swellMaxAttack] seconds.
let attackSpan: Double = swellMaxAttack - swellFastAttack
let slowAttackTime: any ValidGeneratorInput = ($attack * attackSpan) + swellFastAttack
let fastEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: swellFastAttack,
releaseTime: swellRelease
)
let slowEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: slowAttackTime,
releaseTime: swellRelease
)
// gain = slowEnv / (fastEnv + floor), clamped to [0, 1].
let denom: any ValidGeneratorInput = fastEnv + swellDenomFloor
let ratio: any ValidGeneratorInput = slowEnv * Reciprocal.Audio(denom)
return Clip.Audio(ratio, lo: swellGainFloor, hi: swellGainCeil)
}
}
@@ -0,0 +1,156 @@
// ReverseReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Reverse reverb — a backwards-swelling ambience, the "sucked-in" pre-verb of ambient and
/// shoegaze records.
///
/// The dry signal is first run through a segmented ``ReverseDelay``: it is captured in fixed-length
/// segments and each is played back reversed, so a note's natural decay becomes a swell that rises
/// *into* the note. That reversed signal then feeds a `GVerb` room tank, so the backwards swell
/// arrives wrapped in a diffuse reverberant wash rather than as a dry backwards note. The result is
/// distinct from the plain ``ReverseDelayPedal`` (no reverb) and from a forward ``RoomReverbPedal``
/// (energy that follows the note instead of swelling up to it).
///
/// `Time` sets the reverse segment length (and so the pre-delay before each swell); `Decay`, `Size`,
/// and `Damp` shape the GVerb tail. The tank runs natively in stereo and is folded to mono. The
/// base `Pedal` `mix` sets the wet/dry blend, so your live note stays up front while the reversed
/// wash sits under it. Latency is one segment — a note's reversed swell appears up to `Time` seconds
/// after you play it.
///
/// ## Knobs
/// - `time`: Reverse segment length in seconds. Range `[0.1, 2.0]`. Also the swell pre-delay.
/// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`.
/// - `size`: GVerb room size in metres. Range `[1, 100]`.
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
public final class ReverseReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Backwards-swelling reverb — notes bloom in reverse, wrapped in a diffuse wash."
}
// MARK: - Parameters
/// Reverse segment length in seconds (also the swell pre-delay). Range [0.1, 2.0].
@UIParam public var time: Double = 0.5
/// GVerb reverb time (T60) in seconds. Range [0.2, 12.0].
@UIParam public var decay: Double = 3.0
/// GVerb room size in metres. Range [1, 100].
@UIParam public var size: Double = 30.0
/// High-frequency damping in [0, 1]. Higher = darker tail.
@UIParam public var damp: Double = 0.5
// MARK: - Constants
/// Default wet/dry blend — the reversed wash sits under the dry note.
private static let defaultMix: Double = 0.4
/// Maximum reverse segment length the `ReverseDelay` buffers are allocated for, in seconds.
/// Matches the top of the `time` range so a full-length segment never clamps.
private let maxReverseTime: Double = 2.0
/// Reverse-trail feedback. Kept at `0` so each swell is a single clean pass (the GVerb tail,
/// not recirculated reverse segments, provides the sustain).
private let reverseFeedback: Double = 0.0
/// GVerb dry level — how much of the GVerb *source* passes through the tank's dry path. The
/// source here is the already-reversed signal (not the raw input), so this keeps the backwards
/// swell itself audible under its reverb rather than being fully smeared. The pedal's own `mix`
/// then blends this whole wet result against the true dry note. Kept at `0.5` (with the tail and
/// early levels below) so the summed wet path keeps headroom below clipping on a loud input.
private let reverseSwellLevel: Double = 0.5
/// GVerb late-reverb (tail) level.
private let reverbTailLevel: Double = 0.5
/// GVerb early-reflection level. Lowered from the generator's `0.4` default: early reflections
/// fire forward (not reversed), so a high level would fight the backwards-swell character; a
/// smaller amount keeps some room sense while favouring the reversed tail, and trims the sum.
private let reverbEarlyLevel: Double = 0.3
/// Gain folding GVerb's two decorrelated reverb channels to mono. A conservative trim (not a
/// strict doubling correction — the channels are not identical), leaving output headroom.
private let stereoSumGain: Double = 0.5
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.1 ... 2.0
private let decayRange: ClosedRange<Double> = 0.2 ... 12.0
private let sizeRange: ClosedRange<Double> = 1.0 ... 100.0
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Size", node: $size, range: sizeRange),
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
]
}
// MARK: - Init
/// Creates a reverse-reverb 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: "Reverse Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ReverseReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Reverse the dry in fixed segments: a note's decay becomes a swell rising into it.
let reversed: ReverseDelay = ReverseDelay(
input: dry,
maxDelay: maxReverseTime,
delay: $time,
feedback: reverseFeedback,
sampleRate: sampleRate
)
// Wrap the reversed swell in a GVerb room tank (native stereo). `dryLevel` keeps the swell
// itself present under the reverb.
let stereoVerb: GVerb.Audio = GVerb.Audio(
source: reversed,
roomSize: $size,
reverbTime: $decay,
damping: $damp,
earlyLevel: reverbEarlyLevel,
tailLevel: reverbTailLevel,
dryLevel: reverseSwellLevel,
sampleRate: sampleRate
)
// Sum stereo → mono with ×0.5 to avoid level doubling.
return SumChannels.Audio(
input: stereoVerb,
mul: stereoSumGain
)
}
}
@@ -0,0 +1,147 @@
// ScriptPhaserPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Script phaser — the classic one-knob, four-stage orange phaser (the script-logo voicing).
///
/// A single **Speed** knob sweeps a fixed four-stage all-pass cascade; there is no depth or
/// feedback knob, just the signature liquid whoosh. A **Voicing** switch picks the character: the
/// smoother *Script* voicing (lower feedback, gentler notch) or the more resonant *Block* voicing
/// (more feedback, sharper notch) — the two eras of the hardware.
///
/// Distinct from the general-purpose ``PhaserPedal`` (six stages, with rate **and** feedback knobs):
/// this is deliberately the fixed, four-stage, one-knob classic. Wraps the shared `Phaser.Audio`
/// generator run fully wet; the base `Pedal` `mix` sets the wet/dry blend.
///
/// ## Knobs
/// - `speed`: LFO sweep rate in Hz. Range `[0.05, 5.0]`.
///
/// ## Switches
/// - `voicing` (two-state): `0` = Script (smoother), `1` = Block (more resonant).
public final class ScriptPhaserPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"The one-knob four-stage orange phaser — liquid whoosh, script or block voicing."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.05, 5.0].
@UIParam public var speed: Double = 0.5
/// Voicing selector. `0` = Script (smoother, lower feedback), `1` = Block (more resonant).
@UIParam public var voicing: Double = 0.0
// MARK: - Constants
/// Default wet/dry blend — an even mix for the classic comb-filter sweep.
private static let defaultMix: Double = 0.5
/// Internal `Phaser.Audio` mix — `1.0` so the base `Pedal` handles dry/wet.
private let phaserInternalMix: Double = 1.0
/// LFO depth fraction — sweeps the all-pass coefficient across its range.
private let phaserDepth: Double = 0.9
/// Center frequency in Hz for the all-pass coefficient sweep.
private let phaserCenterFreq: Double = 800.0
/// Four cascaded all-pass stages — the defining topology of this phaser (`Phaser.Audio`
/// requires 4, 6, or 8).
private let phaserStages: Int = 4
/// Feedback for the Script voicing — low, for a smooth gentle notch.
private let scriptFeedbackValue: Double = 0.2
/// Feedback for the Block voicing — higher, for a sharper, more resonant notch.
private let blockFeedbackValue: Double = 0.45
// MARK: - Switch values
private let voicingScriptValue: Double = 0.0
private let voicingBlockValue: Double = 1.0
/// Smoothing time in seconds for the voicing→feedback change, so flipping Script↔Block glides
/// the feedback coefficient instead of stepping it (which could tick on a live toggle).
private let voicingSmoothTime: Double = 0.03
// MARK: - Ranges
private let speedRange: ClosedRange<Double> = 0.05 ... 5.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "speed", label: "Speed", node: $speed, kind: .rate, range: speedRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Speed", node: $speed, range: speedRange),
]
}
// MARK: - Switches
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Voicing",
node: $voicing,
options: [
PedalSwitch.Option(title: "Script", value: voicingScriptValue),
PedalSwitch.Option(title: "Block", value: voicingBlockValue),
]
)
]
}
// MARK: - Init
/// Creates a script-phaser 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: "Script Phaser",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ScriptPhaserPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Voicing (0 = Script, 1 = Block) selects the feedback amount live — a linear map between the
// two fixed values, no rebuild needed since feedback is a live Phaser parameter. A short Lag
// glides the coefficient on a Script↔Block toggle so it doesn't step audibly.
let feedbackSpan: Double = blockFeedbackValue - scriptFeedbackValue
let voicedFeedback: any ValidGeneratorInput = ($voicing * feedbackSpan) + scriptFeedbackValue
let smoothedFeedback: Lag.Audio = Lag.Audio(input: voicedFeedback, time: voicingSmoothTime)
return Phaser.Audio(
input: dry,
rate: $speed,
depth: phaserDepth,
centerFreq: phaserCenterFreq,
feedback: smoothedFeedback,
stages: phaserStages,
mix: phaserInternalMix,
sampleRate: sampleRate
)
}
}
@@ -69,6 +69,7 @@ public enum PedalRegistry {
"Sustain Fuzz": { SustainFuzzPedal() },
"Tremolo": { TremoloPedal() },
"Phaser": { PhaserPedal() },
"Script Phaser": { ScriptPhaserPedal() },
"Compressor": { CompressorPedal() },
"Mutant": { MutantPedal() },
"Auto-Wah": { AutoWahPedal() },
@@ -80,12 +81,15 @@ public enum PedalRegistry {
"Bass Octaver": { BassOctaverPedal() },
"Harmonizer": { HarmonizerPedal() },
"Whammy": { WhammyPedal() },
"Poly Octave": { PolyOctavePedal() },
"Ping-Pong": { PingPongDelayPedal() },
"Reverse Delay": { ReverseDelayPedal() },
"Shimmer Reverb": { ShimmerReverbPedal() },
"Plate Reverb": { PlateReverbPedal() },
"Room Reverb": { RoomReverbPedal() },
"Spring Reverb": { SpringReverbPedal() },
"Reverse Reverb": { ReverseReverbPedal() },
"Granular Reverb": { GranularReverbPedal() },
"Limiter": { LimiterPedal() },
"Cabinet": { CabinetPedal() },
"Noise Gate": { NoiseGatePedal() },
@@ -53,11 +53,14 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
"Cabinet": .cabinet,
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
"Script Phaser": .modulation,
"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,
"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,
]
}
@@ -0,0 +1,382 @@
// GranularReverbPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine source.
@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))
}
}
/// A decaying sine burst (full at t=0, silent after `burstDur`) for tail checks.
@MainActor
private final class TestBurstSource: 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 envelope: Line.Control = Line.Control(start: 1.0, end: 0.0, dur: burstDur)
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp) * envelope)
}
}
@MainActor
@Suite("GranularReverbPedal")
struct GranularReverbPedalTests {
private let sampleRate: Double = 44_100.0
private let sineHz: Double = 220.0
private let analysisSkipFrames: Int = 13_230 // ~0.3 s, clears warm-up
private let analysisWindowFrames: Int = 16_384
// MARK: - Render
private func render(
duration: Double,
makeSource: @escaping (Int) -> any Synthesizer,
configure: (GranularReverbPedal) -> 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: any Synthesizer = makeSource(srcBus.index)
let pedal: GranularReverbPedal = GranularReverbPedal(
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
/// Normalised peak autocorrelation of the left channel over the analysis window — a "tonalness"
/// score in ~[0, 1]: near 1 for a clean periodic tone, low for a smeared/inharmonic cloud.
private func tonalness(_ samples: [Float]) -> Double {
let needed: Int = analysisSkipFrames + analysisWindowFrames
guard samples.count >= 2 * needed else { return 0.0 }
var x: [Double] = []
x.reserveCapacity(analysisWindowFrames)
for i: Int in analysisSkipFrames ..< 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 }
var zeroLag: Double = 0.0
for v: Double in x { zeroLag += v * v }
guard zeroLag > 0.0 else { return 0.0 }
let minLag: Int = Int(sampleRate / 1_000.0) // up to 1 kHz
let maxLag: Int = min(Int(sampleRate / 50.0), x.count - 1)
var best: Double = 0.0
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 > best { best = c }
}
return best / zeroLag
}
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()
}
/// Peak absolute left-channel sample over an interleaved-frame range `[loFrame, hiFrame)`.
private func peak(_ 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 m: Double = 0.0
for i: Int in a ..< b {
let v: Double = abs(Double(samples[2 * i]))
if v > m { m = v }
}
return m
}
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
}
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try render(
duration: 0.8,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { _ in }
)
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "granular-reverb output was silent")
}
@Test func higherScatterSmearsPitchIntoBroadbandHaze() throws {
// The defining character: at pitch 0 and scatter 0 the cloud tracks the input's pitch
// (fairly tonal); raising scatter sprays grains across random ratios, smearing the output
// into a broadband haze (low tonalness) — a grain cloud, not a coherent shimmer.
let coherent: [Float] = try render(
duration: 1.0,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { pedal in
pedal.mix = 1.0
pedal.pitch = 0.0
pedal.scatter = 0.0
pedal.density = 60.0
pedal.decay = 0.8 // short tail so cloud tonalness dominates the window
}
)
let smeared: [Float] = try render(
duration: 1.0,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { pedal in
pedal.mix = 1.0
pedal.pitch = 0.0
pedal.scatter = 0.5
pedal.density = 60.0
pedal.decay = 0.8
}
)
let coherentTonalness: Double = tonalness(coherent)
let smearedTonalness: Double = tonalness(smeared)
#expect(hasNonSilentOutput(smeared), "smeared render was silent")
#expect(coherentTonalness > smearedTonalness * 1.3,
"scatter should smear pitch (coherent \(coherentTonalness) vs smeared \(smearedTonalness))")
}
@Test func densityNormalizationBoundsThePeak() throws {
// Worst case for clipping: max density × max grain (heaviest overlap), scatter 0 (grains
// correlated), fully wet, driven by a near-full-scale sine. The sqrt power normalisation must
// keep the output peak bounded — nothing downstream limits it.
let out: [Float] = try render(
duration: 1.0,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz, amplitude: 0.9) },
configure: { pedal in
pedal.mix = 1.0
pedal.density = 80.0
pedal.grain = 0.3
pedal.scatter = 0.0
pedal.decay = 12.0 // longest tail → most reverb buildup, worst case for peak
}
)
let peakOut: Double = peak(out, loFrame: Int(0.3 * sampleRate), hiFrame: Int(0.95 * sampleRate))
#expect(hasNonSilentOutput(out), "max-overlap render was silent")
#expect(peakOut < 1.0, "density normalisation should keep the peak below clipping, got \(peakOut)")
}
@Test func densityChangesTheTexture() throws {
// Normalisation keeps the LEVEL roughly constant, but density still changes the grain
// texture — a sparse and a dense cloud must not render identically, and both must sound.
let sparse: [Float] = try render(
duration: 1.0,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { pedal in
pedal.mix = 1.0; pedal.density = 8.0; pedal.scatter = 0.1; pedal.decay = 1.0
}
)
let dense: [Float] = try render(
duration: 1.0,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { pedal in
pedal.mix = 1.0; pedal.density = 70.0; pedal.scatter = 0.1; pedal.decay = 1.0
}
)
#expect(hasNonSilentOutput(sparse) && hasNonSilentOutput(dense), "a density render was silent")
#expect(sparse != dense, "sparse and dense clouds should render differently")
}
@Test func reverbTailPersistsAfterInput() throws {
let out: [Float] = try render(
duration: 1.4,
makeSource: { bus in
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.15)
},
configure: { pedal in
pedal.mix = 1.0
pedal.decay = 6.0
pedal.density = 40.0
}
)
let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate))
#expect(lateRMS > 1.0e-4, "granular-reverb tail should still ring late, got \(lateRMS)")
}
@Test func renderIsDeterministic() throws {
// The grain cloud is seeded and GVerb is RNG-free, so two identical renders are bit-identical.
let make: () throws -> [Float] = {
try self.render(
duration: 0.8,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { pedal in
pedal.scatter = 0.3
pedal.density = 30.0
}
)
}
let a: [Float] = try make()
let b: [Float] = try make()
#expect(a == b, "seeded granular-reverb renders of the same setting should be bit-identical")
}
// 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: sineHz)
let pedal: GranularReverbPedal = GranularReverbPedal(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 exposesSixKnobs() throws {
let pedal: GranularReverbPedal = GranularReverbPedal()
#expect(pedal.effectKnobs.map { $0.label }
== ["Decay", "Density", "Grain", "Pitch", "Scatter", "Damp"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: GranularReverbPedal = GranularReverbPedal()
pedal.decay = 5.0
pedal.density = 40.0
pedal.grain = 0.2
pedal.pitch = 12.0
pedal.scatter = 0.3
pedal.damp = 0.4
let state: PedalState = pedal.captureState()
let restored: GranularReverbPedal = GranularReverbPedal()
restored.applyState(state)
#expect(restored.decay == 5.0)
#expect(restored.density == 40.0)
#expect(restored.grain == 0.2)
#expect(restored.pitch == 12.0)
#expect(restored.scatter == 0.3)
#expect(restored.damp == 0.4)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Granular Reverb")
#expect(pedal is GranularReverbPedal)
}
}
@@ -0,0 +1,412 @@
// PolyOctavePedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine source for pitch tests — a known, stable fundamental the octave voices can shift
/// so a test can measure the output pitch.
@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("PolyOctavePedal")
struct PolyOctavePedalTests {
// MARK: - Analysis constants
/// Engine sample rate (matches `makeNRTEngine`'s default).
private let sampleRate: Double = 44_100.0
/// Render long enough that the analysis window lands well past the shifter's warm-up.
private let renderDuration: Double = 0.8
/// Test tone fundamental. Mid-range so ±2 octaves stays inside `[20, Nyquist]`.
private let sineHz: Double = 220.0
/// Interleaved-stereo frame offset to start analysis at — clears the shifter's warm-up.
private let analysisSkipFrames: Int = 13_230 // ~0.3 s
/// Analysis window length in frames. ~0.37 s → ≥10 cycles even at −2 octaves.
private let analysisWindowFrames: Int = 16_384
// MARK: - Render helpers
/// Renders the pedal driven by a steady sine at `sineHz`, over `renderDuration`.
private func renderSine(
configure: (PolyOctavePedal) -> Void
) throws -> [Float] {
try renderSine(duration: renderDuration, configure: configure)
}
/// Renders the pedal driven by a steady sine at `sineHz`, over a caller-chosen duration (the
/// swell test needs a longer window to see the bloom develop).
private func renderSine(
duration: Double,
configure: (PolyOctavePedal) -> 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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: PolyOctavePedal = PolyOctavePedal(
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: - Signal analysis
/// Estimates the fundamental of the left channel by autocorrelation. Searches lags in
/// `[20 Hz, maxHz]`; a deep down-shift carries strong grain-rate HF that a wide search would lock
/// onto, so callers testing those pass a ceiling near the expected Hz.
private func fundamentalHz(_ samples: [Float], minHz: Double = 20.0, maxHz: Double = 1_500.0) -> Double {
let needed: Int = analysisSkipFrames + analysisWindowFrames
guard samples.count >= 2 * needed else { return 0.0 }
var x: [Double] = []
x.reserveCapacity(analysisWindowFrames)
for i: Int in analysisSkipFrames ..< needed {
x.append(Double(samples[2 * i])) // left channel of the interleaved pair
}
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 left channel over an interleaved-frame range `[lo, hi)`.
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()
}
/// Max absolute first difference (per-sample step) over `[lo, hi)`. An impulsive click shows up
/// as a step far larger than the signal's own slope.
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
}
// MARK: - Pitch behaviour (one voice isolated at a time, dry muted)
@Test func upOneVoiceRaisesPitchAnOctave() throws {
// +1 oct voice alone (ratio 2.0): 220 Hz should land near 440 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "+1 oct render was silent")
// ±12% is tight enough to reject a wrong interval (a fifth is +50%) but clears the
// autocorrelation lag quantisation (~1% here) and the shifter's warble.
#expect(abs(hz - sineHz * 2.0) < sineHz * 2.0 * 0.12, "+1 oct should be ~440 Hz, got \(hz)")
}
@Test func subOneVoiceLowersPitchAnOctave() throws {
// −1 oct voice alone (ratio 0.5): 220 Hz should land near 110 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.subOne = 1.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "−1 oct render was silent")
#expect(abs(hz - sineHz * 0.5) < sineHz * 0.5 * 0.12, "−1 oct should be ~110 Hz, got \(hz)")
}
@Test func upTwoVoiceRaisesPitchTwoOctaves() throws {
// +2 oct voice alone (ratio 4.0, single stage at the clamp edge): 220 Hz → ~880 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.upTwo = 1.0
}
// Search a band around +2 oct so the autocorrelation can't lock onto the 441 Hz subharmonic
// lag (an 880 Hz tone is also periodic at 440 Hz, a near-tie in the correlation).
let hz: Double = fundamentalHz(out, minHz: 500.0)
#expect(hasNonSilentOutput(out), "+2 oct render was silent")
#expect(abs(hz - sineHz * 4.0) < sineHz * 4.0 * 0.15, "+2 oct should be ~880 Hz, got \(hz)")
}
@Test func subTwoVoiceLowersPitchTwoOctaves() throws {
// −2 oct voice alone (ratio 0.25, single stage at the clamp edge): 220 Hz → ~55 Hz.
// Cap the search near the expected low fundamental so deep-shift grain HF can't win.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.subTwo = 1.0
}
let hz: Double = fundamentalHz(out, maxHz: 160.0)
#expect(hasNonSilentOutput(out), "−2 oct render was silent")
#expect(abs(hz - sineHz * 0.25) < sineHz * 0.25 * 0.15, "−2 oct should be ~55 Hz, got \(hz)")
}
@Test func dryVoicePassesAtUnison() throws {
// Dry voice alone (no octaves): output stays at the input pitch.
let out: [Float] = try renderSine { pedal in
pedal.dry = 1.0
pedal.upOne = 0.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "dry-only render was silent")
#expect(abs(hz - sineHz) < sineHz * 0.2, "dry should stay ~220 Hz, got \(hz)")
}
// MARK: - Swell
@Test func swellIsNeutralAtZeroAttackAndBloomsAtHighAttack() throws {
// Isolate the +1 oct voice (dry muted). The sine starts from silence at engine start, so the
// swell's slow-gear gain shapes the voice's onset: at attack 0 the voice is present from the
// first cycles (early RMS ≈ late RMS); at attack 1 it blooms in over ~1.5 s (early RMS well
// below late RMS). Compare the early/late RMS ratio between the two settings.
let duration: Double = 2.0
let warmupFrames: Int = Int(0.15 * sampleRate) // past the shifter warm-up
let earlyLo: Int = warmupFrames
let earlyHi: Int = warmupFrames + Int(0.2 * sampleRate) // ~0.15–0.35 s
let lateLo: Int = Int(1.5 * sampleRate)
let lateHi: Int = Int(1.9 * sampleRate)
let instant: [Float] = try renderSine(duration: duration) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 0.0
}
let swelled: [Float] = try renderSine(duration: duration) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 1.0
}
let instantRatio: Double =
rms(instant, loFrame: earlyLo, hiFrame: earlyHi)
/ max(rms(instant, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
let swelledRatio: Double =
rms(swelled, loFrame: earlyLo, hiFrame: earlyHi)
/ max(rms(swelled, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
#expect(hasNonSilentOutput(swelled), "swelled render was silent")
// Instant: roughly flat onset (early ≈ late).
#expect(instantRatio > 0.6, "attack 0 should have a near-flat onset, early/late ratio \(instantRatio)")
// Swell: the early window is markedly quieter than steady state, and quieter than the
// instant setting's early window.
#expect(swelledRatio < instantRatio * 0.6,
"attack 1 should bloom in (swelled early/late \(swelledRatio) vs instant \(instantRatio))")
}
@Test func renderIsDeterministic() throws {
// Every PitchShift voice is seeded and the sine source is RNG-free, so two identical renders
// must be bit-identical.
let a: [Float] = try renderSine { pedal in
pedal.subTwo = 0.3
pedal.upOne = 0.7
pedal.upTwo = 0.4
}
let b: [Float] = try renderSine { pedal in
pedal.subTwo = 0.3
pedal.upOne = 0.7
pedal.upTwo = 0.4
}
#expect(a == b, "seeded renders of the same setting should be bit-identical")
}
// MARK: - Bypass transition
/// Renders the pedal manually block-by-block through a no-op `OfflineDriver`, flipping `bypass`
/// from engaged (`0`) to bypassed (`1`) at `flipFrame`, and returns the left hardware-output
/// channel. Hand-stepping `processBlock` is the only way to change a live `@UIParam` mid-render.
private func renderBypassFlip(
flipFrame: Int,
totalFrames: Int,
blockSize: Int,
configure: (PolyOctavePedal) -> Void
) 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: sineHz)
let pedal: PolyOctavePedal = PolyOctavePedal(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()
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 // engage → bypassed, mid-render
flipped = true
}
engine.processBlock(inputSamples: noInput)
let bus: [Float] = engine.audioBuses[0] // hardware output, left
left.append(contentsOf: bus)
frame += blockSize
}
engine.stop()
return left
}
@Test func bypassSwitchIsClickFree() throws {
// Clocking a wet-only octave-up voice (dry muted, +1 oct at full) on/off crossfades the dry
// note against a fully decorrelated shifted voice. The audio-rate linear equal-power bypass
// crossfade must keep that click-free at the engine's real 512-sample block — a block-rate
// smoother would leak a coarse step here.
let blockSize: Int = 512
let totalFrames: Int = 26_460 // 0.6 s
let flipFrame: Int = 15_435 // ~0.35 s
let left: [Float] = try renderBypassFlip(
flipFrame: flipFrame,
totalFrames: totalFrames,
blockSize: blockSize
) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 0.0 // no swell, so the voice is full-scale at the seam
}
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyLo: Int = 9_700 // ~0.22 s
let steadyHi: Int = 14_500 // ~0.33 s
let fadeFrames: Int = Int(0.03 * sampleRate)
let transLo: Int = flipFrame - blockSize
let transHi: Int = flipFrame + fadeFrames + 2_000
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
let transStep: Double = maxStep(left, lo: transLo, hi: transHi)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Build / wiring
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try renderSine { pedal in
pedal.dry = 1.0
pedal.upOne = 0.5
}
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "poly-octave output was silent")
}
@Test func exposesSevenVoiceKnobs() throws {
let pedal: PolyOctavePedal = PolyOctavePedal()
#expect(pedal.effectKnobs.map { $0.label }
== ["-2 Oct", "-1 Oct", "+1 Oct", "+2 Oct", "Dry", "Attack", "Tone"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: PolyOctavePedal = PolyOctavePedal()
pedal.subTwo = 0.2
pedal.subOne = 0.3
pedal.upOne = 0.4
pedal.upTwo = 0.5
pedal.dry = 0.6
pedal.attack = 0.7
pedal.tone = 6000.0
let state: PedalState = pedal.captureState()
let restored: PolyOctavePedal = PolyOctavePedal()
restored.applyState(state)
#expect(restored.subTwo == 0.2)
#expect(restored.subOne == 0.3)
#expect(restored.upOne == 0.4)
#expect(restored.upTwo == 0.5)
#expect(restored.dry == 0.6)
#expect(restored.attack == 0.7)
#expect(restored.tone == 6000.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Poly Octave")
#expect(pedal is PolyOctavePedal)
}
}
@@ -0,0 +1,338 @@
// ReverseReverbPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine source (for non-silent / bypass checks).
@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))
}
}
/// A decaying sine burst: full at the start, linearly fading to silence over `burstDur`, then
/// silent. Its amplitude envelope peaks at `t = 0`, so after the reverse delay the swell appears
/// *later* — the signature a forward effect would not show.
@MainActor
private final class TestBurstSource: 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 envelope: Line.Control = Line.Control(start: 1.0, end: 0.0, dur: burstDur)
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp) * envelope)
}
}
@MainActor
@Suite("ReverseReverbPedal")
struct ReverseReverbPedalTests {
private let sampleRate: Double = 44_100.0
private let sineHz: Double = 220.0
// MARK: - Render helpers
/// Renders a source through the pedal to a stereo CAF, returning interleaved samples.
private func render(
duration: Double,
makeSource: @escaping (Int) -> any Synthesizer,
configure: (ReverseReverbPedal) -> 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: any Synthesizer = makeSource(srcBus.index)
let pedal: ReverseReverbPedal = ReverseReverbPedal(
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()
}
/// Max absolute first difference (per-sample step) over `[lo, hi)`.
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
}
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try render(
duration: 0.8,
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
configure: { _ in }
)
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "reverse-reverb output was silent")
}
@Test func reverseSwellDelaysEnergyPastOneSegment() throws {
// A burst peaking at t=0, rendered fully wet. The reverse delay plays nothing until its first
// segment completes (~`time` seconds), then releases the burst reversed — so the wet energy
// lands AFTER one segment, not at the input's early peak. A forward reverb would put its
// loudest energy during the burst instead. Assert the mid window dominates the early window.
let segmentTime: Double = 0.4
let out: [Float] = try render(
duration: 1.2,
makeSource: { bus in
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
},
configure: { pedal in
pedal.mix = 1.0 // isolate the wet path (no dry passthrough)
pedal.time = segmentTime
pedal.decay = 2.0
}
)
#expect(hasNonSilentOutput(out), "reverse-reverb burst render was silent")
// Early: during/just after the input burst, before the first reversed segment plays.
let earlyRMS: Double = rms(out, loFrame: 0, hiFrame: Int(0.3 * sampleRate))
// Mid: the reversed swell has been released and reverberates.
let midRMS: Double = rms(out, loFrame: Int(0.42 * sampleRate), hiFrame: Int(0.8 * sampleRate))
// The reversed signal is genuinely silent before one segment, so earlyRMS ≈ 0; assert the mid
// window is both non-trivially loud and far above the early window (a forward reverb would put
// its energy in the early window and fail this).
#expect(midRMS > 1.0e-3, "reversed swell should be clearly audible in the mid window, got \(midRMS)")
#expect(midRMS > earlyRMS * 3.0,
"reversed energy should arrive after one segment (mid RMS \(midRMS) vs early \(earlyRMS))")
}
@Test func energyRisesAcrossTheReversedSegment() throws {
// The reverse signature: a burst decaying from t=0 is recorded over segment [0, time) and
// played back end-to-start over [time, 2·time). The recorded END (late, silent) plays first
// and the recorded START (t=0, loudest) plays last, so within the reversed playback the
// energy RISES toward the segment's end. A plain delay→reverb would not — it would preserve
// the burst's decaying shape. Assert the late-segment window is louder than the mid-segment
// window. mix=1.0 isolates the wet path.
let segmentTime: Double = 0.4
let out: [Float] = try render(
duration: 1.2,
makeSource: { bus in
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
},
configure: { pedal in
pedal.mix = 1.0
pedal.time = segmentTime
pedal.decay = 1.5 // modest tail so the rising dry swell dominates the window
}
)
// Reversed playback spans [0.4, 0.8) s. Early-in-playback (reads the silent recorded tail)
// vs late-in-playback (reads the loud recorded onset).
let midSegRMS: Double = rms(out, loFrame: Int(0.48 * sampleRate), hiFrame: Int(0.60 * sampleRate))
let lateSegRMS: Double = rms(out, loFrame: Int(0.68 * sampleRate), hiFrame: Int(0.80 * sampleRate))
#expect(lateSegRMS > midSegRMS * 1.5,
"energy should rise into the segment end (late \(lateSegRMS) vs mid \(midSegRMS))")
}
@Test func reverbTailPersistsAfterInput() throws {
// After the burst and its reversed playback, the GVerb tail should still ring.
let out: [Float] = try render(
duration: 1.4,
makeSource: { bus in
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
},
configure: { pedal in
pedal.mix = 1.0
pedal.time = 0.4
pedal.decay = 6.0 // long tail so late energy is unambiguous
}
)
let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate))
#expect(lateRMS > 1.0e-4, "reverb tail should still ring late in the render, got \(lateRMS)")
}
@Test func renderIsDeterministic() throws {
// ReverseDelay and GVerb are RNG-free, so two identical renders must be bit-identical.
let make: () throws -> [Float] = {
try self.render(
duration: 0.8,
makeSource: { bus in
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
},
configure: { pedal in
pedal.time = 0.3
pedal.decay = 2.0
}
)
}
let a: [Float] = try make()
let b: [Float] = try make()
#expect(a == b, "reverse-reverb renders of the same setting should be bit-identical")
}
// MARK: - Bypass transition
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: sineHz)
let pedal: ReverseReverbPedal = ReverseReverbPedal(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 {
// The audio-rate equal-power bypass crossfade must stay click-free at the engine's real
// 512-sample block.
let blockSize: Int = 512
let totalFrames: Int = 26_460 // 0.6 s
let flipFrame: Int = 15_435 // ~0.35 s
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 exposesFourKnobs() throws {
let pedal: ReverseReverbPedal = ReverseReverbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Decay", "Size", "Damp"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: ReverseReverbPedal = ReverseReverbPedal()
pedal.time = 0.8
pedal.decay = 5.0
pedal.size = 50.0
pedal.damp = 0.3
let state: PedalState = pedal.captureState()
let restored: ReverseReverbPedal = ReverseReverbPedal()
restored.applyState(state)
#expect(restored.time == 0.8)
#expect(restored.decay == 5.0)
#expect(restored.size == 50.0)
#expect(restored.damp == 0.3)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Reverb")
#expect(pedal is ReverseReverbPedal)
}
}
@@ -0,0 +1,232 @@
// ScriptPhaserPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine source — a stable tone the phaser's sweeping notches act on.
@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("ScriptPhaserPedal")
struct ScriptPhaserPedalTests {
private let sampleRate: Double = 44_100.0
private let sineHz: Double = 220.0
/// Minimum RMS difference between two renders to count as a substantial, audible change.
private let renderDiffEpsilon: Double = 1.0e-3
// MARK: - Render
private func render(
duration: Double,
configure: (ScriptPhaserPedal) -> 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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: ScriptPhaserPedal = ScriptPhaserPedal(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)
}
/// RMS of the sample-by-sample difference between two renders' left channels — a magnitude of how
/// much two settings actually diverge, not just whether any bit differs.
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
}
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try render(duration: 0.8) { _ in }
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "script-phaser output was silent")
}
@Test func voicingChangesCharacter() throws {
// Script (feedback 0.2) and Block (0.45) are different notch depths, so the rendered output
// must differ between them.
let script: [Float] = try render(duration: 1.0) { pedal in
pedal.mix = 1.0; pedal.speed = 0.8; pedal.voicing = 0.0
}
let block: [Float] = try render(duration: 1.0) { pedal in
pedal.mix = 1.0; pedal.speed = 0.8; pedal.voicing = 1.0
}
#expect(hasNonSilentOutput(script) && hasNonSilentOutput(block), "a voicing render was silent")
#expect(rmsDiff(script, block) > renderDiffEpsilon,
"Script and Block voicings should differ substantially, diff \(rmsDiff(script, block))")
}
@Test func speedChangesModulation() throws {
// A faster LFO sweeps the notches more often, so a slow and a fast render must differ.
let slow: [Float] = try render(duration: 1.0) { pedal in
pedal.mix = 1.0; pedal.speed = 0.2
}
let fast: [Float] = try render(duration: 1.0) { pedal in
pedal.mix = 1.0; pedal.speed = 3.0
}
#expect(hasNonSilentOutput(slow) && hasNonSilentOutput(fast), "a speed render was silent")
#expect(rmsDiff(slow, fast) > renderDiffEpsilon,
"slow and fast sweeps should differ substantially, diff \(rmsDiff(slow, fast))")
}
@Test func renderIsDeterministic() throws {
// The phaser LFO is a deterministic sine (no RNG), so two identical renders are bit-identical.
let a: [Float] = try render(duration: 0.8) { pedal in pedal.speed = 1.0; pedal.voicing = 1.0 }
let b: [Float] = try render(duration: 0.8) { pedal in pedal.speed = 1.0; pedal.voicing = 1.0 }
#expect(a == b, "deterministic script-phaser renders of the same setting should be bit-identical")
}
// 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: sineHz)
let pedal: ScriptPhaserPedal = ScriptPhaserPedal(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 exposesSpeedKnobAndVoicingSwitch() throws {
let pedal: ScriptPhaserPedal = ScriptPhaserPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Speed"])
let switches: [PedalSwitch] = pedal.effectSwitches
#expect(switches.map { $0.label } == ["Voicing"])
#expect(switches.first?.options.map { $0.title } == ["Script", "Block"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: ScriptPhaserPedal = ScriptPhaserPedal()
pedal.speed = 1.7
pedal.voicing = 1.0
let state: PedalState = pedal.captureState()
let restored: ScriptPhaserPedal = ScriptPhaserPedal()
restored.applyState(state)
#expect(restored.speed == 1.7)
#expect(restored.voicing == 1.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Script Phaser")
#expect(pedal is ScriptPhaserPedal)
}
}