Files
ShoeGaze/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift
T
josh 947dfe427a Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal:

- Beat-quantized transport: record start and loop close both snap to the
  next beat via a LyrebirdRoutine waiting on the shared clock; loop length
  is an exact whole-beat span. Falls back to immediate/unquantized when no
  clock is present.
- Loop-length read-outs (frames/seconds/beats), transport state, and a
  sample-clock-derived play-head position for the UI timeline.
- Overdub undo (pre-dub snapshot + restore), reverse playback (live rate
  flip), and feedback-decay overdub (overdub preLevel via a Feedback knob).
- Inject the shared LyrebirdClock + SynthesisEngine into Pedal via
  PedalBoard/ChainRouter so tempo-aware pedals can reach them.
- New double-width LooperTimelineView (state badge, length read-out,
  sweeping play-head) wired into PedalView via Pedal.widthUnits.

Concurrency hardening from RT-safety review: a transportGeneration counter
drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop()
cannot recall once enqueued; the undo restore is deferred past the RT
overdub gate-close; transport routines use non-blocking stop().

Note: this commit also snapshots pre-existing uncommitted work-in-progress
already in the tree (MIDI control refactor, Tuner, Tempo, preset changes),
which is interleaved with the looper changes through shared files and could
not be split into a separately-building commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:22:20 -07:00

