Add Reverse Delay pedal and ReverseDelay generator

New RT-safe ReverseDelay generator (ShoeGaze): double-buffered segmented
recorder that plays each segment back reversed, ping-ponging record/play
buffers at each boundary with a linear edge-fade to de-click the wrap and
optional feedback for layered reverse trails. Buffers pre-allocated for
maxDelay; delay/feedback read at control rate; segment length changes only
at a boundary.

ReverseDelayPedal wraps it (Time/Feedback), registered with enclosure
color + palette slot. Tests: build/non-silent, feedback-changes-output,
knobs, preset round-trip, registry. Suite 237.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-27 21:28:45 -07:00
parent 5af4230038
commit a334a76f7c
8 changed files with 409 additions and 1 deletions
@@ -0,0 +1,204 @@
// ReverseDelay.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream input
/// yields no channel for a `_computeSamples` call, so the RT path never allocates.
private let reverseDelayZeroBlock: [Double] = makeSampleBuffer()
/// Segmented reverse delay: records the input in fixed-length segments and plays each segment back
/// **reversed**, so phrases come out backwards.
///
/// Two segment buffers ping-pong: one records the incoming signal while the other is read back from
/// its end to its start. At each segment boundary the buffers swap. A short raised-edge (linear)
/// fade at both ends of every reversed segment hides the wrap discontinuity, and an optional
/// feedback term recirculates the reversed output into the record buffer for layered reverse trails.
///
/// `delay` and `feedback` are read at **control rate** (once per block via `floatValue`); a changed
/// `delay` takes effect at the next segment boundary, so the segment length never changes mid-read.
/// Output is mono (channel 0 of the input is processed).
///
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds — the RT path never
/// allocates or resizes. Keep `delay <= maxDelay`; larger values are clamped.
public final class ReverseDelay: GeneratorBase, AudioGenerator {
// MARK: - Inputs (classified once at init)
/// Resolved input signal.
let _input: any ValidGeneratorInput
/// `true` when `_input` resolved to a generator; `false` for a scalar constant. Classified once
/// so the RT path never runs an `is`/`as?` check.
let _inputIsGenerator: Bool
/// Resolved control inputs. Read at block rate via `floatValue` — pass control-rate nodes
/// (`@UIParam` projections) or scalars, not audio-rate generators.
let _delay: any ValidGeneratorInput
let _feedback: any ValidGeneratorInput
// MARK: - Buffers + state
/// The two ping-pong segment buffers, each `_maxFrames` long. One records while the other plays.
private var _bufferA: [Double]
private var _bufferB: [Double]
/// Maximum segment length in frames (`maxDelay · sampleRate`).
private let _maxFrames: Int
/// `true` when buffer A is the record buffer (B plays); toggled at each segment boundary.
var _recordIsA: Bool = true
/// Read/write position within the current segment, `0 ..< _segLen`.
var _phase: Int = 0
/// Current segment length in frames.
var _segLen: Int
/// `false` until the first render block adopts the live `delay` as the segment length (the node
/// value isn't available at `init`).
var _segLenInitialized: Bool = false
/// Edge-fade length in frames, clamped to half the segment per call.
private let _fadeFrames: Int
// MARK: - Constants
/// Largest stable feedback factor.
private let maxFeedback: Double = 0.95
// MARK: - Init
/// Creates a reverse delay.
///
/// - Parameters:
/// - input: Signal to reverse.
/// - maxDelay: Maximum segment length in seconds. Sizes the pre-allocated buffers.
/// - delay: Segment length in seconds (control rate). Clamped to `[1 frame, maxDelay]`; a
/// change applies at the next segment boundary.
/// - feedback: Reverse-trail feedback factor (control rate). Clamped to `[0, 0.95]`. Defaults
/// to `0`.
/// - sampleRate: Sample rate used to size the buffers and convert seconds → frames.
/// - fadeTime: Edge-fade length in seconds, hiding the segment wrap. Defaults to `0.004`.
public init(
input: any ValidGeneratorInput,
maxDelay: Double,
delay: any ValidGeneratorInput,
feedback: any ValidGeneratorInput = 0.0,
sampleRate: Double,
fadeTime: Double = 0.004
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_delay = delay._resolvedInput()
_feedback = feedback._resolvedInput()
let frames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
_maxFrames = frames
_bufferA = [Double](repeating: 0.0, count: frames)
_bufferB = [Double](repeating: 0.0, count: frames)
_segLen = frames
_fadeFrames = max(0, Int((fadeTime * sampleRate).rounded()))
super.init()
}
// MARK: - Render
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate
let delaySeconds: Double = _delay.floatValue(graph: graph)
let rawFeedback: Double = _feedback.floatValue(graph: graph)
let feedback: Double = min(max(rawFeedback, 0.0), maxFeedback)
// Target segment length, applied at the next boundary so a read never changes length mid-segment.
let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames)
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? reverseDelayZeroBlock)
: reverseDelayZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var phase: Int = _phase
var segLen: Int = _segLen
var recordIsA: Bool = _recordIsA
let fadeFrames: Int = _fadeFrames
// Adopt the live delay length on the first block — at `init` the node value isn't known, so
// the segment must not start at the full buffer length (that would delay the first reversed
// segment by `maxDelay`).
if !_segLenInitialized {
segLen = targetLen
phase = 0
_segLenInitialized = true
}
_bufferA.withUnsafeMutableBufferPointer { aBuffer in
_bufferB.withUnsafeMutableBufferPointer { bBuffer in
guard let aPointer: UnsafeMutablePointer<Double> = aBuffer.baseAddress,
let bPointer: UnsafeMutablePointer<Double> = bBuffer.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { outBuffer in
guard let outPointer: UnsafeMutablePointer<Double> = outBuffer.baseAddress else { return }
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
let recordPointer: UnsafeMutablePointer<Double> = recordIsA ? aPointer : bPointer
let playPointer: UnsafeMutablePointer<Double> = recordIsA ? bPointer : aPointer
// Reversed read: end of the play segment first.
let readIndex: Int = segLen - 1 - phase
let raw: Double = playPointer[readIndex]
let envelope: Double = ReverseDelay.edgeFade(
phase: phase, segLen: segLen, fadeFrames: fadeFrames
)
let out: Double = raw * envelope
recordPointer[phase] = x + feedback * out
outPointer[i] = out
phase += 1
if phase >= segLen {
phase = 0
recordIsA.toggle()
segLen = targetLen
}
}
}
}
}
_phase = phase
_segLen = segLen
_recordIsA = recordIsA
return _result
}
/// Linear raised-edge fade in `[0, 1]`: ramps up over the first `fadeFrames` of a segment and
/// down over the last `fadeFrames`, flat `1` in the middle. De-clicks the reverse wrap.
private static func edgeFade(
phase: Int,
segLen: Int,
fadeFrames: Int
) -> Double {
let fade: Int = min(fadeFrames, segLen / 2)
guard fade > 0 else { return 1.0 }
let fromStart: Int = phase
let fromEnd: Int = segLen - 1 - phase
let nearestEdge: Int = min(fromStart, fromEnd)
guard nearestEdge < fade else { return 1.0 }
return Double(nearestEdge) / Double(fade)
}
}
+1
View File
@@ -75,6 +75,7 @@ public extension PedalType {
static let feedbackDelay = PedalType("Feedback Delay")
static let multiTapDelay = PedalType("Multi-Tap Delay")
static let pingPong = PedalType("Ping-Pong")
static let reverseDelay = PedalType("Reverse Delay")
static let reverb = PedalType("Reverb")
// Pitch & octave
@@ -0,0 +1,87 @@
// ReverseDelayPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Reverse delay.
///
/// Records the input in fixed-length segments and plays each one back reversed, so notes and
/// phrases swell in backwards — the classic backwards-tape effect. `Feedback` recirculates the
/// reversed output for layered backward trails. Wraps the ``ReverseDelay`` generator, run fully wet
/// so the pedal's `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
public final class ReverseDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Plays your phrases back in reverse — the backwards-tape swell, with feedback trails."
}
// MARK: - Parameters
/// Reverse segment length in seconds. Range [0.05, 2.0].
@UIParam public var time: Double = 0.5
/// Reverse-trail feedback. Range [0, 0.95].
@UIParam public var feedback: Double = 0.3
// MARK: - Constants
/// Default wet/dry blend — reverse delay sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Maximum segment length the buffers are allocated for, in seconds.
private let maxDelayTime: Double = 2.0
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
// MARK: - Init
/// Creates a reverse-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: "Reverse Delay",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ReverseDelayPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
ReverseDelay(
input: dry,
maxDelay: maxDelayTime,
delay: $time,
feedback: $feedback,
sampleRate: sampleRate
)
}
}
@@ -48,6 +48,7 @@ public enum PedalRegistry {
"Bass Octaver": { BassOctaverPedal() },
"Harmonizer": { HarmonizerPedal() },
"Ping-Pong": { PingPongDelayPedal() },
"Reverse Delay": { ReverseDelayPedal() },
"Limiter": { LimiterPedal() },
"Noise Gate": { NoiseGatePedal() },
"Graphic EQ": { GraphicEQPedal() },
@@ -55,7 +55,7 @@ public struct PedalPaletteView: View {
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
"Harmonizer",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
]
/// Routing/branching topologies the user can insert into the board.
@@ -29,6 +29,7 @@ private func enclosureColor(for displayName: String) -> Color {
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia
case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan
case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
@@ -0,0 +1,94 @@
// ReverseDelayPedalTests.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("ReverseDelayPedal")
struct ReverseDelayPedalTests {
private func render(
configure: (ReverseDelayPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.6
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
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: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ReverseDelayPedal = ReverseDelayPedal(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)
}
/// Sum of squared differences over the full overlapping length. Feedback only diverges once a
/// fed-back segment is replayed (the third segment), so a narrow window can miss it; comparing
/// the whole readable buffer (the reader returns the first 4096 frames) is robust.
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
// Short segment so reversed playback begins within the reader's 4096-frame window.
let samples: [Float] = try render { pedal in pedal.time = 0.03; pedal.mix = 1.0 }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "reverse delay output was silent")
}
@Test func feedbackChangesOutput() throws {
let dry: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.0; pedal.mix = 1.0 }
let trails: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.6; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(trails), "feedback reverse delay was silent")
#expect(totalSSD(dry, trails) > 0, "changing feedback did not change the output")
}
@Test func exposesTimeFeedbackKnobs() throws {
let pedal: ReverseDelayPedal = ReverseDelayPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Time", "Feedback"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: ReverseDelayPedal = ReverseDelayPedal()
pedal.time = 1.2
pedal.feedback = 0.7
let state: PedalState = pedal.captureState()
let restored: ReverseDelayPedal = ReverseDelayPedal()
restored.applyState(state)
#expect(restored.time == 1.2)
#expect(restored.feedback == 0.7)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Delay")
#expect(pedal is ReverseDelayPedal)
}
}
+20
View File
@@ -160,6 +160,26 @@ Per `CLAUDE.md` "Adding a new pedal":
switches/sliders.
8. Use `PedalType` static members at call sites.
## Shimmer scope (true regenerative) — findings
Investigated the regenerative path. The per-pedal graph is acyclic; the only feedback mechanisms in
Lyrebird are (a) generators that close their own loop internally (`DelayLineFeedback`, the reverbs)
and (b) cross-block bus read/write. Pedals use inherited `input(bus:)` / `output(bus:)` In/Out
nodes, but **no pedal allocates an internal scratch/feedback bus** — there's no precedent or
lifecycle hook for that. A bus-feedback shimmer would mean new pedal infrastructure (allocate +
release an internal feedback bus, ordered Out→In with a one-block delay) — fragile and off-pattern.
**Conclusion:** true regenerative shimmer is best built as a **new closed-loop generator**
(`ShimmerReverb`) that holds a reverb + an in-loop pitch-shift + damped feedback internally, the same
way `DelayLineFeedback` contains its own feedback. That's a substantial RT-safe DSP generator
(pre-allocated buffers, denormal guards, feedback clamp for stability, granular/FFT pitch latency in
the loop) — larger than Reverse Delay or Bitcrush, and needing its own stability tuning + RT review.
**Recommendation:** build Reverse Delay and Bitcrusher first (self-contained), then take
`ShimmerReverb` as its own focused task. If it proves too large for the 1.2 window, ship the
parallel-pitch-into-reverb approximation for 1.2 and schedule the regenerative generator for 1.3.
**Decision pending:** regenerative `ShimmerReverb` now, or parallel approximation for 1.2 + defer.
## Decisions (resolved)
- **Harmonizer picker:** new `PedalSelectorKnob` (stepped knob) with the ±3rd interval set above.