// LooperPedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import LyrebirdSynth import LyrebirdUI /// 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. /// /// ## 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. /// /// > Note: Overdub records forward-in-time, so it cannot be engaged while playback is reversed /// > (the write head would drift against the backward-reading play-head). Engaging overdub is /// > blocked while `reverse` is on. /// /// ## 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 { "Multitrack looper: record track A, then layer synced overdubs on tracks B–D." } /// Double-width card: the looper carries a full transport plus a track strip and timeline. public override var widthUnits: Int { 2 } /// The looper always passes the clean signal through and adds the loop on top (see `effect`), /// so the wet/dry Mix knob is meaningless — hide it and keep `mix` fully wet. public override var showsMixControl: Bool { false } // MARK: - Knobs /// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff. @UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime /// Loop playback gain, in dB. @UIParam public var playbackLevel: Double = 0.0 /// Overdub input gain, in dB. @UIParam public var overdubLevel: Double = 0.0 /// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior /// layers indefinitely; lower values fade them for a decaying feedback loop. @UIParam public var feedback: Double = 1.0 // MARK: - Switches /// 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 (read by the audio graph / UI LEDs) /// `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 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 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. @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 /// LED state for the Reset footswitch: `1` whenever there is something to reset (any state /// other than clear). Kept in sync by `phase`'s `didSet`. @UIParam public var resetIndicator: Double = 0.0 // MARK: - Constants /// Number of loop tracks (A–D). public static let trackCount: Int = 4 /// 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 private static let defaultCrossfadeTime: Double = 0.05 private static let reverseRateSpan: Double = 2.0 private static let forwardRate: Double = 1.0 private static let minimumLoopFrames: Int = 1 private let crossfadeTimeRange: ClosedRange = 0.0 ... 2.0 private let levelRangeDb: ClosedRange = -24.0 ... 12.0 private let feedbackRange: ClosedRange = 0.0 ... 1.0 // MARK: - Buffers + generators private var buffers: [LyrebirdBuffer] = [] private var players: [PlayBuffer.Audio] = [] private var overdubRecorders: [RecordBuffer.Audio] = [] private var overdubGates: [ParameterNode] = [] /// Non-looping recorder for track A's length-defining first take. private var masterRecorder: RecordBuffer.Audio? // MARK: - Transport state private enum Phase { case clear case armedRecord case recordingMaster case armedClose case playing case stopped } private var phase: Phase = .clear { didSet { resetIndicator = phase == .clear ? 0.0 : 1.0 } } /// 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 private var transportRoutine: LyrebirdRoutine? private var stopRoutine: LyrebirdRoutine? /// Transient notice shown in place of the state description for `noticeDuration` seconds. private var noticeText: String? private var noticeExpiry: Date? private static let noticeDuration: TimeInterval = 4.0 /// 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 /// 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 / 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), ] } /// Transport row: the smart Loop footswitch, the two stops, direction, and reset. public override var effectTransportButtons: [PedalButton] { [ 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", indicator: $reverse, dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }) { [weak self] in self?.toggleReverse() }, PedalButton(label: "Reset", indicator: $resetIndicator) { [weak self] in self?.resetLoop() }, ] } // MARK: - UI read-outs /// Publicly-observable transport phase for the state indicator, LEDs, and timeline. public var transportState: LooperTransportState { switch phase { case .clear: return .clear case .armedRecord: return .armedRecord case .recordingMaster: return .recordingMaster case .armedClose: return .armedClose case .playing: return .playing case .stopped: return .stopped } } /// Index of the selected track, `0 ..< trackCount`. public var selectedTrackIndex: Int { selectedTrack } /// The track currently overdubbing, or `nil`. public var overdubbingTrackIndex: Int? { overdubbingTrack } /// `true` if track `index` holds recorded material. public func trackHasContent(_ index: Int) -> Bool { index >= 0 && index < trackHasContent.count && trackHasContent[index] } /// `true` while a stop-at-loop-end is armed. public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 } /// Master loop length in frames (`0` until track A is closed). public var loopFrameCount: Int { masterLength } /// Master loop length in seconds. public var loopLengthSeconds: Double { Double(masterLength) / sampleRate } /// 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, 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(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. A transient /// notice (e.g. the engine-stop reset) takes precedence for a few seconds. public var stateDescription: String { if let notice: String = noticeText, let expiry: Date = noticeExpiry, Date() < expiry { return notice } 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 _: Int in 0 ..< LooperPedal.trackCount { let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1) buffers.append(buffer) let gate: ParameterNode = ParameterNode(0.0) overdubGates.append(gate) let overdub: RecordBuffer.Audio = RecordBuffer.Audio( input: dry, buffer: buffer, loop: true, doneAction: .nothing ) // 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) } let master: RecordBuffer.Audio = RecordBuffer.Audio( input: dry, buffer: buffers[0], loop: false, doneAction: .nothing ) master.run = 0.0 masterRecorder = master 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) // Sum all track players. Empty buffers contribute silence. Each player is already // scaled by the `Playback` level, so `Playback` sets the loop amount against the live // signal below. var loopSum: any ValidGeneratorInput = players[0] for i: Int in 1 ..< players.count { loopSum = loopSum + players[i] } // The clean (dry) signal always passes through at full level; the loop bank is added on // top, gated by play/mute. `Playback` controls the looped-vs-live balance. return dry + (loopSum * smoothedGate) } // MARK: - Loop footswitch /// The smart transport press. Behaviour depends on the current phase and selected track. public func pressLoop() { switch phase { case .clear: armMasterRecording() case .recordingMaster: armCloseMaster() case .playing: toggleOverdubSelected() case .stopped: resumePlayback() case .armedRecord, .armedClose: break } } /// 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 } overdubbingTrack = nil // selecting elsewhere ends the current overdub selectedTrack = index updateOverdubGates() } // MARK: - Stops / reset /// Flips playback direction. Engaging reverse ends any active overdub, since overdub records /// forward-in-time and can't follow a backward-reading play-head (see the class doc). public func toggleReverse() { let engagingReverse: Bool = reverse < 0.5 reverse = engagingReverse ? 1.0 : 0.0 if engagingReverse, overdubbingTrack != nil { overdubbingTrack = nil updateOverdubGates() } } /// 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 playTrigger = 0.0 // rearm the play-head reset edge stoppedIndicator = 1.0 phase = .stopped } /// 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() stopRoutine = nil cueStopArmed = 0.0 transportGeneration += 1 return } guard phase == .playing, masterLength > 0 else { return } transportGeneration += 1 let generation: Int = transportGeneration guard let engine: SynthesisEngine = hostEngine else { stopPlayback() return } 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 try ctx.waitUntil(sampleTime: boundary) DispatchQueue.main.async { self?.applyStopAtLoopEnd(generation: generation) } } stopRoutine = routine routine.start(engine: engine) } /// Applies an armed "stop at end" once the boundary is reached, unless superseded. func applyStopAtLoopEnd(generation: Int) { guard generation == transportGeneration, phase == .playing else { return } cueStopArmed = 0.0 overdubbingTrack = nil updateOverdubGates() isPlaying = 0.0 playTrigger = 0.0 stoppedIndicator = 1.0 phase = .stopped } /// When the engine is stopped by the user, drop any recorded loop and return to the clear /// state — a stopped engine can't keep a loop running, and resuming into a half-recorded take /// is confusing. Posts a notice to the message log and briefly on the pedal's own card. public override func engineDidStop() { resetAndNotify("engine stopped") } /// The rig is being torn down (load / clear / input-source change) — reset before this looper /// instance is discarded, stopping any background routines cleanly and logging a notice. public override func rigWillTeardown() { resetAndNotify("rig changed") } /// Returns to the clear state and posts a notice (message log + briefly on the pedal card), /// unless already clear. Shared by ``engineDidStop()`` and ``rigWillTeardown()``. private func resetAndNotify(_ reason: String) { guard phase != .clear else { return } resetLoop() let message: String = "Looper reset — \(reason)." noticeText = message noticeExpiry = Date().addingTimeInterval(LooperPedal.noticeDuration) LyrebirdMessageCenter.shared.info(message, source: displayName) } /// 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() { transportRoutine?.stop() transportRoutine = nil stopRoutine?.stop() stopRoutine = nil transportGeneration += 1 // Gate the recorders off (they run off `$isPlaying`) and stop the master BEFORE clearing, // so the only overlap with `clear()` is at most the one RT block already in flight. isPlaying = 0.0 masterRecorder?.run = 0.0 masterRecorder?.requestReset() for recorder: RecordBuffer.Audio in overdubRecorders { recorder.requestReset() } // `clear()` zeroes the buffers on the main thread. `isPlaying = 0` above stops the // recorders from the next block on, so `clear()` can overlap only the single in-flight // RT block; that overlap is benign because `LyrebirdBuffer.clear()` (`vDSP_vclrD`) and // the recorder both write whole 8-byte-aligned `Double` slots — no torn value — and the // buffer is being zeroed anyway. Deferring the clear would instead race a fast // reset→re-record, so it runs immediately. for buffer: LyrebirdBuffer in buffers { buffer.clear() buffer.setLoopLength(buffer.count) } for i: Int in trackHasContent.indices { trackHasContent[i] = false } selectedTrack = 0 overdubbingTrack = nil masterLength = 0 masterBeats = 0.0 loopOn = 1.0 playTrigger = 0.0 stoppedIndicator = 0.0 cueStopArmed = 0.0 updateOverdubGates() phase = .clear } // MARK: - Transport helpers private func updateOverdubGates() { for i: Int in overdubGates.indices { overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0 } overdubIndicator = overdubbingTrack != nil ? 1.0 : 0.0 } private func toggleOverdubSelected() { if overdubbingTrack == selectedTrack { overdubbingTrack = nil } else { // Overdub records forward-in-time; a reversed player reads backward, so engaging // overdub while reversed would write out of alignment with what's heard. Block it. guard reverse < 0.5 else { return } overdubbingTrack = selectedTrack if trackHasContent.indices.contains(selectedTrack) { trackHasContent[selectedTrack] = true } } updateOverdubGates() } /// (Re)starts playback of all tracks from the top, optionally overdubbing `overdubTrack`. /// /// The recorder write heads (`requestReset`) and the player play-heads (`playTrigger` rising /// edge) are both reset **synchronously here** so they take effect on the same next audio /// block — keeping overdub writes phase-locked to playback. `playTrigger` is zeroed on every /// stop so each start is a clean `0 → 1` edge. 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() playTrigger = 1.0 // rising edge, same block as the resets 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) } private enum QuantizedAction: Sendable { case beginMaster case closeMaster } private func armMasterRecording() { selectedTrack = 0 // only track A in the clear state updateOverdubGates() phase = .armedRecord runQuantized(.beginMaster) } private func armCloseMaster() { phase = .armedClose runQuantized(.closeMaster) } 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) DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) } } transportRoutine = routine routine.start(engine: engine) } private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) { guard generation == transportGeneration else { return } switch action { case .beginMaster: beginMasterRecording(at: beatSample) case .closeMaster: closeMasterAndPlay(at: beatSample) } } func beginMasterRecording(at beatSample: SampleTime?) { guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return } recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0) master.run = 1.0 phase = .recordingMaster } 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 { let spanFrames: Int = Int(closeSample - recordStartSample) masterLength = max(LooperPedal.minimumLoopFrames, spanFrames) masterBeats = beatsForSpan(frames: masterLength, clock: clock) } else { masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount) masterBeats = 0.0 } for buffer: LyrebirdBuffer in buffers { buffer.setLoopLength(masterLength) } if trackHasContent.indices.contains(0) { trackHasContent[0] = true } // Auto-drop into overdub on track A as it wraps to the top (unless reversed — overdub // can't follow reverse playback, so just play). startPlayback(overdubTrack: reverse < 0.5 ? 0 : nil, at: closeSample) } /// 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 } return (Double(frames) / samplesPerBeat).rounded() } }