513 lines
23 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LooperPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A loop-recorder pedal: record a take into a buffer, then play it back looping, with
/// overdub, overdub-undo, reverse playback, feedback-decay overdub, and a crossfaded
/// total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the transport is
/// beat-quantized — record start and loop close both snap to the next beat, so every loop
/// is a whole number of beats long.
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → RecordBuffer.Audio (primary take, passthrough while recording) ─┐
/// dry → RecordBuffer.Audio (overdub, gated by overdubOn × isPlaying, │ (write only)
/// old content scaled by feedback) │
/// loopBuffer → PlayBuffer.Audio (loop, cubic, rate ±1) │
/// primary passthrough ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─┴→ wet
/// ```
///
/// A single fixed generator graph is built once (Lyrebird's node tree does not support
/// rebuilding a synth's internal generators). Every transport action is expressed as a
/// live parameter change the graph already reads every block (`$overdubOn`, `$loopOn`,
/// `$isPlaying`, `$reverse`, `$feedback`, `$playTrigger`), plus, for actions with a genuine
/// non-RT side effect (clearing the buffer, narrowing/restoring `loopLength`, snapshotting
/// for undo), an explicit method.
///
/// ## Transport (beat-quantized when a clock is present)
/// - ``toggleRecordStop()``: `.empty` → arm/begin recording; `.recording` → close the loop
/// and start looping. No-op while `.playing` — use ``resetLoop()`` for a new take.
/// - `overdubOn` (via ``toggleOverdub()``): layers new input onto the loop; engaging it first
/// snapshots the loop so ``undoOverdub()`` can revert the pass.
/// - `loopOn` (switch): crossfaded total mute without stopping the player.
/// - `reverse` (switch): flips playback direction (`rate` 1 → −1) without a rebuild.
/// - ``undoOverdub()``: restores the loop to the snapshot taken when overdub was last engaged.
/// - ``resetLoop()``: clears the buffer and returns to `.empty`.
///
/// ## Knobs
/// - `crossfadeTime`: Fade time constant, in seconds, for `loopOn` and the record→play handoff.
/// - `playbackLevel`: Loop playback gain, in dB.
/// - `overdubLevel`: Overdub input gain, in dB.
/// - `feedback`: Retained level of existing loop content on each overdub pass, `[0, 1]`.
/// `1.0` (default) keeps old layers forever; lower values fade them for a decaying dub.
public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Records a loop, then plays it back with overdub, reverse, and a crossfaded mute."
}
/// Double-width card: the looper carries a full transport plus a loop timeline and reads
/// more comfortably in a wider enclosure.
public override var widthUnits: Int { 2 }
// MARK: - Knobs
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
/// A `Lag.Control` 60 dB settling time, not a fixed-length linear ramp.
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
/// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0
/// Overdub input gain, in dB. Scales only the new material being layered in — the
/// existing loop content is never attenuated by this knob.
@UIParam public var overdubLevel: Double = 0.0
/// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0`
/// keeps prior layers indefinitely; lower values fade them a little on every pass for a
/// decaying "sound-on-sound" feedback loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Overdub gate. `0` = off, `1` = on. Live-gated — has no effect before a loop exists.
@UIParam public var overdubOn: Double = 0.0
/// Total loop mute. `0` = muted (silent), `1` = audible. Transitions are smoothed by
/// `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read by the player's `rate` input
/// as `1 − 2·reverse`, so toggling flips the loop without rebuilding the graph.
@UIParam public var reverse: Double = 0.0
// MARK: - Internal live state
/// `1` once a take has been recorded and looping playback has started, else `0`.
/// Read by the audio graph (gates overdub and the loop crossfade) — not a user knob.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close so playback
/// starts phase-aligned to frame 0 (the anchor for the timeline read-out); rearmed to `0`
/// on ``resetLoop()``. Read by the player's `trigger` input. Not a user knob.
@UIParam public var playTrigger: Double = 0.0
// MARK: - Constants
/// Maximum recordable take length, in seconds.
private static let maxDurationSeconds: Double = 60.0
/// Default crossfade duration, in seconds.
private static let defaultCrossfadeTime: Double = 0.05
/// Bipolar span mapping `reverse ∈ {0, 1}` to a playback rate of `{+1, −1}`.
private static let reverseRateSpan: Double = 2.0
/// Forward playback rate, and the rate offset the reverse span is subtracted from.
private static let forwardRate: Double = 1.0
/// Smallest permitted loop length, in frames, so a degenerate zero-length take can't
/// produce a divide-by-zero in the player or the timeline read-out.
private static let minimumLoopFrames: Int = 1
/// Frames to wait after disabling overdub before restoring an undo snapshot, so the
/// RT-side overdub writer (its `run` gate ramps closed over one control block) has fully
/// stopped writing the loop buffer before the main thread overwrites it. Two maximum
/// blocks (`blockSize ≤ 512`) is a comfortable margin.
private static let undoGuardFrames: Int = 1024
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffer + generators
/// The loop buffer, sized to `maxDurationSeconds` at the engine sample rate. Allocated
/// in `effect(_:)` (called from `build()`), not `init`, because `sampleRate` is only set
/// by `PedalBoard.add(_:)` after construction but before the engine builds the graph.
private var loopBuffer: LyrebirdBuffer?
private var primaryRecorder: RecordBuffer.Audio?
private var overdubRecorder: RecordBuffer.Audio?
private var player: PlayBuffer.Audio?
// MARK: - Transport state
private enum Phase {
case empty
case armedRecord
case recording
case armedStop
case playing
}
private var phase: Phase = .empty
/// Beat-boundary sample time at which the current take started recording, and at which
/// the loop closes. Both are captured from the clock so the loop length is beat-exact.
private var recordStartSample: SampleTime = 0
/// Sample time playback began looping (play-head at frame 0) — the timeline anchor.
private var playStartSample: SampleTime = 0
/// Length of the closed loop in frames (`0` until a take is recorded).
private var loopFrames: Int = 0
/// Length of the closed loop in whole beats (`0` until a beat-quantized take is closed).
private var loopBeats: Double = 0.0
/// Snapshot of the loop taken when overdub was last engaged, for ``undoOverdub()``.
private var overdubUndoSnapshot: [Double]?
/// Background routine that waits for the next beat before applying a transport action.
/// Stopped (non-blocking) before starting a new one, and torn down on ``resetLoop()``.
private var transportRoutine: LyrebirdRoutine?
/// Background routine that defers an undo restore until the RT overdub gate has closed.
private var undoRoutine: LyrebirdRoutine?
/// Monotonic transport-action generation. Bumped on every arm and on ``resetLoop()``; a
/// deferred beat callback carries the generation it was armed under and is dropped if the
/// generation has since advanced — so a callback whose action was superseded (a new press,
/// a reset) can never apply to the wrong take. Guards the `DispatchQueue.main.async` hop,
/// which `LyrebirdRoutine.stop()` cannot itself cancel once enqueued.
/// (internal, not private, only so tests can assert the generation-drop of a stale callback.)
private(set) var transportGeneration: Int = 0
// MARK: - Init
/// Creates a looper pedal.
///
/// - Parameters:
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
/// - outputBus: Audio bus to write the output to. Defaults to `0`; set by the board.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / switches / buttons
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Crossfade", node: $crossfadeTime, range: crossfadeTimeRange),
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
PedalKnob(label: "Overdub", node: $overdubLevel, range: levelRangeDb),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
public override var effectButtons: [PedalButton] {
[
PedalButton(label: "Record / Stop") { [weak self] in self?.toggleRecordStop() },
PedalButton(label: "Overdub") { [weak self] in self?.toggleOverdub() },
PedalButton(label: "Undo") { [weak self] in self?.undoOverdub() },
PedalButton(label: "Loop", node: $loopOn),
PedalButton(label: "Reverse", node: $reverse),
PedalButton(label: "Reset") { [weak self] in self?.resetLoop() },
]
}
// MARK: - UI read-outs
/// Publicly-observable transport phase for the UI (LED colour, armed animation, timeline).
public var transportState: LooperTransportState {
switch phase {
case .empty: return .empty
case .armedRecord: return .armedRecord
case .recording: return .recording
case .armedStop: return .armedStop
case .playing: return .playing
}
}
/// Closed-loop length in frames (`0` until a take is recorded).
public var loopFrameCount: Int { loopFrames }
/// Closed-loop length in seconds (`0` until a take is recorded).
public var loopLengthSeconds: Double { Double(loopFrames) / sampleRate }
/// Closed-loop length in whole beats (`0` unless the take was beat-quantized).
public var loopLengthBeats: Double { loopBeats }
/// Normalised play-head position in `[0, 1)` while `.playing`, else `nil`.
///
/// Derived from the engine sample clock and the frame-0 playback anchor, so it tracks the
/// audio play-head regardless of tempo. The player's play-head is reset by a `playTrigger`
/// edge consumed at the next block boundary, so this read-out may lead the true audio
/// play-head by up to one block (≤ ~11 ms) — imperceptible for a UI sweep. Reverse playback
/// is reflected by mirroring the forward progress, matching the player's negated `rate`.
public func playbackPosition01() -> Double? {
guard phase == .playing, loopFrames > 0, let engine: SynthesisEngine = hostEngine else {
return nil
}
let elapsed: SampleTime = engine.currentTime - playStartSample
guard elapsed >= 0 else { return 0.0 }
let framesInto: Int = Int(elapsed % SampleTime(loopFrames))
let forward: Double = Double(framesInto) / Double(loopFrames)
return reverse >= 0.5 ? (1.0 - forward) : forward
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
loopBuffer = buffer
let primary: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: false,
doneAction: .nothing
)
primary.run = 0.0
primaryRecorder = primary
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: true,
doneAction: .nothing
)
// Live-gated: only writes while a loop exists and overdub is switched on. The existing
// loop content is scaled by `feedback` on each pass (1.0 = keep, < 1.0 = decay).
overdub.$run.source = $overdubOn * $isPlaying
overdub.$recLevel.source = DbAmp.Control($overdubLevel)
overdub.$preLevel.source = $feedback
overdubRecorder = overdub
// Playback rate: forward at +1, reverse at −1, switched live off `$reverse`.
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
player = loopPlayer
// Loop audible only while playing and not muted; smoothed to avoid clicks on either
// the record→play handoff or a loopOn toggle.
let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn
let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime)
let unityGain: Double = 1.0
let dryGate: any ValidGeneratorInput = unityGain - smoothedGate
return (primary * dryGate) + (loopPlayer * smoothedGate)
}
// MARK: - Transport
/// `.empty` → arms/begins recording. `.recording` → closes the loop and starts looping.
/// No-op while `.playing` or already armed.
public func toggleRecordStop() {
switch phase {
case .empty:
armRecording()
case .recording:
armStopAndPlay()
case .armedRecord, .armedStop, .playing:
break
}
}
/// Toggles the overdub gate. Engaging it (off → on) first snapshots the current loop so
/// ``undoOverdub()`` can revert the pass.
public func toggleOverdub() {
// Any overdub press supersedes a pending deferred action (e.g. an in-flight undo
// restore) — advance the generation so that stale callback is dropped, and stop the
// now-superseded undo routine so its background thread doesn't idle-poll to its target.
transportGeneration += 1
undoRoutine?.stop()
undoRoutine = nil
let engaging: Bool = overdubOn < 0.5
if engaging { captureOverdubSnapshot() }
overdubOn = engaging ? 1.0 : 0.0
}
/// Restores the loop to the snapshot captured when overdub was last engaged. No-op if no
/// snapshot exists. Disengages overdub, then restores the buffer only once the RT overdub
/// writer has actually stopped, so the main-thread bulk write can't race the RT thread's
/// lock-free writes into the same buffer.
public func undoOverdub() {
guard let buffer: LyrebirdBuffer = loopBuffer,
let snapshot: [Double] = overdubUndoSnapshot,
snapshot.count <= buffer.totalSampleCount else { return }
overdubOn = 0.0
// Advance the generation and capture it: a later reset / new take / overdub press bumps
// the generation and drops this restore, so it can never stomp a buffer the user has
// since cleared or re-recorded.
transportGeneration += 1
let generation: Int = transportGeneration
guard let engine: SynthesisEngine = hostEngine else {
// No engine (standalone / headless tests): single-threaded, restore immediately.
applyUndoRestore(snapshot, generation: generation)
return
}
// Overdub's `run` gate ramps to zero over one control block, so the recorder may write
// for up to a block more. Wait past that before overwriting the buffer.
undoRoutine?.stop()
let target: SampleTime = engine.currentTime + SampleTime(LooperPedal.undoGuardFrames)
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyUndoRestore(snapshot, generation: generation) }
}
undoRoutine = routine
routine.start(engine: engine)
}
/// Writes an undo snapshot back into the loop buffer, unless its generation has been
/// superseded by a reset, a new take, or a subsequent overdub/undo press.
func applyUndoRestore(_ snapshot: [Double], generation: Int) {
guard generation == transportGeneration,
let buffer: LyrebirdBuffer = loopBuffer,
snapshot.count <= buffer.totalSampleCount else { return }
buffer.setRangeValues(snapshot, startingAt: 0)
}
/// Clears the loop and returns to `.empty`, ready for a fresh take.
public func resetLoop() {
// Stop (non-blocking) any pending transport/undo routines and advance the generation
// so an already-enqueued beat callback is dropped rather than applied to the new take.
transportRoutine?.stop()
transportRoutine = nil
undoRoutine?.stop()
undoRoutine = nil
transportGeneration += 1
primaryRecorder?.run = 0.0
primaryRecorder?.requestReset()
overdubRecorder?.requestReset()
if let buffer: LyrebirdBuffer = loopBuffer {
buffer.clear()
buffer.setLoopLength(buffer.count)
}
isPlaying = 0.0
overdubOn = 0.0
loopOn = 1.0
playTrigger = 0.0
loopFrames = 0
loopBeats = 0.0
overdubUndoSnapshot = nil
phase = .empty
}
// MARK: - Transport helpers
/// Snapshots the closed-loop content into `overdubUndoSnapshot`. Called with overdub off,
/// so only the loop player reads the buffer concurrently (a lock-free read is safe).
private func captureOverdubSnapshot() {
guard let buffer: LyrebirdBuffer = loopBuffer, loopFrames > 0 else { return }
// Mono buffer: linear storage index == frame index. Called with overdub off (only the
// player reads concurrently), so a lock-free read of the storage is safe.
let frameCount: Int = min(loopFrames, buffer.totalSampleCount)
var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount)
for i: Int in 0 ..< frameCount {
snapshot[i] = buffer[i]
}
overdubUndoSnapshot = snapshot
}
/// A transport transition deferred to a beat boundary.
private enum QuantizedAction: Sendable {
case beginRecording
case finishStop
}
/// Begins recording immediately, or — with a clock — on the next beat boundary.
private func armRecording() {
phase = .armedRecord
runQuantized(.beginRecording)
}
/// Closes the loop immediately, or — with a clock — on the next beat boundary.
private func armStopAndPlay() {
phase = .armedStop
runQuantized(.finishStop)
}
/// Applies `action` on the main thread once the clock reaches the next beat, via a
/// background wait routine. With no clock/engine, applies it synchronously for
/// un-quantized transport (and headless tests).
private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1
let generation: Int = transportGeneration
guard let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else {
applyQuantizedTransport(action, generation: generation, at: nil)
return
}
transportRoutine?.stop()
let target: SampleTime = clock.nextBeat()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
// The wait runs on a background thread; all pedal state changes hop to main. The
// generation guard drops this callback if the action was superseded before it fires.
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
}
transportRoutine = routine
routine.start(engine: engine)
}
/// Runs the deferred transport transition (on the main thread), unless its generation has
/// been superseded by a newer arm or a reset.
private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
guard generation == transportGeneration else { return }
switch action {
case .beginRecording: beginRecording(at: beatSample)
case .finishStop: finishRecordingAndPlay(at: beatSample)
}
}
func beginRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
primaryRecorder?.run = 1.0
phase = .recording
}
func finishRecordingAndPlay(at beatSample: SampleTime?) {
guard phase == .armedStop,
let primary: RecordBuffer.Audio = primaryRecorder,
let buffer: LyrebirdBuffer = loopBuffer else { return }
primary.run = 0.0
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
if let clock: LyrebirdClock = clock, beatSample != nil {
// Beat-quantized: loop length is the exact whole-beat span between the two beat
// boundaries, independent of any recording-position snapshot slop.
let spanFrames: Int = Int(closeSample - recordStartSample)
loopFrames = max(LooperPedal.minimumLoopFrames, spanFrames)
loopBeats = beatsForSpan(frames: loopFrames, clock: clock)
} else {
// Un-quantized fallback: trim to the recorder's frame count.
loopFrames = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
loopBeats = 0.0
}
buffer.setLoopLength(loopFrames)
playStartSample = closeSample
playTrigger = 1.0
isPlaying = 1.0
phase = .playing
}
/// Whole-beat length of a `frames`-long span at the clock's *current* tempo. If the tempo
/// changed during the take, `loopFrames` (from raw sample deltas) stays correct while this
/// beat count — a UI read-out only, never audio — may misreport. Acceptable.
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
guard samplesPerBeat > 0 else { return 0.0 }
return (Double(frames) / samplesPerBeat).rounded()
}
}