Looper: multi-slot + timeline + stop/cue-stop, quantized transport

Checkpoint before the multitrack redesign. Adds 4 loop slots (one player
swapped via setBuffer), a play-head timeline with A/B/C/D dots, Loop/Stop/
Cue Stop/Reverse stomp toggles below the knobs, beat-quantized transport,
overdub undo, reverse, and feedback-decay overdub — all reviewed for RT
safety (transportGeneration guards on deferred beat/undo/cue callbacks).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 14:14:46 -07:00
parent 947dfe427a
commit 465e3e6dfd
8 changed files with 600 additions and 203 deletions
+9 -1
View File
@@ -202,8 +202,16 @@ open class Pedal: SynthesizerBase {
[] []
} }
/// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
/// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row.
open var effectTransportButtons: [PedalButton] {
[]
}
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style /// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
/// buttons beneath the switch row. /// buttons beneath the transport row.
/// ///
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset") /// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
/// that need a non-RT side effect beyond writing a single parameter value — see /// that need a non-RT side effect beyond writing a single parameter value — see
+12 -2
View File
@@ -24,7 +24,7 @@ import LyrebirdUI
public struct PedalButton { public struct PedalButton {
/// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`. /// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`.
public enum Style { public enum Style: Equatable {
/// Executes `action` on each press. /// Executes `action` on each press.
case momentary case momentary
/// Flips `node` between `0` and `1` on each press. /// Flips `node` between `0` and `1` on each press.
@@ -43,16 +43,25 @@ public struct PedalButton {
/// The action run on each press. Non-`nil` only for `.momentary` style. /// The action run on each press. Non-`nil` only for `.momentary` style.
public let action: (() -> Void)? public let action: (() -> Void)?
/// Optional LED-indicator node for a `.momentary` button. When non-`nil`, the button is
/// drawn in the same LED + footswitch style as a `.toggle` button, with the LED lit while
/// this node reads `≥ 0.5` — letting a momentary action reflect a persistent state (e.g. a
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
public let indicator: UIParamNode?
/// Creates a momentary action button. /// Creates a momentary action button.
/// ///
/// - Parameters: /// - Parameters:
/// - label: Short label shown on the button. /// - label: Short label shown on the button.
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
/// for a plain button.
/// - action: Closure run on each press. /// - action: Closure run on each press.
public init(label: String, action: @escaping () -> Void) { public init(label: String, indicator: UIParamNode? = nil, action: @escaping () -> Void) {
self.label = label self.label = label
self.style = .momentary self.style = .momentary
self.node = nil self.node = nil
self.action = action self.action = action
self.indicator = indicator
} }
/// Creates a toggle button bound to a `UIParamNode`. /// Creates a toggle button bound to a `UIParamNode`.
@@ -66,5 +75,6 @@ public struct PedalButton {
self.style = .toggle self.style = .toggle
self.node = node self.node = node
self.action = nil self.action = nil
self.indicator = nil
} }
} }
+353 -179
View File
@@ -8,53 +8,48 @@ import Foundation
import LyrebirdSynth import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
/// A loop-recorder pedal: record a take into a buffer, then play it back looping, with /// A multi-slot loop-recorder pedal: record independent loops into any of several slots, then
/// overdub, overdub-undo, reverse playback, feedback-decay overdub, and a crossfaded /// switch between them, with overdub, overdub-undo, reverse playback, feedback-decay overdub,
/// total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the transport is /// and a crossfaded total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the
/// beat-quantized — record start and loop close both snap to the next beat, so every loop /// transport is beat-quantized — record start and loop close both snap to the next beat, so
/// is a whole number of beats long. /// every loop is a whole number of beats long.
/// ///
/// Signal chain (inside `effect(_:)`): /// Signal chain (inside `effect(_:)`), per slot `i` plus one shared player:
/// ``` /// ```
/// dry → RecordBuffer.Audio (primary take, passthrough while recording) ─┐ /// dry → RecordBuffer.Audio primary[i] (take capture, run-gated by transport) ─┐ (write only,
/// dry → RecordBuffer.Audio (overdub, gated by overdubOn × isPlaying, │ (write only) /// dry → RecordBuffer.Audio overdub[i] (gated by overdubOn × isPlaying × slot i) │ RootRegistering)
/// old content scaled by feedback) │ /// buffers[activeSlot] → PlayBuffer.Audio (loop, cubic, rate ±1, swapped ───┤
/// loopBuffer → PlayBuffer.Audio (loop, cubic, rate ±1) │ /// on slot change via setBuffer) │
/// primary passthrough ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─┴→ wet /// dry ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─────────────────────────┴→ wet
/// ``` /// ```
/// ///
/// A single fixed generator graph is built once (Lyrebird's node tree does not support /// A single fixed generator graph is built once. Only one slot records or overdubs at a time
/// rebuilding a synth's internal generators). Every transport action is expressed as a /// (gated so inactive slots keep their content); the shared player's source buffer is swapped
/// live parameter change the graph already reads every block (`$overdubOn`, `$loopOn`, /// to the active slot with ``PlayBuffer/Audio/setBuffer(_:engine:)``. Every transport action is
/// `$isPlaying`, `$reverse`, `$feedback`, `$playTrigger`), plus, for actions with a genuine /// a live parameter change the graph already reads each block, plus explicit methods for the
/// non-RT side effect (clearing the buffer, narrowing/restoring `loopLength`, snapshotting /// genuine non-RT side effects (clearing a buffer, narrowing `loopLength`, snapshotting for undo,
/// for undo), an explicit method. /// swapping the player's buffer).
/// ///
/// ## Transport (beat-quantized when a clock is present) /// ## Transport (beat-quantized when a clock is present)
/// - ``toggleRecordStop()``: `.empty` → arm/begin recording; `.recording` → close the loop /// - ``toggleRecordStop()``: `.empty` → arm/begin recording the active slot; `.recording` →
/// and start looping. No-op while `.playing` — use ``resetLoop()`` for a new take. /// close the loop and start looping. No-op while `.playing` — use ``resetLoop()``.
/// - `overdubOn` (via ``toggleOverdub()``): layers new input onto the loop; engaging it first /// - ``selectSlot(_:)`` / ``cycleSlot()``: switch the active slot. A recorded slot resumes
/// snapshots the loop so ``undoOverdub()`` can revert the pass. /// looping from its head; an empty slot is silent and ready to record.
/// - `loopOn` (switch): crossfaded total mute without stopping the player. /// - `overdubOn` (via ``toggleOverdub()``): layers input onto the active slot; engaging it
/// - `reverse` (switch): flips playback direction (`rate` 1 → −1) without a rebuild. /// first snapshots the loop so ``undoOverdub()`` can revert the pass.
/// - ``undoOverdub()``: restores the loop to the snapshot taken when overdub was last engaged. /// - `loopOn` / `reverse` (switches): crossfaded mute / live playback-direction flip.
/// - ``resetLoop()``: clears the buffer and returns to `.empty`. /// - ``resetLoop()``: clears the active slot and returns it to `.empty`.
/// ///
/// ## Knobs /// ## Knobs
/// - `crossfadeTime`: Fade time constant, in seconds, for `loopOn` and the record→play handoff. /// - `crossfadeTime`, `playbackLevel`, `overdubLevel`, `feedback` (see the property docs).
/// - `playbackLevel`: Loop playback gain, in dB.
/// - `overdubLevel`: Overdub input gain, in dB.
/// - `feedback`: Retained level of existing loop content on each overdub pass, `[0, 1]`.
/// `1.0` (default) keeps old layers forever; lower values fade them for a decaying dub.
public final class LooperPedal: Pedal { public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel. /// One-line description shown in the picker and info panel.
public override var summary: String { public override var summary: String {
"Records a loop, then plays it back with overdub, reverse, and a crossfaded mute." "Multi-slot looper: record several loops, switch between them, overdub, and reverse."
} }
/// Double-width card: the looper carries a full transport plus a loop timeline and reads /// Double-width card: the looper carries a full transport plus a slot strip and timeline.
/// more comfortably in a wider enclosure.
public override var widthUnits: Int { 2 } public override var widthUnits: Int { 2 }
// MARK: - Knobs // MARK: - Knobs
@@ -66,42 +61,47 @@ public final class LooperPedal: Pedal {
/// Loop playback gain, in dB. /// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0 @UIParam public var playbackLevel: Double = 0.0
/// Overdub input gain, in dB. Scales only the new material being layered in — the /// Overdub input gain, in dB. Scales only the new material being layered in.
/// existing loop content is never attenuated by this knob.
@UIParam public var overdubLevel: Double = 0.0 @UIParam public var overdubLevel: Double = 0.0
/// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0` /// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0`
/// keeps prior layers indefinitely; lower values fade them a little on every pass for a /// keeps prior layers indefinitely; lower values fade them for a decaying feedback loop.
/// decaying "sound-on-sound" feedback loop.
@UIParam public var feedback: Double = 1.0 @UIParam public var feedback: Double = 1.0
// MARK: - Switches // MARK: - Switches
/// Overdub gate. `0` = off, `1` = on. Live-gated — has no effect before a loop exists. /// Overdub gate. `0` = off, `1` = on. Live-gated — affects only the active, playing slot.
@UIParam public var overdubOn: Double = 0.0 @UIParam public var overdubOn: Double = 0.0
/// Total loop mute. `0` = muted (silent), `1` = audible. Transitions are smoothed by /// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
/// `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0 @UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read by the player's `rate` input /// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
/// as `1 − 2·reverse`, so toggling flips the loop without rebuilding the graph.
@UIParam public var reverse: Double = 0.0 @UIParam public var reverse: Double = 0.0
// MARK: - Internal live state // MARK: - Internal live state
/// `1` once a take has been recorded and looping playback has started, else `0`. /// `1` while the active slot is looping playback, else `0`. Read by the audio graph.
/// Read by the audio graph (gates overdub and the loop crossfade) — not a user knob.
@UIParam public var isPlaying: Double = 0.0 @UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close so playback /// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close / slot switch.
/// starts phase-aligned to frame 0 (the anchor for the timeline read-out); rearmed to `0`
/// on ``resetLoop()``. Read by the player's `trigger` input. Not a user knob.
@UIParam public var playTrigger: Double = 0.0 @UIParam public var playTrigger: Double = 0.0
/// LED state for the Stop footswitch: `1` while a recorded loop is halted, 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``.
@UIParam public var cueStopArmed: Double = 0.0
// MARK: - Constants // MARK: - Constants
/// Maximum recordable take length, in seconds. /// 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
/// Maximum recordable take length per slot, in seconds.
private static let maxDurationSeconds: Double = 60.0 private static let maxDurationSeconds: Double = 60.0
/// Default crossfade duration, in seconds. /// Default crossfade duration, in seconds.
@@ -113,31 +113,50 @@ public final class LooperPedal: Pedal {
/// Forward playback rate, and the rate offset the reverse span is subtracted from. /// Forward playback rate, and the rate offset the reverse span is subtracted from.
private static let forwardRate: Double = 1.0 private static let forwardRate: Double = 1.0
/// Smallest permitted loop length, in frames, so a degenerate zero-length take can't /// Smallest permitted loop length, in frames, so a degenerate take can't divide by zero.
/// produce a divide-by-zero in the player or the timeline read-out.
private static let minimumLoopFrames: Int = 1 private static let minimumLoopFrames: Int = 1
/// Frames to wait after disabling overdub before restoring an undo snapshot, so the /// Frames to wait after disabling overdub before restoring an undo snapshot, so the RT-side
/// RT-side overdub writer (its `run` gate ramps closed over one control block) has fully /// overdub writer (its `run` gate ramps closed over one control block) has fully stopped
/// stopped writing the loop buffer before the main thread overwrites it. Two maximum /// writing the loop buffer before the main thread overwrites it. Two maximum blocks.
/// blocks (`blockSize ≤ 512`) is a comfortable margin.
private static let undoGuardFrames: Int = 1024 private static let undoGuardFrames: Int = 1024
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0 private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0 private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0 private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffer + generators // MARK: - Buffers + generators (one set per slot, one shared player)
/// The loop buffer, sized to `maxDurationSeconds` at the engine sample rate. Allocated /// Per-slot loop buffers, sized to `maxDurationSeconds`. Allocated in `effect(_:)` because
/// in `effect(_:)` (called from `build()`), not `init`, because `sampleRate` is only set /// `sampleRate` is only set by `PedalBoard.add(_:)` after construction.
/// by `PedalBoard.add(_:)` after construction but before the engine builds the graph. private var buffers: [LyrebirdBuffer] = []
private var loopBuffer: LyrebirdBuffer?
private var primaryRecorder: RecordBuffer.Audio? private var primaryRecorders: [RecordBuffer.Audio] = []
private var overdubRecorder: RecordBuffer.Audio? private var overdubRecorders: [RecordBuffer.Audio] = []
/// 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? 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]?] = []
// MARK: - Transport state // MARK: - Transport state
private enum Phase { private enum Phase {
@@ -146,38 +165,29 @@ public final class LooperPedal: Pedal {
case recording case recording
case armedStop case armedStop
case playing case playing
case stopped
} }
/// Transport phase of the *active* slot.
private var phase: Phase = .empty private var phase: Phase = .empty
/// Beat-boundary sample time at which the current take started recording, and at which /// Beat-boundary sample time at which the active slot started recording.
/// the loop closes. Both are captured from the clock so the loop length is beat-exact.
private var recordStartSample: SampleTime = 0 private var recordStartSample: SampleTime = 0
/// Sample time playback began looping (play-head at frame 0) — the timeline anchor.
private var playStartSample: SampleTime = 0
/// Length of the closed loop in frames (`0` until a take is recorded).
private var loopFrames: Int = 0
/// Length of the closed loop in whole beats (`0` until a beat-quantized take is closed).
private var loopBeats: Double = 0.0
/// Snapshot of the loop taken when overdub was last engaged, for ``undoOverdub()``.
private var overdubUndoSnapshot: [Double]?
/// Background routine that waits for the next beat before applying a transport action. /// Background routine that waits for the next beat before applying a transport action.
/// Stopped (non-blocking) before starting a new one, and torn down on ``resetLoop()``.
private var transportRoutine: LyrebirdRoutine? private var transportRoutine: LyrebirdRoutine?
/// Background routine that defers an undo restore until the RT overdub gate has closed. /// Background routine that defers an undo restore until the RT overdub gate has closed.
private var undoRoutine: LyrebirdRoutine? private var undoRoutine: LyrebirdRoutine?
/// Monotonic transport-action generation. Bumped on every arm and on ``resetLoop()``; a /// Background routine that waits for the loop boundary before an armed "stop at end".
/// deferred beat callback carries the generation it was armed under and is dropped if the private var stopRoutine: LyrebirdRoutine?
/// generation has since advanced — so a callback whose action was superseded (a new press,
/// a reset) can never apply to the wrong take. Guards the `DispatchQueue.main.async` hop, /// Monotonic action generation. Bumped on every arm, slot switch, overdub press, and reset;
/// which `LyrebirdRoutine.stop()` cannot itself cancel once enqueued. /// 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.) /// (internal, not private, only so tests can assert the generation-drop of a stale callback.)
private(set) var transportGeneration: Int = 0 private(set) var transportGeneration: Int = 0
@@ -203,20 +213,30 @@ public final class LooperPedal: Pedal {
] ]
} }
/// Transport row (below the knobs): the two state toggles flank the two stops.
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] { public override var effectButtons: [PedalButton] {
[ [
PedalButton(label: "Record / Stop") { [weak self] in self?.toggleRecordStop() }, PedalButton(label: "Record / Stop") { [weak self] in self?.toggleRecordStop() },
PedalButton(label: "Overdub") { [weak self] in self?.toggleOverdub() }, PedalButton(label: "Overdub") { [weak self] in self?.toggleOverdub() },
PedalButton(label: "Undo") { [weak self] in self?.undoOverdub() }, PedalButton(label: "Undo") { [weak self] in self?.undoOverdub() },
PedalButton(label: "Loop", node: $loopOn), PedalButton(label: "Slot") { [weak self] in self?.cycleSlot() },
PedalButton(label: "Reverse", node: $reverse),
PedalButton(label: "Reset") { [weak self] in self?.resetLoop() }, PedalButton(label: "Reset") { [weak self] in self?.resetLoop() },
] ]
} }
// MARK: - UI read-outs // MARK: - UI read-outs
/// Publicly-observable transport phase for the UI (LED colour, armed animation, timeline). /// Publicly-observable transport phase of the active slot (LED colour, armed state, timeline).
public var transportState: LooperTransportState { public var transportState: LooperTransportState {
switch phase { switch phase {
case .empty: return .empty case .empty: return .empty
@@ -224,19 +244,31 @@ public final class LooperPedal: Pedal {
case .recording: return .recording case .recording: return .recording
case .armedStop: return .armedStop case .armedStop: return .armedStop
case .playing: return .playing case .playing: return .playing
case .stopped: return .stopped
} }
} }
/// Closed-loop length in frames (`0` until a take is recorded). /// `true` while a "stop at loop end" is armed and waiting for the boundary.
public var loopFrameCount: Int { loopFrames } public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Closed-loop length in seconds (`0` until a take is recorded). /// Index of the active loop slot, in `0 ..< slotCount`.
public var loopLengthSeconds: Double { Double(loopFrames) / sampleRate } public var activeSlotIndex: Int { activeSlot }
/// Closed-loop length in whole beats (`0` unless the take was beat-quantized). /// `true` if slot `index` holds a recorded loop.
public var loopLengthBeats: Double { loopBeats } public func slotHasContent(_ index: Int) -> Bool {
index >= 0 && index < loopFrames.count && loopFrames[index] > 0
}
/// Normalised play-head position in `[0, 1)` while `.playing`, else `nil`. /// Active-slot loop length in frames (`0` until a take is recorded).
public var loopFrameCount: Int { loopFrames.indices.contains(activeSlot) ? loopFrames[activeSlot] : 0 }
/// Active-slot loop length in seconds.
public var loopLengthSeconds: Double { Double(loopFrameCount) / sampleRate }
/// 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 }
/// 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 /// 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` /// audio play-head regardless of tempo. The player's play-head is reset by a `playTrigger`
@@ -244,13 +276,13 @@ public final class LooperPedal: Pedal {
/// play-head by up to one block (≤ ~11 ms) — imperceptible for a UI sweep. Reverse playback /// 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`. /// is reflected by mirroring the forward progress, matching the player's negated `rate`.
public func playbackPosition01() -> Double? { public func playbackPosition01() -> Double? {
guard phase == .playing, loopFrames > 0, let engine: SynthesisEngine = hostEngine else { guard phase == .playing, loopFrameCount > 0,
return nil let engine: SynthesisEngine = hostEngine,
} playStartSample.indices.contains(activeSlot) else { return nil }
let elapsed: SampleTime = engine.currentTime - playStartSample let elapsed: SampleTime = engine.currentTime - playStartSample[activeSlot]
guard elapsed >= 0 else { return 0.0 } guard elapsed >= 0 else { return 0.0 }
let framesInto: Int = Int(elapsed % SampleTime(loopFrames)) let framesInto: Int = Int(elapsed % SampleTime(loopFrameCount))
let forward: Double = Double(framesInto) / Double(loopFrames) let forward: Double = Double(framesInto) / Double(loopFrameCount)
return reverse >= 0.5 ? (1.0 - forward) : forward return reverse >= 0.5 ? (1.0 - forward) : forward
} }
@@ -258,37 +290,50 @@ public final class LooperPedal: Pedal {
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate) let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
loopBuffer = buffer
let primary: RecordBuffer.Audio = RecordBuffer.Audio( for i: Int in 0 ..< LooperPedal.slotCount {
input: dry, let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffer: buffer, buffers.append(buffer)
loop: false,
doneAction: .nothing
)
primary.run = 0.0
primaryRecorder = primary
let overdub: RecordBuffer.Audio = RecordBuffer.Audio( let primary: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry, input: dry,
buffer: buffer, buffer: buffer,
loop: true, loop: false,
doneAction: .nothing doneAction: .nothing
) )
// Live-gated: only writes while a loop exists and overdub is switched on. The existing primary.run = 0.0
// loop content is scaled by `feedback` on each pass (1.0 = keep, < 1.0 = decay). primaryRecorders.append(primary)
overdub.$run.source = $overdubOn * $isPlaying
overdub.$recLevel.source = DbAmp.Control($overdubLevel) // Active-slot gate: `1` only for slot 0 at build (the default active slot).
overdub.$preLevel.source = $feedback let activeAtBuild: Double = i == activeSlot ? 1.0 : 0.0
overdubRecorder = overdub let gate: ParameterNode = ParameterNode(activeAtBuild)
slotGateNodes.append(gate)
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
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
overdubRecorders.append(overdub)
}
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`. // Playback rate: forward at +1, reverse at −1, switched live off `$reverse`.
let playbackRate: any ValidGeneratorInput = let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio( let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer, buffer: buffers[activeSlot],
loop: true, loop: true,
interpolation: .cubic, interpolation: .cubic,
rate: playbackRate, rate: playbackRate,
@@ -297,33 +342,101 @@ public final class LooperPedal: Pedal {
) )
player = loopPlayer player = loopPlayer
// Loop audible only while playing and not muted; smoothed to avoid clicks on either // Loop audible only while playing and not muted; smoothed to avoid clicks.
// the record→play handoff or a loopOn toggle.
let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn
let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime) let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime)
let unityGain: Double = 1.0 let unityGain: Double = 1.0
let dryGate: any ValidGeneratorInput = unityGain - smoothedGate let dryGate: any ValidGeneratorInput = unityGain - smoothedGate
return (primary * dryGate) + (loopPlayer * 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)
} }
// MARK: - Transport // MARK: - Transport
/// `.empty` → arms/begins recording. `.recording` → closes the loop and starts looping. /// `.empty` → arm/begin recording the active slot. `.recording` → close the loop and start
/// No-op while `.playing` or already armed. /// looping. No-op while `.playing` or already armed.
public func toggleRecordStop() { public func toggleRecordStop() {
switch phase { switch phase {
case .empty: case .empty:
armRecording() armRecording()
case .recording: case .recording:
armStopAndPlay() armStopAndPlay()
case .stopped:
resumePlayback()
case .armedRecord, .armedStop, .playing: case .armedRecord, .armedStop, .playing:
break break
} }
} }
/// Toggles the overdub gate. Engaging it (off → on) first snapshots the current loop so /// Immediately halts loop playback of the active slot. The recorded content is retained —
/// ``undoOverdub()`` can revert the pass. /// press Record / Stop (or switch slots) to start it again. Cancels any armed "stop at end".
public func stopPlayback() {
guard phase == .playing else { return }
transportGeneration += 1
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
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.
public func toggleStopAtLoopEnd() {
if isStopAtLoopEndArmed {
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
transportGeneration += 1
return
}
guard phase == .playing, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) 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
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
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() { public func toggleOverdub() {
// Any overdub press supersedes a pending deferred action (e.g. an in-flight undo // 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 // restore) — advance the generation so that stale callback is dropped, and stop the
@@ -336,23 +449,22 @@ public final class LooperPedal: Pedal {
overdubOn = engaging ? 1.0 : 0.0 overdubOn = engaging ? 1.0 : 0.0
} }
/// Restores the loop to the snapshot captured when overdub was last engaged. No-op if no /// Restores the active slot to the snapshot captured when overdub was last engaged. No-op if
/// snapshot exists. Disengages overdub, then restores the buffer only once the RT overdub /// no snapshot exists. Disengages overdub, then restores the buffer only once the RT overdub
/// writer has actually stopped, so the main-thread bulk write can't race the RT thread's /// writer has actually stopped, so the main-thread bulk write can't race the RT thread.
/// lock-free writes into the same buffer.
public func undoOverdub() { public func undoOverdub() {
guard let buffer: LyrebirdBuffer = loopBuffer, guard buffers.indices.contains(activeSlot),
let snapshot: [Double] = overdubUndoSnapshot, let snapshot: [Double] = overdubUndoSnapshots[activeSlot],
snapshot.count <= buffer.totalSampleCount else { return } snapshot.count <= buffers[activeSlot].totalSampleCount else { return }
overdubOn = 0.0 overdubOn = 0.0
// Advance the generation and capture it: a later reset / new take / overdub press bumps // Advance and capture the generation: a later reset / new take / slot switch / overdub
// the generation and drops this restore, so it can never stomp a buffer the user has // press bumps it and drops this restore, so it can't stomp a buffer since changed.
// since cleared or re-recorded.
transportGeneration += 1 transportGeneration += 1
let generation: Int = transportGeneration let generation: Int = transportGeneration
let slot: Int = activeSlot
guard let engine: SynthesisEngine = hostEngine else { guard let engine: SynthesisEngine = hostEngine else {
// No engine (standalone / headless tests): single-threaded, restore immediately. // No engine (standalone / headless tests): single-threaded, restore immediately.
applyUndoRestore(snapshot, generation: generation) applyUndoRestore(snapshot, slot: slot, generation: generation)
return return
} }
// Overdub's `run` gate ramps to zero over one control block, so the recorder may write // Overdub's `run` gate ramps to zero over one control block, so the recorder may write
@@ -361,61 +473,123 @@ public final class LooperPedal: Pedal {
let target: SampleTime = engine.currentTime + SampleTime(LooperPedal.undoGuardFrames) let target: SampleTime = engine.currentTime + SampleTime(LooperPedal.undoGuardFrames)
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target) try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyUndoRestore(snapshot, generation: generation) } DispatchQueue.main.async { self?.applyUndoRestore(snapshot, slot: slot, generation: generation) }
} }
undoRoutine = routine undoRoutine = routine
routine.start(engine: engine) routine.start(engine: engine)
} }
/// Writes an undo snapshot back into the loop buffer, unless its generation has been /// Writes an undo snapshot back into slot `slot`'s buffer, unless its generation has been
/// superseded by a reset, a new take, or a subsequent overdub/undo press. /// superseded by a reset, a new take, a slot switch, or a subsequent overdub/undo press.
func applyUndoRestore(_ snapshot: [Double], generation: Int) { func applyUndoRestore(_ snapshot: [Double], slot: Int, generation: Int) {
guard generation == transportGeneration, guard generation == transportGeneration,
let buffer: LyrebirdBuffer = loopBuffer, buffers.indices.contains(slot),
snapshot.count <= buffer.totalSampleCount else { return } snapshot.count <= buffers[slot].totalSampleCount else { return }
buffer.setRangeValues(snapshot, startingAt: 0) buffers[slot].setRangeValues(snapshot, startingAt: 0)
} }
/// Clears the loop and returns to `.empty`, ready for a fresh take. /// 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.
public func resetLoop() { public func resetLoop() {
// Stop (non-blocking) any pending transport/undo routines and advance the generation // Stop (non-blocking) any pending routines and advance the generation so an enqueued
// so an already-enqueued beat callback is dropped rather than applied to the new take. // beat/undo callback is dropped rather than applied to the new take.
transportRoutine?.stop() transportRoutine?.stop()
transportRoutine = nil transportRoutine = nil
undoRoutine?.stop() undoRoutine?.stop()
undoRoutine = nil undoRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
stoppedIndicator = 0.0
transportGeneration += 1 transportGeneration += 1
primaryRecorder?.run = 0.0
primaryRecorder?.requestReset() if primaryRecorders.indices.contains(activeSlot) {
overdubRecorder?.requestReset() primaryRecorders[activeSlot].run = 0.0
if let buffer: LyrebirdBuffer = loopBuffer { primaryRecorders[activeSlot].requestReset()
buffer.clear() }
buffer.setLoopLength(buffer.count) if overdubRecorders.indices.contains(activeSlot) {
overdubRecorders[activeSlot].requestReset()
}
if buffers.indices.contains(activeSlot) {
buffers[activeSlot].clear()
buffers[activeSlot].setLoopLength(buffers[activeSlot].count)
} }
isPlaying = 0.0 isPlaying = 0.0
overdubOn = 0.0 overdubOn = 0.0
loopOn = 1.0 loopOn = 1.0
playTrigger = 0.0 playTrigger = 0.0
loopFrames = 0 if loopFrames.indices.contains(activeSlot) { loopFrames[activeSlot] = 0 }
loopBeats = 0.0 if loopBeats.indices.contains(activeSlot) { loopBeats[activeSlot] = 0.0 }
overdubUndoSnapshot = nil if overdubUndoSnapshots.indices.contains(activeSlot) { overdubUndoSnapshots[activeSlot] = nil }
phase = .empty phase = .empty
} }
// MARK: - Transport helpers // MARK: - Transport helpers
/// Snapshots the closed-loop content into `overdubUndoSnapshot`. Called with overdub off, /// Snapshots the active slot's closed-loop content into `overdubUndoSnapshots`. Called with
/// so only the loop player reads the buffer concurrently (a lock-free read is safe). /// overdub off, so only the loop player reads the buffer concurrently (a lock-free read is safe).
private func captureOverdubSnapshot() { private func captureOverdubSnapshot() {
guard let buffer: LyrebirdBuffer = loopBuffer, loopFrames > 0 else { return } guard buffers.indices.contains(activeSlot), loopFrameCount > 0 else { return }
// Mono buffer: linear storage index == frame index. Called with overdub off (only the let buffer: LyrebirdBuffer = buffers[activeSlot]
// player reads concurrently), so a lock-free read of the storage is safe. // Mono buffer: linear storage index == frame index.
let frameCount: Int = min(loopFrames, buffer.totalSampleCount) let frameCount: Int = min(loopFrameCount, buffer.totalSampleCount)
var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount) var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount)
for i: Int in 0 ..< frameCount { for i: Int in 0 ..< frameCount {
snapshot[i] = buffer[i] snapshot[i] = buffer[i]
} }
overdubUndoSnapshot = snapshot overdubUndoSnapshots[activeSlot] = snapshot
}
/// 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 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 }
self.playTrigger = 1.0
}
} }
/// A transport transition deferred to a beat boundary. /// A transport transition deferred to a beat boundary.
@@ -436,9 +610,8 @@ public final class LooperPedal: Pedal {
runQuantized(.finishStop) runQuantized(.finishStop)
} }
/// Applies `action` on the main thread once the clock reaches the next beat, via a /// Applies `action` on the main thread once the clock reaches the next beat, via a background
/// background wait routine. With no clock/engine, applies it synchronously for /// wait routine. With no clock/engine, applies it synchronously for un-quantized transport.
/// un-quantized transport (and headless tests).
private func runQuantized(_ action: QuantizedAction) { private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1 transportGeneration += 1
let generation: Int = transportGeneration let generation: Int = transportGeneration
@@ -459,7 +632,7 @@ public final class LooperPedal: Pedal {
} }
/// Runs the deferred transport transition (on the main thread), unless its generation has /// Runs the deferred transport transition (on the main thread), unless its generation has
/// been superseded by a newer arm or a reset. /// been superseded by a newer arm, a slot switch, or a reset.
private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) { private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
guard generation == transportGeneration else { return } guard generation == transportGeneration else { return }
switch action { switch action {
@@ -469,16 +642,17 @@ public final class LooperPedal: Pedal {
} }
func beginRecording(at beatSample: SampleTime?) { func beginRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord else { return } guard phase == .armedRecord, primaryRecorders.indices.contains(activeSlot) else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0) recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
primaryRecorder?.run = 1.0 primaryRecorders[activeSlot].run = 1.0
phase = .recording phase = .recording
} }
func finishRecordingAndPlay(at beatSample: SampleTime?) { func finishRecordingAndPlay(at beatSample: SampleTime?) {
guard phase == .armedStop, guard phase == .armedStop, primaryRecorders.indices.contains(activeSlot),
let primary: RecordBuffer.Audio = primaryRecorder, buffers.indices.contains(activeSlot) else { return }
let buffer: LyrebirdBuffer = loopBuffer else { return } let primary: RecordBuffer.Audio = primaryRecorders[activeSlot]
let buffer: LyrebirdBuffer = buffers[activeSlot]
primary.run = 0.0 primary.run = 0.0
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0) let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
@@ -486,16 +660,16 @@ public final class LooperPedal: Pedal {
// Beat-quantized: loop length is the exact whole-beat span between the two beat // Beat-quantized: loop length is the exact whole-beat span between the two beat
// boundaries, independent of any recording-position snapshot slop. // boundaries, independent of any recording-position snapshot slop.
let spanFrames: Int = Int(closeSample - recordStartSample) let spanFrames: Int = Int(closeSample - recordStartSample)
loopFrames = max(LooperPedal.minimumLoopFrames, spanFrames) loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, spanFrames)
loopBeats = beatsForSpan(frames: loopFrames, clock: clock) loopBeats[activeSlot] = beatsForSpan(frames: loopFrames[activeSlot], clock: clock)
} else { } else {
// Un-quantized fallback: trim to the recorder's frame count. // Un-quantized fallback: trim to the recorder's frame count.
loopFrames = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount) loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
loopBeats = 0.0 loopBeats[activeSlot] = 0.0
} }
buffer.setLoopLength(loopFrames) buffer.setLoopLength(loopFrames[activeSlot])
playStartSample = closeSample playStartSample[activeSlot] = closeSample
playTrigger = 1.0 playTrigger = 1.0
isPlaying = 1.0 isPlaying = 1.0
phase = .playing phase = .playing
@@ -27,4 +27,7 @@ public enum LooperTransportState: Sendable, Equatable {
/// Looping playback of the recorded take (overdub / reverse / mute apply here). /// Looping playback of the recorded take (overdub / reverse / mute apply here).
case playing case playing
/// Playback halted by a stop, but a recorded loop is still loaded (ready to resume).
case stopped
} }
@@ -31,6 +31,14 @@ struct LooperTimelineView: View {
private static let lengthLabelOpacity: Double = 0.75 private static let lengthLabelOpacity: Double = 0.75
private static let emptyLedBrightness: Double = 0.3 private static let emptyLedBrightness: Double = 0.3
private static let borderLineWidth: CGFloat = 1 private static let borderLineWidth: CGFloat = 1
private static let slotDotSpacing: CGFloat = 4
private static let slotDotDiameter: CGFloat = 18
private static let slotLabelFontSize: CGFloat = 10
private static let slotDotBrightness: Double = 0.16
private static let slotFilledOpacity: Double = 0.55
private static let slotEmptyOpacity: Double = 0.45
private static let slotActiveRingWidth: CGFloat = 1.5
private static let slotLabels: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
// MARK: - Properties // MARK: - Properties
@@ -40,6 +48,9 @@ struct LooperTimelineView: View {
@State private var state: LooperTransportState = .empty @State private var state: LooperTransportState = .empty
@State private var lengthSeconds: Double = 0.0 @State private var lengthSeconds: Double = 0.0
@State private var lengthBeats: Double = 0.0 @State private var lengthBeats: Double = 0.0
@State private var activeSlot: Int = 0
@State private var slotContent: [Bool] = Array(repeating: false, count: LooperPedal.slotCount)
@State private var stopArmed: Bool = false
init(pedal: LooperPedal) { init(pedal: LooperPedal) {
self.pedal = pedal self.pedal = pedal
@@ -52,6 +63,8 @@ struct LooperTimelineView: View {
HStack(spacing: LooperTimelineView.sectionSpacing) { HStack(spacing: LooperTimelineView.sectionSpacing) {
stateBadge stateBadge
Spacer(minLength: 0) Spacer(minLength: 0)
slotDots
Spacer(minLength: 0)
lengthLabel lengthLabel
} }
track track
@@ -63,6 +76,9 @@ struct LooperTimelineView: View {
state = pedal.transportState state = pedal.transportState
lengthSeconds = pedal.loopLengthSeconds lengthSeconds = pedal.loopLengthSeconds
lengthBeats = pedal.loopLengthBeats lengthBeats = pedal.loopLengthBeats
activeSlot = pedal.activeSlotIndex
slotContent = (0 ..< LooperPedal.slotCount).map { pedal.slotHasContent($0) }
stopArmed = pedal.isStopAtLoopEndArmed
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds) try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
} }
} }
@@ -70,6 +86,29 @@ struct LooperTimelineView: View {
// MARK: - Subviews // MARK: - Subviews
/// One labelled dot per slot: filled when it holds a loop, ringed when it is the active slot.
private var slotDots: some View {
HStack(spacing: LooperTimelineView.slotDotSpacing) {
ForEach(0 ..< LooperPedal.slotCount, id: \.self) { index in
let isActive: Bool = index == activeSlot
let hasContent: Bool = index < slotContent.count && slotContent[index]
Text(LooperTimelineView.slotLabels[index])
.font(.system(size: LooperTimelineView.slotLabelFontSize,
weight: .bold, design: .monospaced))
.foregroundStyle(hasContent ? Color.white : Color.white.opacity(LooperTimelineView.slotEmptyOpacity))
.frame(width: LooperTimelineView.slotDotDiameter, height: LooperTimelineView.slotDotDiameter)
.background(
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.slotFilledOpacity)
: Color(white: LooperTimelineView.slotDotBrightness))
)
.overlay(
Circle().stroke(isActive ? Color.white : Color.clear,
lineWidth: LooperTimelineView.slotActiveRingWidth)
)
}
}
}
private var stateBadge: some View { private var stateBadge: some View {
HStack(spacing: LooperTimelineView.badgeInnerSpacing) { HStack(spacing: LooperTimelineView.badgeInnerSpacing) {
Circle() Circle()
@@ -78,6 +117,11 @@ struct LooperTimelineView: View {
Text(stateText) Text(stateText)
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced)) .font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
if stopArmed {
Text("→END")
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.orange)
}
} }
} }
@@ -122,6 +166,7 @@ struct LooperTimelineView: View {
case .armedRecord, .armedStop: return Color.orange case .armedRecord, .armedStop: return Color.orange
case .recording: return Color.red case .recording: return Color.red
case .playing: return Color.green case .playing: return Color.green
case .stopped: return Color.orange
} }
} }
@@ -132,6 +177,7 @@ struct LooperTimelineView: View {
case .recording: return "REC" case .recording: return "REC"
case .armedStop: return "END" case .armedStop: return "END"
case .playing: return "PLAY" case .playing: return "PLAY"
case .stopped: return "STOP"
} }
} }
@@ -39,7 +39,21 @@ public struct PedalButtonView: View {
public var body: some View { public var body: some View {
switch pedalButton.style { switch pedalButton.style {
case .momentary: case .momentary:
ParameterButton(pedalButton.label, action: pedalButton.action ?? {}) if let indicator: UIParamNode = pedalButton.indicator {
// LED + footswitch, same look as a toggle, but the press runs an action and the
// LED reflects a separate state node (e.g. Stop lit while stopped). Reading
// `indicator.value` registers this view for @Observable re-render.
let isOn: Bool = indicator.value >= PedalButtonView.toggleOnThreshold
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(action: pedalButton.action ?? {})
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
}
} else {
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
}
case .toggle: case .toggle:
if let node: UIParamNode = pedalButton.node { if let node: UIParamNode = pedalButton.node {
// Reading `node.value` registers this view for @Observable re-render. // Reading `node.value` registers this view for @Observable re-render.
+50 -18
View File
@@ -132,9 +132,10 @@ struct LEDIndicator: View {
// MARK: - Footswitch // MARK: - Footswitch
/// A round footswitch-style button that flips a `UIParamNode` between `0` and `1`. /// A round footswitch-style button. Either flips a bound `UIParamNode` between `0` and `1`
/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can /// (toggle) or runs an arbitrary action (momentary) — both render the identical stompbox look.
/// reuse the same stompbox footswitch look for non-bypass toggles. /// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can reuse
/// it for non-bypass toggles and momentary stomp actions.
struct FootswitchButton: View { struct FootswitchButton: View {
private static let diameter: CGFloat = 44 private static let diameter: CGFloat = 44
@@ -144,14 +145,23 @@ struct FootswitchButton: View {
private static let ringBrightness: Double = 0.50 private static let ringBrightness: Double = 0.50
private static let innerFillBrightness: Double = 0.25 private static let innerFillBrightness: Double = 0.25
let node: UIParamNode private let action: () -> Void
/// Flips `node` between `0` and `1` on each press.
init(node: UIParamNode) {
self.action = {
let engaged: Bool = node.value < 0.5
node.update(engaged ? 1.0 : 0.0)
}
}
/// Runs `action` on each press (momentary).
init(action: @escaping () -> Void) {
self.action = action
}
var body: some View { var body: some View {
Button(action: { Button(action: action) {
let engaged: Bool = node.value < 0.5
// Toggle: engaged (0) → bypassed (1) and vice-versa.
node.update(engaged ? 1.0 : 0.0)
}) {
ZStack { ZStack {
Circle() Circle()
.fill(Color(white: FootswitchButton.outerFillBrightness)) .fill(Color(white: FootswitchButton.outerFillBrightness))
@@ -207,6 +217,8 @@ public struct PedalView: View {
private static let enclosurePadding: CGFloat = 14 private static let enclosurePadding: CGFloat = 14
private static let screwInset: CGFloat = 6 private static let screwInset: CGFloat = 6
private static let knobColumnCount: Int = 3 private static let knobColumnCount: Int = 3
/// Knob columns for a double-width pedal card (fits a four-knob effect bank on one row).
private static let wideKnobColumnCount: Int = 4
private static let knobSpacing: CGFloat = 10 private static let knobSpacing: CGFloat = 10
/// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred /// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred
/// rows keep a comfortable, touch-friendly gap between adjacent knobs. /// rows keep a comfortable, touch-friendly gap between adjacent knobs.
@@ -297,6 +309,7 @@ public struct PedalView: View {
knobGrid knobGrid
selectorRow selectorRow
switchRow switchRow
transportButtonRow
buttonRow buttonRow
sliderBank(sliders) sliderBank(sliders)
Spacer(minLength: 0) Spacer(minLength: 0)
@@ -367,24 +380,25 @@ public struct PedalView: View {
/// `Level` on the left, `Mix` on the right — leaving more room for the effect controls /// `Level` on the left, `Mix` on the right — leaving more room for the effect controls
/// at the top and giving every pedal a symmetric footer. /// at the top and giving every pedal a symmetric footer.
private var knobGrid: some View { private var knobGrid: some View {
// Wide (double-width) pedals fit four knobs across, so a four-knob effect bank (e.g.
// the looper's Crossfade / Playback / Overdub / Feedback) sits on one row.
let columns: Int = pedal.widthUnits >= 2 ? PedalView.wideKnobColumnCount : PedalView.knobColumnCount
let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2)) let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2))
let rows: [[PedalKnob]] = stride( let rows: [[PedalKnob]] = stride(
from: 0, from: 0,
to: knobs.count, to: knobs.count,
by: PedalView.knobColumnCount by: columns
).map { startIndex in ).map { startIndex in
Array(knobs[startIndex ..< min(startIndex + PedalView.knobColumnCount, knobs.count)]) Array(knobs[startIndex ..< min(startIndex + columns, knobs.count)])
} }
return VStack(spacing: PedalView.knobSpacing) { return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
let row: [PedalKnob] = rowPair.element let row: [PedalKnob] = rowPair.element
// Centre each row: a short row (one or two knobs) sits centred in the // Centre each row: a short row sits centred in the enclosure rather than
// enclosure rather than left-aligned. Symmetric spacers also centre a full // left-aligned. A full row keeps the tight spacing so it fits the enclosure;
// three-knob row, so every row stays horizontally centred.
// A full three-knob row keeps the tight spacing so it fits the enclosure;
// shorter centred rows use a wider, touch-friendly gap. // shorter centred rows use a wider, touch-friendly gap.
let rowItemSpacing: CGFloat = row.count >= PedalView.knobColumnCount let rowItemSpacing: CGFloat = row.count >= columns
? PedalView.knobSpacing ? PedalView.knobSpacing
: PedalView.knobRowItemSpacing : PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) { HStack(spacing: rowItemSpacing) {
@@ -430,8 +444,26 @@ public struct PedalView: View {
} }
} }
/// Row of stomp-style action buttons drawn from `pedal.effectButtons`, beneath the /// Transport-control row drawn from `pedal.effectTransportButtons`, placed directly below
/// switch row. Renders nothing when the pedal publishes no buttons. /// the knobs so persistent state toggles and transport stops (e.g. the looper's Loop /
/// Stop / Cue Stop / Reverse) sit apart from the momentary actions. Renders nothing when
/// the pedal publishes no transport buttons.
@ViewBuilder
private var transportButtonRow: some View {
let buttons: [PedalButton] = pedal.effectTransportButtons
if !buttons.isEmpty {
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of momentary stomp-style action buttons drawn from `pedal.effectButtons`, beneath
/// the transport row. Renders nothing when the pedal publishes no buttons.
@ViewBuilder @ViewBuilder
private var buttonRow: some View { private var buttonRow: some View {
let buttons: [PedalButton] = pedal.effectButtons let buttons: [PedalButton] = pedal.effectButtons
@@ -297,8 +297,11 @@ struct LooperPedalTests {
let pedal: LooperPedal = LooperPedal() let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"]) #expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#expect(pedal.effectSwitches.isEmpty) #expect(pedal.effectSwitches.isEmpty)
// Transport row: Loop / Stop / Cue Stop / Reverse, with the two toggles flanking the stops.
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse"])
#expect(pedal.effectTransportButtons.filter { $0.style == .toggle }.map { $0.label } == ["Loop", "Reverse"])
#expect(pedal.effectButtons.map { $0.label } == #expect(pedal.effectButtons.map { $0.label } ==
["Record / Stop", "Overdub", "Undo", "Loop", "Reverse", "Reset"]) ["Record / Stop", "Overdub", "Undo", "Slot", "Reset"])
} }
@Test func looperIsDoubleWidth() throws { @Test func looperIsDoubleWidth() throws {
@@ -437,6 +440,113 @@ struct LooperPedalTests {
} }
} }
@Test func slotsHoldIndependentLoopsAndSwitch() throws {
let sampleRate: Double = 44100.0
var captured: LooperPedal?
let samples: [Float] = try render(totalDuration: 1.0, sampleRate: sampleRate) { engine, source, pedal, scheduleAction in
captured = pedal
pedal.hostEngine = engine // enable the player buffer swap
pedal.toggleRecordStop() // record slot A (default)
try scheduleAction(0.1) { pedal.toggleRecordStop() } // close A → playing
try scheduleAction(0.12) { source.amplitude = 0.0 } // silence live input
try scheduleAction(0.3) { pedal.selectSlot(1) } // switch to empty slot B
try scheduleAction(0.6) { pedal.selectSlot(0) } // switch back to A
}
let stride: Int = 2
// While parked on empty slot B (input silenced), output should be silent.
let bStart: Int = Int(0.45 * sampleRate) * stride
let bEnd: Int = Int(0.58 * sampleRate) * stride
let onEmptyB: [Float] = Array(samples[bStart ..< min(bEnd, samples.count)])
#expect(!hasNonSilentOutput(onEmptyB), "Empty slot B with silenced input should be silent")
// After switching back to A, its recorded loop should be audible again.
let aStart: Int = Int(0.85 * sampleRate) * stride
let backOnA: [Float] = Array(samples[aStart...])
#expect(hasNonSilentOutput(backOnA), "Switching back to slot A should replay its loop")
let pedal: LooperPedal = try #require(captured)
#expect(pedal.activeSlotIndex == 0)
#expect(pedal.slotHasContent(0))
#expect(!pedal.slotHasContent(1))
}
@Test func cycleSlotWrapsThroughAllSlots() throws {
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(clock) {
#expect(pedal.activeSlotIndex == 0)
for expected: Int in [1, 2, 3, 0] {
pedal.cycleSlot()
#expect(pedal.activeSlotIndex == expected)
}
}
}
@Test func stopPlaybackHaltsAndRecordStopResumes() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil // immediate (un-quantized) transport
pedal.toggleRecordStop() // recording
pedal.toggleRecordStop() // close → playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.playbackPosition01() == nil)
pedal.toggleRecordStop() // Record / Stop resumes from a stopped loop
#expect(pedal.transportState == .playing)
#expect(pedal.isPlaying == 1.0)
} }
}
@Test func stopAtLoopEndArmsAndCancels() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Reach a playing loop through the quantized path.
pedal.toggleRecordStop()
pedal.beginRecording(at: SampleTime(sampleRate * 0.5))
pedal.toggleRecordStop()
pedal.finishRecordingAndPlay(at: SampleTime(sampleRate * 2.5))
#expect(pedal.transportState == .playing)
#expect(!pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed, "first press arms the end-stop")
pedal.toggleStopAtLoopEnd()
#expect(!pedal.isStopAtLoopEndArmed, "second press disarms it")
// An immediate Stop while armed cancels the pending end-stop.
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(!pedal.isStopAtLoopEndArmed)
} }
}
@Test func selectSlotIsNoOpWhileRecording() throws {
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(clock) {
// Drop the clock so transport is immediate (un-quantized): a record press lands
// directly in `.recording` rather than arming for the next beat.
pedal.clock = nil
pedal.toggleRecordStop()
#expect(pedal.transportState == .recording)
// Switching slots must be ignored mid-record — no active-slot change, no phase change.
pedal.selectSlot(1)
#expect(pedal.activeSlotIndex == 0)
#expect(pedal.transportState == .recording)
}
}
@Test func staleUndoRestoreIsDroppedWhenGenerationAdvances() throws { @Test func staleUndoRestoreIsDroppedWhenGenerationAdvances() throws {
let sampleRate: Double = 44100.0 let sampleRate: Double = 44100.0
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) = let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
@@ -457,7 +567,7 @@ struct LooperPedalTests {
// The deferred restore must now be a no-op: it must not reintroduce audio into the // The deferred restore must now be a no-op: it must not reintroduce audio into the
// buffer the user just cleared. // buffer the user just cleared.
pedal.applyUndoRestore(snapshot, generation: staleGeneration) pedal.applyUndoRestore(snapshot, slot: pedal.activeSlotIndex, generation: staleGeneration)
#expect(pedal.transportState == .empty) #expect(pedal.transportState == .empty)
#expect(pedal.loopFrameCount == 0) #expect(pedal.loopFrameCount == 0)
} }