Looper: multitrack redesign with smart Loop footswitch

Replace the one-at-a-time slot model with a synchronized multitrack looper:
four track players summed to one output, track A's first take defining the
master loop length, and tracks B–D recorded as phase-locked overdub layers
on the same grid (overdub recorders run continuously while playing, reset to
the top at play-start, gated per-track by recLevel so only the selected
track layers new input — instant, drift-free overdub toggles).

A single smart Loop footswitch drives the whole transport by state:
record A → set end (quantized) → auto-overdub on wrap → toggle overdub/play;
B–D toggle overdub aligned to A's play-head. Selecting a track ends the
prior overdub. Stop / Cue Stop pause; Loop resumes. Reset returns to clear.

UI: transport row is now Loop / Stop / Cue Stop / Reverse / Reset; the old
action row is replaced by a one-line state indicator; the A/B/C/D timeline
dots are tappable to select a track; every stomp button shows a live caption
of what its next press does (Record → Set End → Overdub → Play, etc.).

Overdub-undo dropped. All transport routines keep the transportGeneration
guard on deferred beat/stop callbacks.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 14:24:46 -07:00
parent 465e3e6dfd
commit 3007b76798
8 changed files with 637 additions and 907 deletions
+321 -403
View File
@@ -8,187 +8,144 @@ import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A multi-slot loop-recorder pedal: record independent loops into any of several slots, then
/// switch between them, 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.
/// A synchronized multitrack loop pedal. Track A's first take defines the master loop length;
/// tracks B–D are overdub layers recorded onto the same grid. All recorded tracks play at once,
/// summed to one output and locked in phase. When the board supplies a tempo ``LyrebirdClock``
/// the master take is beat-quantized so every loop is a whole number of beats long.
///
/// Signal chain (inside `effect(_:)`), per slot `i` plus one shared player:
/// ```
/// dry → RecordBuffer.Audio primary[i] (take capture, run-gated by transport) ─┐ (write only,
/// dry → RecordBuffer.Audio overdub[i] (gated by overdubOn × isPlaying × slot i) │ RootRegistering)
/// buffers[activeSlot] → PlayBuffer.Audio (loop, cubic, rate ±1, swapped ───┤
/// on slot change via setBuffer) │
/// dry ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─────────────────────────┴→ wet
/// ```
/// ## The Loop footswitch drives the transport by state
/// - **Clear** (nothing recorded; only track A selectable): press → record A; press → set the
/// loop end (quantized) and drop into overdub on A when it wraps; press → end overdub, keep
/// playing; further presses toggle overdub ↔ play on the selected track.
/// - **Playing, track B–D selected**: press toggles overdub on that track, aligned to A's
/// play-head. Recording an empty track is just overdub onto silence.
/// - Selecting another track ends any overdub on the previous one (it drops to playback). A
/// newly-selected track records nothing until Loop is pressed.
/// - **Stopped** (via Stop / Cue Stop): press → resume all tracks; next press → toggle overdub.
///
/// A single fixed generator graph is built once. Only one slot records or overdubs at a time
/// (gated so inactive slots keep their content); the shared player's source buffer is swapped
/// to the active slot with ``PlayBuffer/Audio/setBuffer(_:engine:)``. Every transport action is
/// a live parameter change the graph already reads each block, plus explicit methods for the
/// genuine non-RT side effects (clearing a buffer, narrowing `loopLength`, snapshotting for undo,
/// swapping the player's buffer).
///
/// ## Transport (beat-quantized when a clock is present)
/// - ``toggleRecordStop()``: `.empty` → arm/begin recording the active slot; `.recording` →
/// close the loop and start looping. No-op while `.playing` — use ``resetLoop()``.
/// - ``selectSlot(_:)`` / ``cycleSlot()``: switch the active slot. A recorded slot resumes
/// looping from its head; an empty slot is silent and ready to record.
/// - `overdubOn` (via ``toggleOverdub()``): layers input onto the active slot; engaging it
/// first snapshots the loop so ``undoOverdub()`` can revert the pass.
/// - `loopOn` / `reverse` (switches): crossfaded mute / live playback-direction flip.
/// - ``resetLoop()``: clears the active slot and returns it to `.empty`.
///
/// ## Knobs
/// - `crossfadeTime`, `playbackLevel`, `overdubLevel`, `feedback` (see the property docs).
/// ## Audio graph (built once in `effect(_:)`)
/// One `PlayBuffer` per track, all summed; one always-running overdub `RecordBuffer` per track
/// whose `recLevel` is gated so only the selected, overdubbing track layers new input; a
/// non-looping master recorder for track A's length-defining take. The overdub recorders run
/// continuously while playing (reset to the top at play-start) so their write head stays locked
/// to the shared play-head — overdub can be toggled on any track without drifting out of phase.
public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-slot looper: record several loops, switch between them, overdub, and reverse."
"Multitrack looper: record track A, then layer synced overdubs on tracks B–D."
}
/// Double-width card: the looper carries a full transport plus a slot strip and timeline.
/// Double-width card: the looper carries a full transport plus a track strip and timeline.
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.
/// Overdub input gain, in dB.
@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 for a decaying feedback loop.
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
/// layers indefinitely; lower values fade them for a decaying feedback loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Overdub gate. `0` = off, `1` = on. Live-gated — affects only the active, playing slot.
@UIParam public var overdubOn: Double = 0.0
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
@UIParam public var reverse: Double = 0.0
// MARK: - Internal live state
// MARK: - Internal live state (read by the audio graph / UI LEDs)
/// `1` while the active slot is looping playback, else `0`. Read by the audio graph.
/// `1` while the loop bank is playing, else `0`. Gates the whole player sum and the overdub
/// recorders' `run`.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close / slot switch.
/// Play-head reset trigger for every player. Pulsed `0 → 1` at play-start so all tracks
/// start phase-aligned to frame 0.
@UIParam public var playTrigger: Double = 0.0
/// LED state for the Stop footswitch: `1` while a recorded loop is halted, else `0`.
/// LED state for the Stop footswitch: `1` while stopped, else `0`.
@UIParam public var stoppedIndicator: Double = 0.0
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed, else `0`.
/// Also the single source of truth for ``isStopAtLoopEndArmed``.
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed.
@UIParam public var cueStopArmed: Double = 0.0
/// LED state for the Loop footswitch: `1` while overdubbing a track.
@UIParam public var overdubIndicator: Double = 0.0
// MARK: - Constants
/// Number of independent loop slots. Each slot allocates its own `maxDurationSeconds`
/// buffer, so per-instance memory is roughly `slotCount × maxDurationSeconds × sampleRate ×
/// 8 bytes` (≈ 21 MB per slot at 44.1 kHz / 60 s — ~85 MB for four). Raise with that in mind.
public static let slotCount: Int = 4
/// Number of loop tracks (A–D).
public static let trackCount: Int = 4
/// Maximum recordable take length per slot, in seconds.
/// Maximum recordable master length, in seconds (each track allocates a buffer this long, so
/// per-instance memory is roughly `trackCount × maxDurationSeconds × sampleRate × 8 bytes`).
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 take can't divide by zero.
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.
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: - Buffers + generators (one set per slot, one shared player)
// MARK: - Buffers + generators
/// Per-slot loop buffers, sized to `maxDurationSeconds`. Allocated in `effect(_:)` because
/// `sampleRate` is only set by `PedalBoard.add(_:)` after construction.
private var buffers: [LyrebirdBuffer] = []
private var primaryRecorders: [RecordBuffer.Audio] = []
private var players: [PlayBuffer.Audio] = []
private var overdubRecorders: [RecordBuffer.Audio] = []
private var overdubGates: [ParameterNode] = []
/// Per-slot overdub gate (`1` for the active slot, `0` otherwise), multiplied into each
/// overdub recorder's `run` so only the active slot layers new material.
private var slotGateNodes: [ParameterNode] = []
/// The shared player. Its source buffer is swapped to the active slot on ``selectSlot(_:)``.
private var player: PlayBuffer.Audio?
// MARK: - Per-slot state
private var activeSlot: Int = 0
/// Closed-loop length, in frames, per slot (`0` = empty).
private var loopFrames: [Int] = []
/// Closed-loop length, in whole beats, per slot (`0` unless beat-quantized).
private var loopBeats: [Double] = []
/// Sample time playback began looping (play-head at frame 0), per slot — timeline anchor.
private var playStartSample: [SampleTime] = []
/// Undo snapshot per slot, captured when overdub was last engaged on that slot.
private var overdubUndoSnapshots: [[Double]?] = []
/// Non-looping recorder for track A's length-defining first take.
private var masterRecorder: RecordBuffer.Audio?
// MARK: - Transport state
private enum Phase {
case empty
case clear
case armedRecord
case recording
case armedStop
case recordingMaster
case armedClose
case playing
case stopped
}
/// Transport phase of the *active* slot.
private var phase: Phase = .empty
private var phase: Phase = .clear
/// Beat-boundary sample time at which the active slot started recording.
/// The track the Loop footswitch records / overdubs into (`0` = A).
private var selectedTrack: Int = 0
/// The track currently overdubbing, or `nil` when just playing.
private var overdubbingTrack: Int?
/// `true` once a track holds recorded material.
private var trackHasContent: [Bool] = []
/// Master loop length in frames (`0` until track A is closed).
private var masterLength: Int = 0
/// Master loop length in whole beats (`0` unless beat-quantized).
private var masterBeats: Double = 0.0
/// Sample time at which the master take began recording, and at which playback last (re)started.
private var recordStartSample: SampleTime = 0
private var playStartSample: SampleTime = 0
/// Background routine that waits for the next beat before applying a transport action.
private var transportRoutine: LyrebirdRoutine?
/// Background routine that defers an undo restore until the RT overdub gate has closed.
private var undoRoutine: LyrebirdRoutine?
/// Background routine that waits for the loop boundary before an armed "stop at end".
private var stopRoutine: LyrebirdRoutine?
/// Monotonic action generation. Bumped on every arm, slot switch, overdub press, and reset;
/// a deferred beat/undo callback carries the generation it was armed under and is dropped if
/// the generation has since advanced — so a superseded callback can never apply to the wrong
/// state. 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.)
/// Monotonic action generation guarding deferred beat/stop callbacks (see the single-track
/// history — `LyrebirdRoutine.stop()` cannot recall an already-enqueued main-thread hop).
private(set) var transportGeneration: Int = 0
// MARK: - Init
@@ -202,7 +159,7 @@ public final class LooperPedal: Pedal {
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / switches / buttons
// MARK: - Knobs / buttons
public override var effectKnobs: [PedalKnob] {
[
@@ -213,101 +170,130 @@ public final class LooperPedal: Pedal {
]
}
/// Transport row (below the knobs): the two state toggles flank the two stops.
/// Transport row: the smart Loop footswitch, the two stops, direction, and reset.
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(label: "Loop", node: $loopOn),
PedalButton(label: "Stop", indicator: $stoppedIndicator) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", node: $reverse),
]
}
/// Momentary action row.
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: "Slot") { [weak self] in self?.cycleSlot() },
PedalButton(label: "Loop", indicator: $overdubIndicator,
dynamicLabel: { [weak self] in self?.loopButtonCaption ?? "Loop" }) { [weak self] in self?.pressLoop() },
PedalButton(label: "Stop", indicator: $stoppedIndicator,
dynamicLabel: { [weak self] in self?.stopButtonCaption ?? "Stop" }) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed,
dynamicLabel: { [weak self] in self?.cueStopButtonCaption ?? "Cue Stop" }) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", node: $reverse,
dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }),
PedalButton(label: "Reset") { [weak self] in self?.resetLoop() },
]
}
// MARK: - UI read-outs
/// Publicly-observable transport phase of the active slot (LED colour, armed state, timeline).
/// Publicly-observable transport phase for the state indicator, LEDs, and 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
case .stopped: return .stopped
case .clear: return .clear
case .armedRecord: return .armedRecord
case .recordingMaster: return .recordingMaster
case .armedClose: return .armedClose
case .playing: return .playing
case .stopped: return .stopped
}
}
/// `true` while a "stop at loop end" is armed and waiting for the boundary.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Index of the selected track, `0 ..< trackCount`.
public var selectedTrackIndex: Int { selectedTrack }
/// Index of the active loop slot, in `0 ..< slotCount`.
public var activeSlotIndex: Int { activeSlot }
/// The track currently overdubbing, or `nil`.
public var overdubbingTrackIndex: Int? { overdubbingTrack }
/// `true` if slot `index` holds a recorded loop.
public func slotHasContent(_ index: Int) -> Bool {
index >= 0 && index < loopFrames.count && loopFrames[index] > 0
/// `true` if track `index` holds recorded material.
public func trackHasContent(_ index: Int) -> Bool {
index >= 0 && index < trackHasContent.count && trackHasContent[index]
}
/// Active-slot loop length in frames (`0` until a take is recorded).
public var loopFrameCount: Int { loopFrames.indices.contains(activeSlot) ? loopFrames[activeSlot] : 0 }
/// `true` while a stop-at-loop-end is armed.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Active-slot loop length in seconds.
public var loopLengthSeconds: Double { Double(loopFrameCount) / sampleRate }
/// Master loop length in frames (`0` until track A is closed).
public var loopFrameCount: Int { masterLength }
/// Active-slot loop length in whole beats (`0` unless the take was beat-quantized).
public var loopLengthBeats: Double { loopBeats.indices.contains(activeSlot) ? loopBeats[activeSlot] : 0.0 }
/// Master loop length in seconds.
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
/// Normalised play-head position in `[0, 1)` while the active slot is `.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`.
/// Master loop length in whole beats (`0` unless beat-quantized).
public var loopLengthBeats: Double { masterBeats }
/// Normalised play-head position in `[0, 1)` while playing, else `nil`. Shared by all tracks.
public func playbackPosition01() -> Double? {
guard phase == .playing, loopFrameCount > 0,
let engine: SynthesisEngine = hostEngine,
playStartSample.indices.contains(activeSlot) else { return nil }
let elapsed: SampleTime = engine.currentTime - playStartSample[activeSlot]
guard phase == .playing, masterLength > 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(loopFrameCount))
let forward: Double = Double(framesInto) / Double(loopFrameCount)
let framesInto: Int = Int(elapsed % SampleTime(masterLength))
let forward: Double = Double(framesInto) / Double(masterLength)
return reverse >= 0.5 ? (1.0 - forward) : forward
}
/// Caption for the Loop footswitch describing what the *next* press does.
public var loopButtonCaption: String {
switch phase {
case .clear: return "Record"
case .armedRecord: return "Recording"
case .recordingMaster: return "Set End"
case .armedClose: return "Closing"
case .stopped: return "Play"
case .playing:
if overdubbingTrack == selectedTrack { return "Play" }
return trackHasContent(selectedTrack) ? "Overdub" : "Record"
}
}
/// Caption for the Stop footswitch (what the next press does).
public var stopButtonCaption: String { phase == .stopped ? "Stopped" : "Stop" }
/// Caption for the Cue Stop footswitch.
public var cueStopButtonCaption: String { isStopAtLoopEndArmed ? "Cancel" : "Cue Stop" }
/// Caption for the Reverse footswitch (the direction the next press switches to).
public var reverseButtonCaption: String { reverse >= 0.5 ? "Forward" : "Reverse" }
/// One-line description of what the pedal is doing now, for the state indicator.
public var stateDescription: String {
let armedSuffix: String = isStopAtLoopEndArmed ? " · stop at end" : ""
switch phase {
case .clear: return "Empty — record track A"
case .armedRecord: return "Waiting for beat…"
case .recordingMaster: return "Recording A"
case .armedClose: return "Closing loop…"
case .stopped: return "Stopped"
case .playing:
if let track: Int = overdubbingTrack {
return "Overdubbing \(LooperPedal.trackLabel(track))" + armedSuffix
}
return "Playing" + armedSuffix
}
}
/// The letter for a track index (0 → "A").
public static func trackLabel(_ index: Int) -> String {
let letters: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
return letters.indices.contains(index) ? letters[index] : "?"
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let unity: Double = 1.0
for i: Int in 0 ..< LooperPedal.slotCount {
for _: Int in 0 ..< LooperPedal.trackCount {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffers.append(buffer)
let primary: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: false,
doneAction: .nothing
)
primary.run = 0.0
primaryRecorders.append(primary)
// Active-slot gate: `1` only for slot 0 at build (the default active slot).
let activeAtBuild: Double = i == activeSlot ? 1.0 : 0.0
let gate: ParameterNode = ParameterNode(activeAtBuild)
slotGateNodes.append(gate)
let gate: ParameterNode = ParameterNode(0.0)
overdubGates.append(gate)
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
@@ -315,76 +301,102 @@ public final class LooperPedal: Pedal {
loop: true,
doneAction: .nothing
)
// Live-gated: writes only while this slot is active, playing, and overdub is on.
// Existing content is scaled by `feedback` each pass (1.0 = keep, < 1.0 = decay).
overdub.$run.source = $overdubOn * $isPlaying * gate
overdub.$recLevel.source = DbAmp.Control($overdubLevel)
overdub.$preLevel.source = $feedback
// Always running while playing; its write head stays locked to the shared play-head.
// `recLevel` is zero unless this track is the one being overdubbed; `preLevel` is 1
// (identity — keep existing content) except while overdubbing, when it is `feedback`.
overdub.$run.source = $isPlaying
overdub.$recLevel.source = gate * DbAmp.Control($overdubLevel)
overdub.$preLevel.source = (unity - gate) + gate * $feedback
overdubRecorders.append(overdub)
let player: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
players.append(player)
}
loopFrames = [Int](repeating: 0, count: LooperPedal.slotCount)
loopBeats = [Double](repeating: 0.0, count: LooperPedal.slotCount)
playStartSample = [SampleTime](repeating: 0, count: LooperPedal.slotCount)
overdubUndoSnapshots = [[Double]?](repeating: nil, count: LooperPedal.slotCount)
// 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: buffers[activeSlot],
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
let master: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffers[0],
loop: false,
doneAction: .nothing
)
player = loopPlayer
master.run = 0.0
masterRecorder = master
// Loop audible only while playing and not muted; smoothed to avoid clicks.
trackHasContent = [Bool](repeating: false, count: LooperPedal.trackCount)
// Loop bank audible only while playing and not muted; smoothed to avoid clicks.
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
let dryGate: any ValidGeneratorInput = unity - smoothedGate
// The recorders are `RootRegistering` and run for their write side effect; the mix is
// the dry passthrough plus the shared player.
return (dry * dryGate) + (loopPlayer * smoothedGate)
// Sum all track players. Empty buffers contribute silence.
var loopSum: any ValidGeneratorInput = players[0]
for i: Int in 1 ..< players.count {
loopSum = loopSum + players[i]
}
return (dry * dryGate) + (loopSum * smoothedGate)
}
// MARK: - Transport
// MARK: - Loop footswitch
/// `.empty` → arm/begin recording the active slot. `.recording` → close the loop and start
/// looping. No-op while `.playing` or already armed.
public func toggleRecordStop() {
/// The smart transport press. Behaviour depends on the current phase and selected track.
public func pressLoop() {
switch phase {
case .empty:
armRecording()
case .recording:
armStopAndPlay()
case .stopped:
resumePlayback()
case .armedRecord, .armedStop, .playing:
case .clear: armMasterRecording()
case .recordingMaster: armCloseMaster()
case .playing: toggleOverdubSelected()
case .stopped: resumePlayback()
case .armedRecord, .armedClose:
break
}
}
/// Immediately halts loop playback of the active slot. The recorded content is retained —
/// press Record / Stop (or switch slots) to start it again. Cancels any armed "stop at end".
/// Selects the active track (the one Loop records / overdubs into). Tapping a timeline dot
/// calls this. Only track A is selectable while clear. Selecting a new track ends any overdub
/// on the previous one (it drops to playback); the new track records nothing until Loop.
public func selectTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, index != selectedTrack, !buffers.isEmpty else { return }
switch phase {
case .clear:
return // only track A while clear
case .armedRecord, .recordingMaster, .armedClose:
return // not mid master-record
case .playing, .stopped:
break
}
if overdubbingTrack != nil {
overdubbingTrack = nil // selecting elsewhere ends the current overdub
}
selectedTrack = index
updateOverdubGates()
}
// MARK: - Stops / reset
/// Immediately halts playback of all tracks; recorded content is retained (resume via Loop).
public func stopPlayback() {
guard phase == .playing else { return }
transportGeneration += 1
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// Arms (or, if already armed, cancels) a stop that fires when the active loop next reaches
/// its end. No-op unless a loop is playing. With no engine to schedule against, stops now.
/// Arms (or cancels) a stop that fires when the loop next reaches its end. No-op unless
/// playing. With no engine to schedule against, stops now.
public func toggleStopAtLoopEnd() {
if isStopAtLoopEndArmed {
stopRoutine?.stop()
@@ -393,18 +405,16 @@ public final class LooperPedal: Pedal {
transportGeneration += 1
return
}
guard phase == .playing, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) else { return }
guard phase == .playing, masterLength > 0 else { return }
transportGeneration += 1
let generation: Int = transportGeneration
guard let engine: SynthesisEngine = hostEngine else {
stopPlayback()
return
}
// Sample time of the next loop boundary after now.
let anchor: SampleTime = playStartSample[activeSlot]
let frames: SampleTime = SampleTime(loopFrameCount)
let elapsed: SampleTime = max(0, engine.currentTime - anchor)
let boundary: SampleTime = anchor + (elapsed / frames + 1) * frames
let frames: SampleTime = SampleTime(masterLength)
let elapsed: SampleTime = max(0, engine.currentTime - playStartSample)
let boundary: SampleTime = playStartSample + (elapsed / frames + 1) * frames
cueStopArmed = 1.0
stopRoutine?.stop()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
@@ -419,172 +429,94 @@ public final class LooperPedal: Pedal {
func applyStopAtLoopEnd(generation: Int) {
guard generation == transportGeneration, phase == .playing else { return }
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// Resumes looping playback of a stopped slot from its head.
private func resumePlayback() {
guard phase == .stopped, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) else { return }
transportGeneration += 1
isPlaying = 1.0
stoppedIndicator = 0.0
phase = .playing
playStartSample[activeSlot] = hostEngine?.currentTime ?? 0
pulsePlayTrigger()
}
/// Toggles the overdub gate on the active slot. 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 active slot 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.
public func undoOverdub() {
guard buffers.indices.contains(activeSlot),
let snapshot: [Double] = overdubUndoSnapshots[activeSlot],
snapshot.count <= buffers[activeSlot].totalSampleCount else { return }
overdubOn = 0.0
// Advance and capture the generation: a later reset / new take / slot switch / overdub
// press bumps it and drops this restore, so it can't stomp a buffer since changed.
transportGeneration += 1
let generation: Int = transportGeneration
let slot: Int = activeSlot
guard let engine: SynthesisEngine = hostEngine else {
// No engine (standalone / headless tests): single-threaded, restore immediately.
applyUndoRestore(snapshot, slot: slot, 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, slot: slot, generation: generation) }
}
undoRoutine = routine
routine.start(engine: engine)
}
/// Writes an undo snapshot back into slot `slot`'s buffer, unless its generation has been
/// superseded by a reset, a new take, a slot switch, or a subsequent overdub/undo press.
func applyUndoRestore(_ snapshot: [Double], slot: Int, generation: Int) {
guard generation == transportGeneration,
buffers.indices.contains(slot),
snapshot.count <= buffers[slot].totalSampleCount else { return }
buffers[slot].setRangeValues(snapshot, startingAt: 0)
}
/// Advances to the next slot (wrapping), as the `Slot` footswitch does.
public func cycleSlot() {
selectSlot((activeSlot + 1) % LooperPedal.slotCount)
}
/// Switches the active slot. A recorded slot resumes looping from its head; an empty slot is
/// silent and ready to record. No-op while recording or armed (finish or reset first).
public func selectSlot(_ index: Int) {
guard index >= 0, index < LooperPedal.slotCount, index != activeSlot,
buffers.indices.contains(index), loopFrames.indices.contains(index) else { return }
guard phase == .empty || phase == .playing || phase == .stopped else { return }
// The RT player's buffer can only be swapped with an engine; without one the switch
// would desync the UI/transport state from the (unchanged) audio, so require it.
guard let engine: SynthesisEngine = hostEngine else { return }
transportGeneration += 1
undoRoutine?.stop()
undoRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
stoppedIndicator = 0.0
overdubOn = 0.0
if slotGateNodes.indices.contains(activeSlot) { slotGateNodes[activeSlot].value = 0.0 }
activeSlot = index
if slotGateNodes.indices.contains(index) { slotGateNodes[index].value = 1.0 }
player?.setBuffer(buffers[index], engine: engine)
if loopFrames[index] > 0 {
isPlaying = 1.0
phase = .playing
playStartSample[index] = engine.currentTime
pulsePlayTrigger()
} else {
isPlaying = 0.0
phase = .empty
playTrigger = 0.0
}
}
/// Clears the active slot and returns it to `.empty`, ready for a fresh take.
/// Returns the pedal to the clear state: all tracks cleared, track A selected, length reset.
/// If sound is playing it acts as an immediate stop-and-clear.
public func resetLoop() {
// Stop (non-blocking) any pending routines and advance the generation so an enqueued
// beat/undo callback is dropped rather than applied to the new take.
transportRoutine?.stop()
transportRoutine = nil
undoRoutine?.stop()
undoRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
stoppedIndicator = 0.0
transportGeneration += 1
if primaryRecorders.indices.contains(activeSlot) {
primaryRecorders[activeSlot].run = 0.0
primaryRecorders[activeSlot].requestReset()
masterRecorder?.run = 0.0
masterRecorder?.requestReset()
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset()
}
if overdubRecorders.indices.contains(activeSlot) {
overdubRecorders[activeSlot].requestReset()
for buffer: LyrebirdBuffer in buffers {
buffer.clear()
buffer.setLoopLength(buffer.count)
}
if buffers.indices.contains(activeSlot) {
buffers[activeSlot].clear()
buffers[activeSlot].setLoopLength(buffers[activeSlot].count)
for i: Int in trackHasContent.indices {
trackHasContent[i] = false
}
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
isPlaying = 0.0
overdubOn = 0.0
loopOn = 1.0
playTrigger = 0.0
if loopFrames.indices.contains(activeSlot) { loopFrames[activeSlot] = 0 }
if loopBeats.indices.contains(activeSlot) { loopBeats[activeSlot] = 0.0 }
if overdubUndoSnapshots.indices.contains(activeSlot) { overdubUndoSnapshots[activeSlot] = nil }
phase = .empty
stoppedIndicator = 0.0
cueStopArmed = 0.0
updateOverdubGates()
phase = .clear
}
// MARK: - Transport helpers
/// Snapshots the active slot's closed-loop content into `overdubUndoSnapshots`. Called with
/// overdub off, so only the loop player reads the buffer concurrently (a lock-free read is safe).
private func captureOverdubSnapshot() {
guard buffers.indices.contains(activeSlot), loopFrameCount > 0 else { return }
let buffer: LyrebirdBuffer = buffers[activeSlot]
// Mono buffer: linear storage index == frame index.
let frameCount: Int = min(loopFrameCount, buffer.totalSampleCount)
var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount)
for i: Int in 0 ..< frameCount {
snapshot[i] = buffer[i]
private func updateOverdubGates() {
for i: Int in overdubGates.indices {
overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0
}
overdubUndoSnapshots[activeSlot] = snapshot
overdubIndicator = overdubbingTrack != nil ? 1.0 : 0.0
}
/// Pulses `playTrigger` `0 → 1` across two run-loop turns so the player sees a clean reset
/// edge even when the trigger was already high (e.g. switching between recorded slots).
private func toggleOverdubSelected() {
if overdubbingTrack == selectedTrack {
overdubbingTrack = nil
} else {
overdubbingTrack = selectedTrack
if trackHasContent.indices.contains(selectedTrack) { trackHasContent[selectedTrack] = true }
}
updateOverdubGates()
}
/// (Re)starts playback of all tracks from the top, optionally overdubbing `overdubTrack`.
private func startPlayback(overdubTrack: Int?, at sample: SampleTime) {
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset() // realign every write head to the top
}
playStartSample = sample
isPlaying = 1.0
stoppedIndicator = 0.0
overdubbingTrack = overdubTrack
if let track: Int = overdubTrack, trackHasContent.indices.contains(track) {
trackHasContent[track] = true
}
updateOverdubGates()
pulsePlayTrigger()
phase = .playing
}
/// Resumes playback of all active tracks from a stopped state.
private func resumePlayback() {
guard phase == .stopped, masterLength > 0 else { return }
transportGeneration += 1
startPlayback(overdubTrack: nil, at: hostEngine?.currentTime ?? 0)
}
/// Pulses `playTrigger` `0 → 1` across two run-loop turns so every player sees a clean reset
/// edge, guarded by the generation so a superseding action drops the delayed edge.
private func pulsePlayTrigger() {
playTrigger = 0.0
// Guard the delayed edge with the generation (bumped by every transport action) so a
// record/reset/switch landing in the async gap can't fire a stale trigger on the player.
let generation: Int = transportGeneration
DispatchQueue.main.async { [weak self] in
guard let self, self.transportGeneration == generation else { return }
@@ -592,26 +524,23 @@ public final class LooperPedal: Pedal {
}
}
/// A transport transition deferred to a beat boundary.
private enum QuantizedAction: Sendable {
case beginRecording
case finishStop
case beginMaster
case closeMaster
}
/// Begins recording immediately, or — with a clock — on the next beat boundary.
private func armRecording() {
private func armMasterRecording() {
selectedTrack = 0 // only track A in the clear state
updateOverdubGates()
phase = .armedRecord
runQuantized(.beginRecording)
runQuantized(.beginMaster)
}
/// Closes the loop immediately, or — with a clock — on the next beat boundary.
private func armStopAndPlay() {
phase = .armedStop
runQuantized(.finishStop)
private func armCloseMaster() {
phase = .armedClose
runQuantized(.closeMaster)
}
/// 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.
private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1
let generation: Int = transportGeneration
@@ -623,61 +552,50 @@ public final class LooperPedal: Pedal {
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, a slot switch, 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)
case .beginMaster: beginMasterRecording(at: beatSample)
case .closeMaster: closeMasterAndPlay(at: beatSample)
}
}
func beginRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, primaryRecorders.indices.contains(activeSlot) else { return }
func beginMasterRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
primaryRecorders[activeSlot].run = 1.0
phase = .recording
master.run = 1.0
phase = .recordingMaster
}
func finishRecordingAndPlay(at beatSample: SampleTime?) {
guard phase == .armedStop, primaryRecorders.indices.contains(activeSlot),
buffers.indices.contains(activeSlot) else { return }
let primary: RecordBuffer.Audio = primaryRecorders[activeSlot]
let buffer: LyrebirdBuffer = buffers[activeSlot]
primary.run = 0.0
func closeMasterAndPlay(at beatSample: SampleTime?) {
guard phase == .armedClose, let master: RecordBuffer.Audio = masterRecorder, !buffers.isEmpty else { return }
master.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[activeSlot] = max(LooperPedal.minimumLoopFrames, spanFrames)
loopBeats[activeSlot] = beatsForSpan(frames: loopFrames[activeSlot], clock: clock)
masterLength = max(LooperPedal.minimumLoopFrames, spanFrames)
masterBeats = beatsForSpan(frames: masterLength, clock: clock)
} else {
// Un-quantized fallback: trim to the recorder's frame count.
loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
loopBeats[activeSlot] = 0.0
masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount)
masterBeats = 0.0
}
buffer.setLoopLength(loopFrames[activeSlot])
playStartSample[activeSlot] = closeSample
playTrigger = 1.0
isPlaying = 1.0
phase = .playing
for buffer: LyrebirdBuffer in buffers {
buffer.setLoopLength(masterLength)
}
if trackHasContent.indices.contains(0) { trackHasContent[0] = true }
// Auto-drop into overdub on track A when the loop wraps to the top.
startPlayback(overdubTrack: 0, at: closeSample)
}
/// 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.
/// Whole-beat length of a `frames`-long span at the clock's current tempo (UI read-out only).
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 }