// 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." } /// Triple-width card: the looper spreads its timeline, knobs, and transport grid across three /// columns so the tall pedal fits the canvas without scrolling. public override var widthUnits: Int { 3 } /// 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 /// Transport sync mode. `1` = beat-quantized (record start / loop close snap to the next /// beat via the shared clock); `0` = freeform (immediate, loop length is whatever you play). /// Persisted with the rig. Default `1`. @UIParam public var syncToBeat: Double = 1.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] = [] /// Per-track playback mute gate (`1` = audible, `0` = muted), smoothed by `crossfadeTime` and /// multiplied into each track's player so a recorded track can be silenced. private var muteGates: [ParameterNode] = [] /// Per-track mute state (`true` = muted). private var trackMuted: [Bool] = [] /// 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 /// Play-head position tracking that survives direction changes. `playHeadAnchor01` is the /// normalised play-head fraction at the last anchor event (playback start or a reverse flip); /// `playHeadAnchorSample` is the engine sample at that event. Between events the position is /// `anchor01 + direction · (elapsed / masterLength)`, wrapped into `[0, 1)`. This mirrors the /// actual `PlayBuffer` play-head — which reverses smoothly from its live phase — instead of the /// old `1 − forward` reflection that jumped the read-out to the mirror point on every reverse. private var playHeadAnchor01: Double = 0.0 private var playHeadAnchorSample: SampleTime = 0 private var transportRoutine: LyrebirdRoutine? private var stopRoutine: LyrebirdRoutine? private var reverseRoutine: LyrebirdRoutine? /// Generation guard for a beat-deferred reverse. Separate from `transportGeneration` so /// scheduling a reverse never invalidates a pending record/close (and vice versa). private(set) var reverseGeneration: Int = 0 /// 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), ] } /// Beat-sync vs freeform transport mode, as a two-position segmented switch below the knobs. public override var effectSwitches: [PedalSwitch] { [ PedalSwitch( label: "Sync to Tempo", node: $syncToBeat, options: [ PedalSwitch.Option(title: "Free", value: 0.0), PedalSwitch.Option(title: "Sync", value: 1.0), ], tempoDependent: true ), ] } /// 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] } /// Per-track generator array counts — internal only so a test can verify a graph rebuild /// (`effect()` re-run) doesn't accumulate them. All four should equal `trackCount`. var trackGeneratorCountsForTesting: (buffers: Int, players: Int, overdub: Int, gates: Int) { (buffers.count, players.count, overdubRecorders.count, overdubGates.count) } /// `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 } return playHeadFraction(at: engine.currentTime) } /// The normalised play-head fraction in `[0, 1)` at engine sample `sample`, integrating the /// signed distance travelled since the last anchor (playback start or reverse flip). Reversal /// simply changes the sign of the accumulation from the current position — no jump. func playHeadFraction(at sample: SampleTime) -> Double { guard masterLength > 0 else { return 0.0 } let direction: Double = reverse >= 0.5 ? -1.0 : 1.0 let elapsed: Double = Double(sample - playHeadAnchorSample) let raw: Double = playHeadAnchor01 + direction * elapsed / Double(masterLength) var frac: Double = raw.truncatingRemainder(dividingBy: 1.0) if frac < 0 { frac += 1.0 } return frac } /// 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 { // `effect()` runs from `build()`, which the engine re-invokes via `rebuildGraph()` on // EVERY add — including the re-adds that a board edit (reorder, insert/remove a neighbour, // toggle a split) performs on this same instance. Start from a clean slate so the per-track // generator arrays don't accumulate across rebuilds, and so stale transport state doesn't // outlive the freshly re-allocated (empty) buffers built below. resetForRebuild() 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 muteGate: ParameterNode = ParameterNode(1.0) // 1 = audible muteGates.append(muteGate) 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) trackMuted = [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, each scaled by its smoothed per-track mute gate. 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] * Lag.Control(input: muteGates[0], time: $crossfadeTime) for i: Int in 1 ..< players.count { loopSum = loopSum + players[i] * Lag.Control(input: muteGates[i], time: $crossfadeTime) } // 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 } } /// Handles a tap on a track dot: selects the track, or — when it is already the selected track /// and holds recorded material — toggles its mute. So a first tap focuses a track (to overdub /// or record it), and a second tap on that same recorded track mutes/unmutes it. public func tapTrack(_ index: Int) { guard index >= 0, index < LooperPedal.trackCount, !buffers.isEmpty else { return } if index == selectedTrack, trackHasContent(index) { toggleTrackMute(index) } else { selectTrack(index) } } /// `true` if track `index` is currently muted. public func isTrackMuted(_ index: Int) -> Bool { index >= 0 && index < trackMuted.count && trackMuted[index] } /// Toggles a recorded track's playback mute (smoothed via `crossfadeTime`). private func toggleTrackMute(_ index: Int) { guard trackMuted.indices.contains(index), muteGates.indices.contains(index) else { return } trackMuted[index].toggle() muteGates[index].value = trackMuted[index] ? 0.0 : 1.0 } /// Selects the active track (the one Loop records / overdubs into). 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 /// Advances the Sync mode through its options (Free ↔ Sync), wrapping — so a MIDI switch can /// oscillate through the positions on each press, matching the segmented control. public func cycleSyncMode() { guard let sync: PedalSwitch = effectSwitches.first(where: { $0.node === $syncToBeat }) else { return } syncToBeat = sync.nextValue(after: syncToBeat) } /// Flips playback direction from the current play-head position. In Sync mode the flip is /// deferred to the next beat; in Free mode (or with no clock/engine, or when not playing) it /// applies immediately. 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() { reverseRoutine?.stop() reverseRoutine = nil // Not playing: no live play-head to reverse — just flip the direction for the next start. guard phase == .playing else { applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample) return } reverseGeneration += 1 let generation: Int = reverseGeneration // Free mode, or no clock/engine to schedule against → reverse immediately from here. guard syncToBeat >= 0.5, let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else { applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample) return } // Sync mode: reverse on the next beat, from wherever the play-head is at that beat. let target: SampleTime = clock.nextBeat() let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in try ctx.waitUntil(sampleTime: target) DispatchQueue.main.async { self?.applyDeferredReverse(generation: generation, at: target) } } reverseRoutine = routine routine.start(engine: engine) } /// Applies a beat-deferred reverse once its target beat is reached, unless superseded by a /// newer reverse press or a transport change. func applyDeferredReverse(generation: Int, at beatSample: SampleTime) { guard generation == reverseGeneration, phase == .playing else { return } reverseRoutine = nil applyReverse(at: beatSample) } /// Flips the playback direction, re-anchoring the position read-out to the current play-head so /// it continues smoothly in the new direction. `sample` is the point the flip takes effect. func applyReverse(at sample: SampleTime) { let engagingReverse: Bool = reverse < 0.5 // Re-anchor at the current play-head fraction *before* flipping, so the new-direction // accumulation starts from where we actually are. playHeadAnchor01 = playHeadFraction(at: sample) playHeadAnchorSample = sample 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 reverseRoutine?.stop() reverseRoutine = 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 reverseRoutine?.stop() reverseRoutine = 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 } for i: Int in trackMuted.indices { trackMuted[i] = false } for gate: ParameterNode in muteGates { gate.value = 1.0 } selectedTrack = 0 overdubbingTrack = nil masterLength = 0 masterBeats = 0.0 loopOn = 1.0 reverse = 0.0 // clean slate: forward playback playTrigger = 0.0 stoppedIndicator = 0.0 cueStopArmed = 0.0 // Drop any lingering transient notice so it can't mask the fresh state indicator. noticeText = nil noticeExpiry = nil updateOverdubGates() phase = .clear } // MARK: - Transport helpers /// Clears the per-track generator arrays and returns transport state to clear, so a graph /// rebuild (`build()` re-run) starts fresh instead of doubling the arrays or leaving state /// that references the discarded buffers. Called at the top of ``effect(_:)``. private func resetForRebuild() { transportRoutine?.stop() transportRoutine = nil stopRoutine?.stop() stopRoutine = nil reverseRoutine?.stop() reverseRoutine = nil buffers.removeAll() players.removeAll() overdubRecorders.removeAll() overdubGates.removeAll() muteGates.removeAll() masterRecorder = nil trackHasContent = [] trackMuted = [] selectedTrack = 0 overdubbingTrack = nil masterLength = 0 masterBeats = 0.0 isPlaying = 0.0 loopOn = 1.0 reverse = 0.0 playTrigger = 0.0 stoppedIndicator = 0.0 cueStopArmed = 0.0 overdubIndicator = 0.0 noticeText = nil noticeExpiry = nil phase = .clear } 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 // Play head resets to the top (frame 0) via the playTrigger edge below; anchor the // position read-out there so direction changes accumulate from a known origin. playHeadAnchor01 = 0.0 playHeadAnchorSample = 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) } 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 // Freeform (Sync off) or no clock/engine → apply immediately, un-quantized. guard syncToBeat >= 0.5, 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) } 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() } }