Looper: multitrack redesign with smart Loop footswitch

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 14:24:46 -07:00
parent 465e3e6dfd
commit 3007b76798
8 changed files with 637 additions and 907 deletions
@@ -384,11 +384,11 @@ public final class MIDIController {
let toggleThreshold: Double = 0.5
switch kind {
case .looperRecordStop:
(pedal as? LooperPedal)?.toggleRecordStop()
// The smart Loop footswitch drives record / set-end / overdub / play by state.
(pedal as? LooperPedal)?.pressLoop()
case .looperOverdubToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$overdubOn
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
// Overdub is toggled by the same Loop press once a loop is playing.
(pedal as? LooperPedal)?.pressLoop()
case .looperLoopToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$loopOn
+17 -2
View File
@@ -49,19 +49,32 @@ public struct PedalButton {
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
public let indicator: UIParamNode?
/// Optional live caption describing what the *next* press does, polled by the UI. When set,
/// the button shows this instead of the static `label` — letting a state-driven control (the
/// looper's Loop footswitch) read "Record" → "Set End" → "Overdub" → "Play" as the state
/// changes. `nil` shows the static `label`.
public let dynamicLabel: (() -> String)?
/// Creates a momentary action button.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
/// for a plain button.
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
/// - action: Closure run on each press.
public init(label: String, indicator: UIParamNode? = nil, action: @escaping () -> Void) {
public init(
label: String,
indicator: UIParamNode? = nil,
dynamicLabel: (() -> String)? = nil,
action: @escaping () -> Void
) {
self.label = label
self.style = .momentary
self.node = nil
self.action = action
self.indicator = indicator
self.dynamicLabel = dynamicLabel
}
/// Creates a toggle button bound to a `UIParamNode`.
@@ -70,11 +83,13 @@ public struct PedalButton {
/// - label: Short label shown on the button.
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$overdubOn`, `pedal.$loopOn`, …).
public init(label: String, node: UIParamNode) {
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
public init(label: String, node: UIParamNode, dynamicLabel: (() -> String)? = nil) {
self.label = label
self.style = .toggle
self.node = node
self.action = nil
self.indicator = nil
self.dynamicLabel = dynamicLabel
}
}
+321 -403
View File
@@ -8,187 +8,144 @@ import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A multi-slot loop-recorder pedal: record independent loops into any of several slots, then
/// switch between them, with overdub, overdub-undo, reverse playback, feedback-decay overdub,
/// and a crossfaded total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the
/// transport is beat-quantized — record start and loop close both snap to the next beat, so
/// every loop is a whole number of beats long.
/// A synchronized multitrack loop pedal. Track A's first take defines the master loop length;
/// tracks B–D are overdub layers recorded onto the same grid. All recorded tracks play at once,
/// summed to one output and locked in phase. When the board supplies a tempo ``LyrebirdClock``
/// the master take is beat-quantized so every loop is a whole number of beats long.
///
/// Signal chain (inside `effect(_:)`), per slot `i` plus one shared player:
/// ```
/// dry → RecordBuffer.Audio primary[i] (take capture, run-gated by transport) ─┐ (write only,
/// dry → RecordBuffer.Audio overdub[i] (gated by overdubOn × isPlaying × slot i) │ RootRegistering)
/// buffers[activeSlot] → PlayBuffer.Audio (loop, cubic, rate ±1, swapped ───┤
/// on slot change via setBuffer) │
/// dry ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─────────────────────────┴→ wet
/// ```
/// ## The Loop footswitch drives the transport by state
/// - **Clear** (nothing recorded; only track A selectable): press → record A; press → set the
/// loop end (quantized) and drop into overdub on A when it wraps; press → end overdub, keep
/// playing; further presses toggle overdub ↔ play on the selected track.
/// - **Playing, track B–D selected**: press toggles overdub on that track, aligned to A's
/// play-head. Recording an empty track is just overdub onto silence.
/// - Selecting another track ends any overdub on the previous one (it drops to playback). A
/// newly-selected track records nothing until Loop is pressed.
/// - **Stopped** (via Stop / Cue Stop): press → resume all tracks; next press → toggle overdub.
///
/// A single fixed generator graph is built once. Only one slot records or overdubs at a time
/// (gated so inactive slots keep their content); the shared player's source buffer is swapped
/// to the active slot with ``PlayBuffer/Audio/setBuffer(_:engine:)``. Every transport action is
/// a live parameter change the graph already reads each block, plus explicit methods for the
/// genuine non-RT side effects (clearing a buffer, narrowing `loopLength`, snapshotting for undo,
/// swapping the player's buffer).
///
/// ## Transport (beat-quantized when a clock is present)
/// - ``toggleRecordStop()``: `.empty` → arm/begin recording the active slot; `.recording` →
/// close the loop and start looping. No-op while `.playing` — use ``resetLoop()``.
/// - ``selectSlot(_:)`` / ``cycleSlot()``: switch the active slot. A recorded slot resumes
/// looping from its head; an empty slot is silent and ready to record.
/// - `overdubOn` (via ``toggleOverdub()``): layers input onto the active slot; engaging it
/// first snapshots the loop so ``undoOverdub()`` can revert the pass.
/// - `loopOn` / `reverse` (switches): crossfaded mute / live playback-direction flip.
/// - ``resetLoop()``: clears the active slot and returns it to `.empty`.
///
/// ## Knobs
/// - `crossfadeTime`, `playbackLevel`, `overdubLevel`, `feedback` (see the property docs).
/// ## Audio graph (built once in `effect(_:)`)
/// One `PlayBuffer` per track, all summed; one always-running overdub `RecordBuffer` per track
/// whose `recLevel` is gated so only the selected, overdubbing track layers new input; a
/// non-looping master recorder for track A's length-defining take. The overdub recorders run
/// continuously while playing (reset to the top at play-start) so their write head stays locked
/// to the shared play-head — overdub can be toggled on any track without drifting out of phase.
public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-slot looper: record several loops, switch between them, overdub, and reverse."
"Multitrack looper: record track A, then layer synced overdubs on tracks B–D."
}
/// Double-width card: the looper carries a full transport plus a slot strip and timeline.
/// Double-width card: the looper carries a full transport plus a track strip and timeline.
public override var widthUnits: Int { 2 }
// MARK: - Knobs
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
/// A `Lag.Control` 60 dB settling time, not a fixed-length linear ramp.
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
/// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0
/// Overdub input gain, in dB. Scales only the new material being layered in.
/// Overdub input gain, in dB.
@UIParam public var overdubLevel: Double = 0.0
/// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0`
/// keeps prior layers indefinitely; lower values fade them for a decaying feedback loop.
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
/// layers indefinitely; lower values fade them for a decaying feedback loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Overdub gate. `0` = off, `1` = on. Live-gated — affects only the active, playing slot.
@UIParam public var overdubOn: Double = 0.0
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
@UIParam public var reverse: Double = 0.0
// MARK: - Internal live state
// MARK: - Internal live state (read by the audio graph / UI LEDs)
/// `1` while the active slot is looping playback, else `0`. Read by the audio graph.
/// `1` while the loop bank is playing, else `0`. Gates the whole player sum and the overdub
/// recorders' `run`.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close / slot switch.
/// Play-head reset trigger for every player. Pulsed `0 → 1` at play-start so all tracks
/// start phase-aligned to frame 0.
@UIParam public var playTrigger: Double = 0.0
/// LED state for the Stop footswitch: `1` while a recorded loop is halted, else `0`.
/// LED state for the Stop footswitch: `1` while stopped, else `0`.
@UIParam public var stoppedIndicator: Double = 0.0
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed, else `0`.
/// Also the single source of truth for ``isStopAtLoopEndArmed``.
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed.
@UIParam public var cueStopArmed: Double = 0.0
/// LED state for the Loop footswitch: `1` while overdubbing a track.
@UIParam public var overdubIndicator: Double = 0.0
// MARK: - Constants
/// Number of independent loop slots. Each slot allocates its own `maxDurationSeconds`
/// buffer, so per-instance memory is roughly `slotCount × maxDurationSeconds × sampleRate ×
/// 8 bytes` (≈ 21 MB per slot at 44.1 kHz / 60 s — ~85 MB for four). Raise with that in mind.
public static let slotCount: Int = 4
/// Number of loop tracks (A–D).
public static let trackCount: Int = 4
/// Maximum recordable take length per slot, in seconds.
/// Maximum recordable master length, in seconds (each track allocates a buffer this long, so
/// per-instance memory is roughly `trackCount × maxDurationSeconds × sampleRate × 8 bytes`).
private static let maxDurationSeconds: Double = 60.0
/// Default crossfade duration, in seconds.
private static let defaultCrossfadeTime: Double = 0.05
/// Bipolar span mapping `reverse ∈ {0, 1}` to a playback rate of `{+1, −1}`.
private static let reverseRateSpan: Double = 2.0
/// Forward playback rate, and the rate offset the reverse span is subtracted from.
private static let forwardRate: Double = 1.0
/// Smallest permitted loop length, in frames, so a degenerate take can't divide by zero.
private static let minimumLoopFrames: Int = 1
/// Frames to wait after disabling overdub before restoring an undo snapshot, so the RT-side
/// overdub writer (its `run` gate ramps closed over one control block) has fully stopped
/// writing the loop buffer before the main thread overwrites it. Two maximum blocks.
private static let undoGuardFrames: Int = 1024
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffers + generators (one set per slot, one shared player)
// MARK: - Buffers + generators
/// Per-slot loop buffers, sized to `maxDurationSeconds`. Allocated in `effect(_:)` because
/// `sampleRate` is only set by `PedalBoard.add(_:)` after construction.
private var buffers: [LyrebirdBuffer] = []
private var primaryRecorders: [RecordBuffer.Audio] = []
private var players: [PlayBuffer.Audio] = []
private var overdubRecorders: [RecordBuffer.Audio] = []
private var overdubGates: [ParameterNode] = []
/// Per-slot overdub gate (`1` for the active slot, `0` otherwise), multiplied into each
/// overdub recorder's `run` so only the active slot layers new material.
private var slotGateNodes: [ParameterNode] = []
/// The shared player. Its source buffer is swapped to the active slot on ``selectSlot(_:)``.
private var player: PlayBuffer.Audio?
// MARK: - Per-slot state
private var activeSlot: Int = 0
/// Closed-loop length, in frames, per slot (`0` = empty).
private var loopFrames: [Int] = []
/// Closed-loop length, in whole beats, per slot (`0` unless beat-quantized).
private var loopBeats: [Double] = []
/// Sample time playback began looping (play-head at frame 0), per slot — timeline anchor.
private var playStartSample: [SampleTime] = []
/// Undo snapshot per slot, captured when overdub was last engaged on that slot.
private var overdubUndoSnapshots: [[Double]?] = []
/// Non-looping recorder for track A's length-defining first take.
private var masterRecorder: RecordBuffer.Audio?
// MARK: - Transport state
private enum Phase {
case empty
case clear
case armedRecord
case recording
case armedStop
case recordingMaster
case armedClose
case playing
case stopped
}
/// Transport phase of the *active* slot.
private var phase: Phase = .empty
private var phase: Phase = .clear
/// Beat-boundary sample time at which the active slot started recording.
/// The track the Loop footswitch records / overdubs into (`0` = A).
private var selectedTrack: Int = 0
/// The track currently overdubbing, or `nil` when just playing.
private var overdubbingTrack: Int?
/// `true` once a track holds recorded material.
private var trackHasContent: [Bool] = []
/// Master loop length in frames (`0` until track A is closed).
private var masterLength: Int = 0
/// Master loop length in whole beats (`0` unless beat-quantized).
private var masterBeats: Double = 0.0
/// Sample time at which the master take began recording, and at which playback last (re)started.
private var recordStartSample: SampleTime = 0
private var playStartSample: SampleTime = 0
/// Background routine that waits for the next beat before applying a transport action.
private var transportRoutine: LyrebirdRoutine?
/// Background routine that defers an undo restore until the RT overdub gate has closed.
private var undoRoutine: LyrebirdRoutine?
/// Background routine that waits for the loop boundary before an armed "stop at end".
private var stopRoutine: LyrebirdRoutine?
/// Monotonic action generation. Bumped on every arm, slot switch, overdub press, and reset;
/// a deferred beat/undo callback carries the generation it was armed under and is dropped if
/// the generation has since advanced — so a superseded callback can never apply to the wrong
/// state. Guards the `DispatchQueue.main.async` hop, which `LyrebirdRoutine.stop()` cannot
/// itself cancel once enqueued.
/// (internal, not private, only so tests can assert the generation-drop of a stale callback.)
/// Monotonic action generation guarding deferred beat/stop callbacks (see the single-track
/// history — `LyrebirdRoutine.stop()` cannot recall an already-enqueued main-thread hop).
private(set) var transportGeneration: Int = 0
// MARK: - Init
@@ -202,7 +159,7 @@ public final class LooperPedal: Pedal {
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / switches / buttons
// MARK: - Knobs / buttons
public override var effectKnobs: [PedalKnob] {
[
@@ -213,101 +170,130 @@ public final class LooperPedal: Pedal {
]
}
/// Transport row (below the knobs): the two state toggles flank the two stops.
/// Transport row: the smart Loop footswitch, the two stops, direction, and reset.
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(label: "Loop", node: $loopOn),
PedalButton(label: "Stop", indicator: $stoppedIndicator) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", node: $reverse),
]
}
/// Momentary action row.
public override var effectButtons: [PedalButton] {
[
PedalButton(label: "Record / Stop") { [weak self] in self?.toggleRecordStop() },
PedalButton(label: "Overdub") { [weak self] in self?.toggleOverdub() },
PedalButton(label: "Undo") { [weak self] in self?.undoOverdub() },
PedalButton(label: "Slot") { [weak self] in self?.cycleSlot() },
PedalButton(label: "Loop", indicator: $overdubIndicator,
dynamicLabel: { [weak self] in self?.loopButtonCaption ?? "Loop" }) { [weak self] in self?.pressLoop() },
PedalButton(label: "Stop", indicator: $stoppedIndicator,
dynamicLabel: { [weak self] in self?.stopButtonCaption ?? "Stop" }) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed,
dynamicLabel: { [weak self] in self?.cueStopButtonCaption ?? "Cue Stop" }) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", node: $reverse,
dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }),
PedalButton(label: "Reset") { [weak self] in self?.resetLoop() },
]
}
// MARK: - UI read-outs
/// Publicly-observable transport phase of the active slot (LED colour, armed state, timeline).
/// Publicly-observable transport phase for the state indicator, LEDs, and timeline.
public var transportState: LooperTransportState {
switch phase {
case .empty: return .empty
case .armedRecord: return .armedRecord
case .recording: return .recording
case .armedStop: return .armedStop
case .playing: return .playing
case .stopped: return .stopped
case .clear: return .clear
case .armedRecord: return .armedRecord
case .recordingMaster: return .recordingMaster
case .armedClose: return .armedClose
case .playing: return .playing
case .stopped: return .stopped
}
}
/// `true` while a "stop at loop end" is armed and waiting for the boundary.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Index of the selected track, `0 ..< trackCount`.
public var selectedTrackIndex: Int { selectedTrack }
/// Index of the active loop slot, in `0 ..< slotCount`.
public var activeSlotIndex: Int { activeSlot }
/// The track currently overdubbing, or `nil`.
public var overdubbingTrackIndex: Int? { overdubbingTrack }
/// `true` if slot `index` holds a recorded loop.
public func slotHasContent(_ index: Int) -> Bool {
index >= 0 && index < loopFrames.count && loopFrames[index] > 0
/// `true` if track `index` holds recorded material.
public func trackHasContent(_ index: Int) -> Bool {
index >= 0 && index < trackHasContent.count && trackHasContent[index]
}
/// Active-slot loop length in frames (`0` until a take is recorded).
public var loopFrameCount: Int { loopFrames.indices.contains(activeSlot) ? loopFrames[activeSlot] : 0 }
/// `true` while a stop-at-loop-end is armed.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Active-slot loop length in seconds.
public var loopLengthSeconds: Double { Double(loopFrameCount) / sampleRate }
/// Master loop length in frames (`0` until track A is closed).
public var loopFrameCount: Int { masterLength }
/// Active-slot loop length in whole beats (`0` unless the take was beat-quantized).
public var loopLengthBeats: Double { loopBeats.indices.contains(activeSlot) ? loopBeats[activeSlot] : 0.0 }
/// Master loop length in seconds.
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
/// Normalised play-head position in `[0, 1)` while the active slot is `.playing`, else `nil`.
///
/// Derived from the engine sample clock and the frame-0 playback anchor, so it tracks the
/// audio play-head regardless of tempo. The player's play-head is reset by a `playTrigger`
/// edge consumed at the next block boundary, so this read-out may lead the true audio
/// play-head by up to one block (≤ ~11 ms) — imperceptible for a UI sweep. Reverse playback
/// is reflected by mirroring the forward progress, matching the player's negated `rate`.
/// Master loop length in whole beats (`0` unless beat-quantized).
public var loopLengthBeats: Double { masterBeats }
/// Normalised play-head position in `[0, 1)` while playing, else `nil`. Shared by all tracks.
public func playbackPosition01() -> Double? {
guard phase == .playing, loopFrameCount > 0,
let engine: SynthesisEngine = hostEngine,
playStartSample.indices.contains(activeSlot) else { return nil }
let elapsed: SampleTime = engine.currentTime - playStartSample[activeSlot]
guard phase == .playing, masterLength > 0, let engine: SynthesisEngine = hostEngine else {
return nil
}
let elapsed: SampleTime = engine.currentTime - playStartSample
guard elapsed >= 0 else { return 0.0 }
let framesInto: Int = Int(elapsed % SampleTime(loopFrameCount))
let forward: Double = Double(framesInto) / Double(loopFrameCount)
let framesInto: Int = Int(elapsed % SampleTime(masterLength))
let forward: Double = Double(framesInto) / Double(masterLength)
return reverse >= 0.5 ? (1.0 - forward) : forward
}
/// Caption for the Loop footswitch describing what the *next* press does.
public var loopButtonCaption: String {
switch phase {
case .clear: return "Record"
case .armedRecord: return "Recording"
case .recordingMaster: return "Set End"
case .armedClose: return "Closing"
case .stopped: return "Play"
case .playing:
if overdubbingTrack == selectedTrack { return "Play" }
return trackHasContent(selectedTrack) ? "Overdub" : "Record"
}
}
/// Caption for the Stop footswitch (what the next press does).
public var stopButtonCaption: String { phase == .stopped ? "Stopped" : "Stop" }
/// Caption for the Cue Stop footswitch.
public var cueStopButtonCaption: String { isStopAtLoopEndArmed ? "Cancel" : "Cue Stop" }
/// Caption for the Reverse footswitch (the direction the next press switches to).
public var reverseButtonCaption: String { reverse >= 0.5 ? "Forward" : "Reverse" }
/// One-line description of what the pedal is doing now, for the state indicator.
public var stateDescription: String {
let armedSuffix: String = isStopAtLoopEndArmed ? " · stop at end" : ""
switch phase {
case .clear: return "Empty — record track A"
case .armedRecord: return "Waiting for beat…"
case .recordingMaster: return "Recording A"
case .armedClose: return "Closing loop…"
case .stopped: return "Stopped"
case .playing:
if let track: Int = overdubbingTrack {
return "Overdubbing \(LooperPedal.trackLabel(track))" + armedSuffix
}
return "Playing" + armedSuffix
}
}
/// The letter for a track index (0 → "A").
public static func trackLabel(_ index: Int) -> String {
let letters: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
return letters.indices.contains(index) ? letters[index] : "?"
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let unity: Double = 1.0
for i: Int in 0 ..< LooperPedal.slotCount {
for _: Int in 0 ..< LooperPedal.trackCount {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffers.append(buffer)
let primary: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: false,
doneAction: .nothing
)
primary.run = 0.0
primaryRecorders.append(primary)
// Active-slot gate: `1` only for slot 0 at build (the default active slot).
let activeAtBuild: Double = i == activeSlot ? 1.0 : 0.0
let gate: ParameterNode = ParameterNode(activeAtBuild)
slotGateNodes.append(gate)
let gate: ParameterNode = ParameterNode(0.0)
overdubGates.append(gate)
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
@@ -315,76 +301,102 @@ public final class LooperPedal: Pedal {
loop: true,
doneAction: .nothing
)
// Live-gated: writes only while this slot is active, playing, and overdub is on.
// Existing content is scaled by `feedback` each pass (1.0 = keep, < 1.0 = decay).
overdub.$run.source = $overdubOn * $isPlaying * gate
overdub.$recLevel.source = DbAmp.Control($overdubLevel)
overdub.$preLevel.source = $feedback
// Always running while playing; its write head stays locked to the shared play-head.
// `recLevel` is zero unless this track is the one being overdubbed; `preLevel` is 1
// (identity — keep existing content) except while overdubbing, when it is `feedback`.
overdub.$run.source = $isPlaying
overdub.$recLevel.source = gate * DbAmp.Control($overdubLevel)
overdub.$preLevel.source = (unity - gate) + gate * $feedback
overdubRecorders.append(overdub)
let player: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
players.append(player)
}
loopFrames = [Int](repeating: 0, count: LooperPedal.slotCount)
loopBeats = [Double](repeating: 0.0, count: LooperPedal.slotCount)
playStartSample = [SampleTime](repeating: 0, count: LooperPedal.slotCount)
overdubUndoSnapshots = [[Double]?](repeating: nil, count: LooperPedal.slotCount)
// Playback rate: forward at +1, reverse at −1, switched live off `$reverse`.
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffers[activeSlot],
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
let master: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffers[0],
loop: false,
doneAction: .nothing
)
player = loopPlayer
master.run = 0.0
masterRecorder = master
// Loop audible only while playing and not muted; smoothed to avoid clicks.
trackHasContent = [Bool](repeating: false, count: LooperPedal.trackCount)
// Loop bank audible only while playing and not muted; smoothed to avoid clicks.
let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn
let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime)
let unityGain: Double = 1.0
let dryGate: any ValidGeneratorInput = unityGain - smoothedGate
let dryGate: any ValidGeneratorInput = unity - smoothedGate
// The recorders are `RootRegistering` and run for their write side effect; the mix is
// the dry passthrough plus the shared player.
return (dry * dryGate) + (loopPlayer * smoothedGate)
// Sum all track players. Empty buffers contribute silence.
var loopSum: any ValidGeneratorInput = players[0]
for i: Int in 1 ..< players.count {
loopSum = loopSum + players[i]
}
return (dry * dryGate) + (loopSum * smoothedGate)
}
// MARK: - Transport
// MARK: - Loop footswitch
/// `.empty` → arm/begin recording the active slot. `.recording` → close the loop and start
/// looping. No-op while `.playing` or already armed.
public func toggleRecordStop() {
/// The smart transport press. Behaviour depends on the current phase and selected track.
public func pressLoop() {
switch phase {
case .empty:
armRecording()
case .recording:
armStopAndPlay()
case .stopped:
resumePlayback()
case .armedRecord, .armedStop, .playing:
case .clear: armMasterRecording()
case .recordingMaster: armCloseMaster()
case .playing: toggleOverdubSelected()
case .stopped: resumePlayback()
case .armedRecord, .armedClose:
break
}
}
/// Immediately halts loop playback of the active slot. The recorded content is retained —
/// press Record / Stop (or switch slots) to start it again. Cancels any armed "stop at end".
/// Selects the active track (the one Loop records / overdubs into). Tapping a timeline dot
/// calls this. Only track A is selectable while clear. Selecting a new track ends any overdub
/// on the previous one (it drops to playback); the new track records nothing until Loop.
public func selectTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, index != selectedTrack, !buffers.isEmpty else { return }
switch phase {
case .clear:
return // only track A while clear
case .armedRecord, .recordingMaster, .armedClose:
return // not mid master-record
case .playing, .stopped:
break
}
if overdubbingTrack != nil {
overdubbingTrack = nil // selecting elsewhere ends the current overdub
}
selectedTrack = index
updateOverdubGates()
}
// MARK: - Stops / reset
/// Immediately halts playback of all tracks; recorded content is retained (resume via Loop).
public func stopPlayback() {
guard phase == .playing else { return }
transportGeneration += 1
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// Arms (or, if already armed, cancels) a stop that fires when the active loop next reaches
/// its end. No-op unless a loop is playing. With no engine to schedule against, stops now.
/// Arms (or cancels) a stop that fires when the loop next reaches its end. No-op unless
/// playing. With no engine to schedule against, stops now.
public func toggleStopAtLoopEnd() {
if isStopAtLoopEndArmed {
stopRoutine?.stop()
@@ -393,18 +405,16 @@ public final class LooperPedal: Pedal {
transportGeneration += 1
return
}
guard phase == .playing, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) else { return }
guard phase == .playing, masterLength > 0 else { return }
transportGeneration += 1
let generation: Int = transportGeneration
guard let engine: SynthesisEngine = hostEngine else {
stopPlayback()
return
}
// Sample time of the next loop boundary after now.
let anchor: SampleTime = playStartSample[activeSlot]
let frames: SampleTime = SampleTime(loopFrameCount)
let elapsed: SampleTime = max(0, engine.currentTime - anchor)
let boundary: SampleTime = anchor + (elapsed / frames + 1) * frames
let frames: SampleTime = SampleTime(masterLength)
let elapsed: SampleTime = max(0, engine.currentTime - playStartSample)
let boundary: SampleTime = playStartSample + (elapsed / frames + 1) * frames
cueStopArmed = 1.0
stopRoutine?.stop()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
@@ -419,172 +429,94 @@ public final class LooperPedal: Pedal {
func applyStopAtLoopEnd(generation: Int) {
guard generation == transportGeneration, phase == .playing else { return }
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// Resumes looping playback of a stopped slot from its head.
private func resumePlayback() {
guard phase == .stopped, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) else { return }
transportGeneration += 1
isPlaying = 1.0
stoppedIndicator = 0.0
phase = .playing
playStartSample[activeSlot] = hostEngine?.currentTime ?? 0
pulsePlayTrigger()
}
/// Toggles the overdub gate on the active slot. Engaging it (off → on) first snapshots the
/// current loop so ``undoOverdub()`` can revert the pass.
public func toggleOverdub() {
// Any overdub press supersedes a pending deferred action (e.g. an in-flight undo
// restore) — advance the generation so that stale callback is dropped, and stop the
// now-superseded undo routine so its background thread doesn't idle-poll to its target.
transportGeneration += 1
undoRoutine?.stop()
undoRoutine = nil
let engaging: Bool = overdubOn < 0.5
if engaging { captureOverdubSnapshot() }
overdubOn = engaging ? 1.0 : 0.0
}
/// Restores the active slot to the snapshot captured when overdub was last engaged. No-op if
/// no snapshot exists. Disengages overdub, then restores the buffer only once the RT overdub
/// writer has actually stopped, so the main-thread bulk write can't race the RT thread.
public func undoOverdub() {
guard buffers.indices.contains(activeSlot),
let snapshot: [Double] = overdubUndoSnapshots[activeSlot],
snapshot.count <= buffers[activeSlot].totalSampleCount else { return }
overdubOn = 0.0
// Advance and capture the generation: a later reset / new take / slot switch / overdub
// press bumps it and drops this restore, so it can't stomp a buffer since changed.
transportGeneration += 1
let generation: Int = transportGeneration
let slot: Int = activeSlot
guard let engine: SynthesisEngine = hostEngine else {
// No engine (standalone / headless tests): single-threaded, restore immediately.
applyUndoRestore(snapshot, slot: slot, generation: generation)
return
}
// Overdub's `run` gate ramps to zero over one control block, so the recorder may write
// for up to a block more. Wait past that before overwriting the buffer.
undoRoutine?.stop()
let target: SampleTime = engine.currentTime + SampleTime(LooperPedal.undoGuardFrames)
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyUndoRestore(snapshot, slot: slot, generation: generation) }
}
undoRoutine = routine
routine.start(engine: engine)
}
/// Writes an undo snapshot back into slot `slot`'s buffer, unless its generation has been
/// superseded by a reset, a new take, a slot switch, or a subsequent overdub/undo press.
func applyUndoRestore(_ snapshot: [Double], slot: Int, generation: Int) {
guard generation == transportGeneration,
buffers.indices.contains(slot),
snapshot.count <= buffers[slot].totalSampleCount else { return }
buffers[slot].setRangeValues(snapshot, startingAt: 0)
}
/// Advances to the next slot (wrapping), as the `Slot` footswitch does.
public func cycleSlot() {
selectSlot((activeSlot + 1) % LooperPedal.slotCount)
}
/// Switches the active slot. A recorded slot resumes looping from its head; an empty slot is
/// silent and ready to record. No-op while recording or armed (finish or reset first).
public func selectSlot(_ index: Int) {
guard index >= 0, index < LooperPedal.slotCount, index != activeSlot,
buffers.indices.contains(index), loopFrames.indices.contains(index) else { return }
guard phase == .empty || phase == .playing || phase == .stopped else { return }
// The RT player's buffer can only be swapped with an engine; without one the switch
// would desync the UI/transport state from the (unchanged) audio, so require it.
guard let engine: SynthesisEngine = hostEngine else { return }
transportGeneration += 1
undoRoutine?.stop()
undoRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
stoppedIndicator = 0.0
overdubOn = 0.0
if slotGateNodes.indices.contains(activeSlot) { slotGateNodes[activeSlot].value = 0.0 }
activeSlot = index
if slotGateNodes.indices.contains(index) { slotGateNodes[index].value = 1.0 }
player?.setBuffer(buffers[index], engine: engine)
if loopFrames[index] > 0 {
isPlaying = 1.0
phase = .playing
playStartSample[index] = engine.currentTime
pulsePlayTrigger()
} else {
isPlaying = 0.0
phase = .empty
playTrigger = 0.0
}
}
/// Clears the active slot and returns it to `.empty`, ready for a fresh take.
/// Returns the pedal to the clear state: all tracks cleared, track A selected, length reset.
/// If sound is playing it acts as an immediate stop-and-clear.
public func resetLoop() {
// Stop (non-blocking) any pending routines and advance the generation so an enqueued
// beat/undo callback is dropped rather than applied to the new take.
transportRoutine?.stop()
transportRoutine = nil
undoRoutine?.stop()
undoRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
stoppedIndicator = 0.0
transportGeneration += 1
if primaryRecorders.indices.contains(activeSlot) {
primaryRecorders[activeSlot].run = 0.0
primaryRecorders[activeSlot].requestReset()
masterRecorder?.run = 0.0
masterRecorder?.requestReset()
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset()
}
if overdubRecorders.indices.contains(activeSlot) {
overdubRecorders[activeSlot].requestReset()
for buffer: LyrebirdBuffer in buffers {
buffer.clear()
buffer.setLoopLength(buffer.count)
}
if buffers.indices.contains(activeSlot) {
buffers[activeSlot].clear()
buffers[activeSlot].setLoopLength(buffers[activeSlot].count)
for i: Int in trackHasContent.indices {
trackHasContent[i] = false
}
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
isPlaying = 0.0
overdubOn = 0.0
loopOn = 1.0
playTrigger = 0.0
if loopFrames.indices.contains(activeSlot) { loopFrames[activeSlot] = 0 }
if loopBeats.indices.contains(activeSlot) { loopBeats[activeSlot] = 0.0 }
if overdubUndoSnapshots.indices.contains(activeSlot) { overdubUndoSnapshots[activeSlot] = nil }
phase = .empty
stoppedIndicator = 0.0
cueStopArmed = 0.0
updateOverdubGates()
phase = .clear
}
// MARK: - Transport helpers
/// Snapshots the active slot's closed-loop content into `overdubUndoSnapshots`. Called with
/// overdub off, so only the loop player reads the buffer concurrently (a lock-free read is safe).
private func captureOverdubSnapshot() {
guard buffers.indices.contains(activeSlot), loopFrameCount > 0 else { return }
let buffer: LyrebirdBuffer = buffers[activeSlot]
// Mono buffer: linear storage index == frame index.
let frameCount: Int = min(loopFrameCount, buffer.totalSampleCount)
var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount)
for i: Int in 0 ..< frameCount {
snapshot[i] = buffer[i]
private func updateOverdubGates() {
for i: Int in overdubGates.indices {
overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0
}
overdubUndoSnapshots[activeSlot] = snapshot
overdubIndicator = overdubbingTrack != nil ? 1.0 : 0.0
}
/// Pulses `playTrigger` `0 → 1` across two run-loop turns so the player sees a clean reset
/// edge even when the trigger was already high (e.g. switching between recorded slots).
private func toggleOverdubSelected() {
if overdubbingTrack == selectedTrack {
overdubbingTrack = nil
} else {
overdubbingTrack = selectedTrack
if trackHasContent.indices.contains(selectedTrack) { trackHasContent[selectedTrack] = true }
}
updateOverdubGates()
}
/// (Re)starts playback of all tracks from the top, optionally overdubbing `overdubTrack`.
private func startPlayback(overdubTrack: Int?, at sample: SampleTime) {
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset() // realign every write head to the top
}
playStartSample = sample
isPlaying = 1.0
stoppedIndicator = 0.0
overdubbingTrack = overdubTrack
if let track: Int = overdubTrack, trackHasContent.indices.contains(track) {
trackHasContent[track] = true
}
updateOverdubGates()
pulsePlayTrigger()
phase = .playing
}
/// Resumes playback of all active tracks from a stopped state.
private func resumePlayback() {
guard phase == .stopped, masterLength > 0 else { return }
transportGeneration += 1
startPlayback(overdubTrack: nil, at: hostEngine?.currentTime ?? 0)
}
/// Pulses `playTrigger` `0 → 1` across two run-loop turns so every player sees a clean reset
/// edge, guarded by the generation so a superseding action drops the delayed edge.
private func pulsePlayTrigger() {
playTrigger = 0.0
// Guard the delayed edge with the generation (bumped by every transport action) so a
// record/reset/switch landing in the async gap can't fire a stale trigger on the player.
let generation: Int = transportGeneration
DispatchQueue.main.async { [weak self] in
guard let self, self.transportGeneration == generation else { return }
@@ -592,26 +524,23 @@ public final class LooperPedal: Pedal {
}
}
/// A transport transition deferred to a beat boundary.
private enum QuantizedAction: Sendable {
case beginRecording
case finishStop
case beginMaster
case closeMaster
}
/// Begins recording immediately, or — with a clock — on the next beat boundary.
private func armRecording() {
private func armMasterRecording() {
selectedTrack = 0 // only track A in the clear state
updateOverdubGates()
phase = .armedRecord
runQuantized(.beginRecording)
runQuantized(.beginMaster)
}
/// Closes the loop immediately, or — with a clock — on the next beat boundary.
private func armStopAndPlay() {
phase = .armedStop
runQuantized(.finishStop)
private func armCloseMaster() {
phase = .armedClose
runQuantized(.closeMaster)
}
/// Applies `action` on the main thread once the clock reaches the next beat, via a background
/// wait routine. With no clock/engine, applies it synchronously for un-quantized transport.
private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1
let generation: Int = transportGeneration
@@ -623,61 +552,50 @@ public final class LooperPedal: Pedal {
let target: SampleTime = clock.nextBeat()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
// The wait runs on a background thread; all pedal state changes hop to main. The
// generation guard drops this callback if the action was superseded before it fires.
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
}
transportRoutine = routine
routine.start(engine: engine)
}
/// Runs the deferred transport transition (on the main thread), unless its generation has
/// been superseded by a newer arm, a slot switch, or a reset.
private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
guard generation == transportGeneration else { return }
switch action {
case .beginRecording: beginRecording(at: beatSample)
case .finishStop: finishRecordingAndPlay(at: beatSample)
case .beginMaster: beginMasterRecording(at: beatSample)
case .closeMaster: closeMasterAndPlay(at: beatSample)
}
}
func beginRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, primaryRecorders.indices.contains(activeSlot) else { return }
func beginMasterRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
primaryRecorders[activeSlot].run = 1.0
phase = .recording
master.run = 1.0
phase = .recordingMaster
}
func finishRecordingAndPlay(at beatSample: SampleTime?) {
guard phase == .armedStop, primaryRecorders.indices.contains(activeSlot),
buffers.indices.contains(activeSlot) else { return }
let primary: RecordBuffer.Audio = primaryRecorders[activeSlot]
let buffer: LyrebirdBuffer = buffers[activeSlot]
primary.run = 0.0
func closeMasterAndPlay(at beatSample: SampleTime?) {
guard phase == .armedClose, let master: RecordBuffer.Audio = masterRecorder, !buffers.isEmpty else { return }
master.run = 0.0
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
if let clock: LyrebirdClock = clock, beatSample != nil {
// Beat-quantized: loop length is the exact whole-beat span between the two beat
// boundaries, independent of any recording-position snapshot slop.
let spanFrames: Int = Int(closeSample - recordStartSample)
loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, spanFrames)
loopBeats[activeSlot] = beatsForSpan(frames: loopFrames[activeSlot], clock: clock)
masterLength = max(LooperPedal.minimumLoopFrames, spanFrames)
masterBeats = beatsForSpan(frames: masterLength, clock: clock)
} else {
// Un-quantized fallback: trim to the recorder's frame count.
loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
loopBeats[activeSlot] = 0.0
masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount)
masterBeats = 0.0
}
buffer.setLoopLength(loopFrames[activeSlot])
playStartSample[activeSlot] = closeSample
playTrigger = 1.0
isPlaying = 1.0
phase = .playing
for buffer: LyrebirdBuffer in buffers {
buffer.setLoopLength(masterLength)
}
if trackHasContent.indices.contains(0) { trackHasContent[0] = true }
// Auto-drop into overdub on track A when the loop wraps to the top.
startPlayback(overdubTrack: 0, at: closeSample)
}
/// Whole-beat length of a `frames`-long span at the clock's *current* tempo. If the tempo
/// changed during the take, `loopFrames` (from raw sample deltas) stays correct while this
/// beat count — a UI read-out only, never audio — may misreport. Acceptable.
/// Whole-beat length of a `frames`-long span at the clock's current tempo (UI read-out only).
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
guard samplesPerBeat > 0 else { return 0.0 }
@@ -4,30 +4,31 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Publicly-observable transport phase of ``LooperPedal``, surfaced for the UI so it can
/// colour the record LED, animate the "waiting for the next beat" armed states, and drive
/// the loop timeline.
/// Publicly-observable transport phase of the multitrack ``LooperPedal``, surfaced for the UI
/// so it can colour the state indicator, animate the "waiting for the next beat" armed states,
/// and drive the loop timeline.
///
/// The two `armed…` cases exist only when the pedal has a tempo ``LyrebirdClock`` — a
/// transport action then waits for the next beat boundary before it takes effect. Without a
/// clock the pedal transitions straight between ``empty``, ``recording`` and ``playing``.
/// The pedal is a synchronized multitrack looper: track A's first take defines the master loop
/// length, and tracks B–D are overdub layers recorded onto the same grid, all playing at once.
public enum LooperTransportState: Sendable, Equatable {
/// No take recorded yet. `Record` begins recording (or arms it, with a clock).
case empty
/// No material recorded on any track. Only track A can be selected; press Loop to record it.
case clear
/// A `Record` has been requested and the pedal is waiting for the next beat to start.
/// A Loop press has been made in the clear state and the pedal is waiting for the next beat
/// to start recording track A.
case armedRecord
/// Actively recording the primary take.
case recording
/// Recording track A's first take, which defines the master loop length.
case recordingMaster
/// A stop has been requested and the pedal is waiting for the next beat to close the loop.
case armedStop
/// A Loop press closed the master take and the pedal is waiting for the next beat to set the
/// loop end.
case armedClose
/// Looping playback of the recorded take (overdub / reverse / mute apply here).
/// Looping playback of all recorded tracks. The selected track may be overdubbing.
case playing
/// Playback halted by a stop, but a recorded loop is still loaded (ready to resume).
/// Playback paused by a stop, with recorded material still loaded (ready to resume).
case stopped
}
@@ -7,12 +7,12 @@
import SwiftUI
import LyrebirdShoeGaze
/// The looper's loop timeline: a transport-state label, a loop-length read-out, and a track
/// with a sweeping play-head. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
/// The looper's loop timeline: a transport-state badge, tappable A–D track dots, a loop-length
/// read-out, a sweeping play-head track, and a one-line state indicator describing what the
/// pedal is doing. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
///
/// `LooperPedal`'s transport state is plain (non-`@Observable`) RT-adjacent data, so this view
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out — rather
/// than relying on SwiftUI change tracking.
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out.
struct LooperTimelineView: View {
// MARK: - Constants
@@ -29,28 +29,32 @@ struct LooperTimelineView: View {
private static let ledDiameter: CGFloat = 9
private static let badgeInnerSpacing: CGFloat = 4
private static let lengthLabelOpacity: Double = 0.75
private static let emptyLedBrightness: Double = 0.3
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"]
private static let dotSpacing: CGFloat = 4
private static let dotDiameter: CGFloat = 18
private static let dotLabelFontSize: CGFloat = 10
private static let dotBrightness: Double = 0.16
private static let dotFilledOpacity: Double = 0.55
private static let dotEmptyOpacity: Double = 0.45
private static let activeRingWidth: CGFloat = 1.5
private static let indicatorFontSize: CGFloat = 11
private static let indicatorOpacity: Double = 0.85
private static let overdubRingColor: Color = Color.red
private static let dotLabels: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
// MARK: - Properties
private let pedal: LooperPedal
@State private var position: Double?
@State private var state: LooperTransportState = .empty
@State private var state: LooperTransportState = .clear
@State private var lengthSeconds: 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 selectedTrack: Int = 0
@State private var overdubbingTrack: Int?
@State private var trackContent: [Bool] = Array(repeating: false, count: LooperPedal.trackCount)
@State private var stopArmed: Bool = false
@State private var stateDescription: String = ""
init(pedal: LooperPedal) {
self.pedal = pedal
@@ -63,22 +67,24 @@ struct LooperTimelineView: View {
HStack(spacing: LooperTimelineView.sectionSpacing) {
stateBadge
Spacer(minLength: 0)
slotDots
trackDots
Spacer(minLength: 0)
lengthLabel
}
track
stateIndicator
}
.task {
// Poll the pedal's transport read-outs; it isn't @Observable (RT-adjacent state).
while !Task.isCancelled {
position = pedal.playbackPosition01()
state = pedal.transportState
lengthSeconds = pedal.loopLengthSeconds
lengthBeats = pedal.loopLengthBeats
activeSlot = pedal.activeSlotIndex
slotContent = (0 ..< LooperPedal.slotCount).map { pedal.slotHasContent($0) }
selectedTrack = pedal.selectedTrackIndex
overdubbingTrack = pedal.overdubbingTrackIndex
trackContent = (0 ..< LooperPedal.trackCount).map { pedal.trackHasContent($0) }
stopArmed = pedal.isStopAtLoopEndArmed
stateDescription = pedal.stateDescription
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
}
}
@@ -86,25 +92,32 @@ struct LooperTimelineView: View {
// 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)
)
/// One tappable labelled dot per track: filled when it holds a loop, white-ringed when
/// selected, red-ringed while overdubbing. Tapping selects the track.
private var trackDots: some View {
HStack(spacing: LooperTimelineView.dotSpacing) {
ForEach(0 ..< LooperPedal.trackCount, id: \.self) { index in
let isSelected: Bool = index == selectedTrack
let isOverdub: Bool = index == overdubbingTrack
let hasContent: Bool = index < trackContent.count && trackContent[index]
Button {
pedal.selectTrack(index)
} label: {
Text(LooperTimelineView.dotLabels[index])
.font(.system(size: LooperTimelineView.dotLabelFontSize, weight: .bold, design: .monospaced))
.foregroundStyle(hasContent ? Color.white : Color.white.opacity(LooperTimelineView.dotEmptyOpacity))
.frame(width: LooperTimelineView.dotDiameter, height: LooperTimelineView.dotDiameter)
.background(
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.dotFilledOpacity)
: Color(white: LooperTimelineView.dotBrightness))
)
.overlay(
Circle().stroke(isOverdub ? LooperTimelineView.overdubRingColor
: (isSelected ? Color.white : Color.clear),
lineWidth: LooperTimelineView.activeRingWidth)
)
}
.buttonStyle(.plain)
}
}
}
@@ -131,6 +144,14 @@ struct LooperTimelineView: View {
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
}
/// One-line description of what the pedal is doing now — replaces the old action-button row.
private var stateIndicator: some View {
Text(stateDescription)
.font(.system(size: LooperTimelineView.indicatorFontSize, weight: .medium))
.foregroundStyle(Color.white.opacity(LooperTimelineView.indicatorOpacity))
.frame(maxWidth: .infinity, alignment: .leading)
}
private var track: some View {
GeometryReader { geometry in
let width: CGFloat = geometry.size.width
@@ -143,7 +164,6 @@ struct LooperTimelineView: View {
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
lineWidth: LooperTimelineView.borderLineWidth)
)
// Filled region up to the play-head, only while playing.
if position != nil {
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
@@ -162,22 +182,22 @@ struct LooperTimelineView: View {
private var stateColor: Color {
switch state {
case .empty: return Color(white: LooperTimelineView.emptyLedBrightness)
case .armedRecord, .armedStop: return Color.orange
case .recording: return Color.red
case .playing: return Color.green
case .stopped: return Color.orange
case .clear: return Color(white: 0.3)
case .armedRecord, .armedClose: return Color.orange
case .recordingMaster: return Color.red
case .playing: return Color.green
case .stopped: return Color.orange
}
}
private var stateText: String {
switch state {
case .empty: return "EMPTY"
case .armedRecord: return "ARM"
case .recording: return "REC"
case .armedStop: return "END"
case .playing: return "PLAY"
case .stopped: return "STOP"
case .clear: return "CLEAR"
case .armedRecord: return "ARM"
case .recordingMaster: return "REC"
case .armedClose: return "END"
case .playing: return "PLAY"
case .stopped: return "STOP"
}
}
@@ -47,9 +47,7 @@ public struct PedalButtonView: View {
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(action: pedalButton.action ?? {})
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
caption
}
} else {
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
@@ -61,11 +59,48 @@ public struct PedalButtonView: View {
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(node: node)
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
caption
}
}
}
}
/// The button caption — a live "what the next press does" label when the descriptor supplies
/// a `dynamicLabel`, otherwise the static label.
@ViewBuilder
private var caption: some View {
if let provider: () -> String = pedalButton.dynamicLabel {
DynamicCaption(provider: provider, fallback: pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
} else {
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
}
}
}
// MARK: - DynamicCaption
/// A caption that polls a text provider (RT-adjacent pedal state that isn't `@Observable`), on
/// the same `.task` cadence as the looper timeline, so a state-driven button label stays current.
private struct DynamicCaption: View {
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
let provider: () -> String
let fallback: String
@State private var text: String = ""
var body: some View {
Text(text.isEmpty ? fallback : text)
.task {
while !Task.isCancelled {
text = provider()
try? await Task.sleep(nanoseconds: DynamicCaption.pollIntervalNanoseconds)
}
}
}
}
+166 -425
View File
@@ -16,9 +16,8 @@ struct LooperPedalTests {
// MARK: - Test fixtures
/// A constant-frequency sine source with a live-settable amplitude, so tests can
/// silence the live input at an exact scheduled time and attribute any remaining
/// output unambiguously to the looper's own playback.
/// A constant-frequency sine source with a live-settable amplitude, so tests can silence the
/// live input at an exact scheduled time and attribute any remaining output to the looper.
private final class ToneSource: SynthesizerBase {
let ampNode: ParameterNode = ParameterNode(0.3)
var amplitude: Double {
@@ -39,12 +38,8 @@ struct LooperPedalTests {
}
}
/// A no-audio synth that posts a `TriggerEvent` (via `SendTrigger.Control`) at an exact
/// sample-accurate time within a single continuous NRT render. `build()` runs eagerly at
/// `engine.add(_:)` time, but the *trigger* it wires only fires once its own `Line.Control`
/// ramp crosses zero at `fireTime` seconds — so combined with a `TriggerListener` handler,
/// this is how tests schedule an exact-time side effect (e.g. flipping a looper transport
/// action) mid-render.
/// Posts a `TriggerEvent` at an exact sample-accurate time within a single NRT render, so a
/// test can flip a looper transport action mid-render.
private final class TimedTrigger: SynthesizerBase {
private let fireTime: Double
private let triggerID: Int32
@@ -70,7 +65,8 @@ struct LooperPedalTests {
}
/// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register
/// exact-time actions via `scheduleAction`, then renders and returns the stereo samples.
/// exact-time actions, then renders and returns the stereo samples. No clock is injected, so
/// the looper transport is immediate (un-quantized).
private func render(
totalDuration: Double,
toneAmplitude: Double = 0.3,
@@ -87,15 +83,13 @@ struct LooperPedalTests {
defer { try? FileManager.default.removeItem(at: url) }
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
let numAudioBuses: Int = 64
let numControlBuses: Int = 512
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let listener: TriggerListener = TriggerListener(engine: engine)
@@ -124,8 +118,6 @@ struct LooperPedalTests {
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
try engine.add(trigger)
listener.addHandler(id: id) { _, _ in
// `_drainSync` calls this inline, synchronously, on the same thread that
// called `engine.start()` in NRT mode — which is this MainActor test method.
MainActor.assumeIsolated { action() }
}
}
@@ -136,247 +128,9 @@ struct LooperPedalTests {
return readStereoCAF(url: url, sampleRate: sampleRate)
}
// MARK: - Tests
@Test func emptyPhasePassesDryThrough() throws {
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(samples), "Looper in .empty phase should pass the dry signal through")
}
@Test func recordThenPlayReproducesLoopContentAfterInputGoesSilent() throws {
let recordDuration: Double = 0.1
let totalDuration: Double = 0.6
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
// Begin recording immediately (post-build, pre-start): sample 0 of the render.
pedal.toggleRecordStop()
// Stop recording and start looping at `recordDuration`; silence the live input
// at the same instant so anything heard afterward can only be the looped take.
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
}
// Look well past the crossfade convergence window so only loop content remains.
let tailStart: Int = Int(Double(samples.count) * 0.75)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Loop should keep playing after the live input is silenced")
}
@Test func loopLengthBoundsPlaybackToRecordedTakeNotFullBuffer() throws {
// Record a very short take, then render well beyond it with the input silenced.
// Continuous non-silence over that long tail proves playback wraps at the
// narrow recorded length, not the full 60 s allocation.
let recordDuration: Double = 0.05
let totalDuration: Double = 1.0
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
}
let lateWindowStart: Int = Int(Double(samples.count) * 0.9)
let lateWindow: [Float] = Array(samples[lateWindowStart...])
#expect(hasNonSilentOutput(lateWindow), "Loop should still be wrapping near the end of a 1 s render from a 0.05 s take")
}
@Test func overdubAddsEnergyToTheLoop() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.2
let overdubDuration: Double = 0.1
let totalDuration: Double = 0.9
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 }
try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 }
// Silence the live input once overdubbing is done so the measurement window
// reflects only what is now baked into the loop.
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
}
let stride: Int = 2 // interleaved stereo
let measureStart: Double = 0.6
let measureStartIndex: Int = Int(measureStart * 44100.0) * stride
guard measureStartIndex < samples.count else {
Issue.record("Render too short to measure post-overdub loop content")
return
}
let measured: [Float] = Array(samples[measureStartIndex...])
#expect(hasNonSilentOutput(measured), "Loop should contain audible content after an overdub pass")
}
@Test func resetLoopClearsContentAndReturnsToPassthrough() throws {
let recordDuration: Double = 0.1
let resetAt: Double = 0.2
let totalDuration: Double = 0.5
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(resetAt) { pedal.resetLoop() }
// Silence the input after reset — the loop is gone, so output should be silent.
try scheduleAction(resetAt) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(!hasNonSilentOutput(tail), "After reset + silenced input, no leftover loop content should remain")
}
@Test func loopOffMutesLoopButKeepsLivePassthrough() throws {
let recordDuration: Double = 0.1
let loopOffAt: Double = 0.2
let totalDuration: Double = 0.5
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(loopOffAt) { pedal.loopOn = 0.0 }
// Keep the live tone audible (do not silence it) — loopOn muting the loop
// should not also silence the live passthrough.
}
let tailStart: Int = Int(Double(samples.count) * 0.9)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Muting the loop should not silence the live passthrough")
}
@Test func playbackLevelAttenuatesLoopOutput() throws {
let recordDuration: Double = 0.1
let totalDuration: Double = 0.5
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.playbackLevel = playbackLevelDb
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
}
}
let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0))
let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0))
#expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB")
let expectedRatio: Double = dbToAmp(-6.0)
let tolerance: Double = 0.15
let actualRatio: Double = attenuatedRMS / unityRMS
#expect(
abs(actualRatio - expectedRatio) < tolerance,
"Expected ~\(expectedRatio) amplitude ratio at -6 dB, got \(actualRatio)"
)
}
@Test func overdubLevelScalesOnlyTheNewMaterial() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.2
let overdubDuration: Double = 0.1
let totalDuration: Double = 0.5
func renderOverdub(overdubLevelDb: Double) throws -> [Float] {
try render(totalDuration: totalDuration, toneAmplitude: 0.0) { engine, source, pedal, scheduleAction in
// Record silence for the initial take so the loop starts at zero content —
// isolates the overdub pass's own level.
pedal.overdubLevel = overdubLevelDb
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(overdubStart) { source.amplitude = 0.3 }
try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 }
try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 }
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
}
}
let unityRMS: Double = rms(try renderOverdub(overdubLevelDb: 0.0))
let attenuatedRMS: Double = rms(try renderOverdub(overdubLevelDb: -6.0))
#expect(attenuatedRMS < unityRMS, "-6 dB overdub level should bake in less energy than 0 dB")
}
@Test func exposesLooperControls() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#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 } ==
["Record / Stop", "Overdub", "Undo", "Slot", "Reset"])
}
@Test func looperIsDoubleWidth() throws {
#expect(LooperPedal().widthUnits == 2)
}
@Test func readoutsReflectRecordedTakeLength() throws {
let recordDuration: Double = 0.1
let sampleRate: Double = 44100.0
var captured: LooperPedal?
_ = try render(totalDuration: 0.4, sampleRate: sampleRate) { engine, source, pedal, scheduleAction in
captured = pedal
// Surface the engine clock so the play-head anchor and read-outs are live.
pedal.hostEngine = engine
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
}
let pedal: LooperPedal = try #require(captured)
#expect(pedal.transportState == .playing)
// No clock injected → un-quantized fallback trims to the recorder's frame count.
let expectedFrames: Double = recordDuration * sampleRate
// Recorder stop is snapshot at block rate, so allow one block of slop.
let renderBlockSize: Double = 512.0
let tolerance: Double = renderBlockSize
#expect(abs(Double(pedal.loopFrameCount) - expectedFrames) < tolerance,
"loopFrameCount \(pedal.loopFrameCount) should be ~\(expectedFrames)")
#expect(abs(pedal.loopLengthSeconds - recordDuration) < 0.02)
#expect(pedal.loopLengthBeats == 0.0, "No clock → no beat-length read-out")
let position: Double? = pedal.playbackPosition01()
#expect(position != nil && position! >= 0.0 && position! < 1.0)
}
@Test func transportStartsEmptyAndReturnsEmptyAfterReset() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.transportState == .empty)
#expect(pedal.playbackPosition01() == nil)
pedal.resetLoop()
#expect(pedal.transportState == .empty)
}
@Test func undoOverdubRestoresPreDubLoopEnergy() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.2
let overdubDuration: Double = 0.1
let totalDuration: Double = 0.9
let measureStart: Double = 0.6
func tailRMS(undo: Bool) throws -> Double {
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
// Engage overdub via the transport action so a pre-dub snapshot is captured.
try scheduleAction(overdubStart) { pedal.toggleOverdub() }
try scheduleAction(overdubStart + overdubDuration) { pedal.toggleOverdub() }
if undo {
try scheduleAction(overdubStart + overdubDuration) { pedal.undoOverdub() }
}
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
}
let startIndex: Int = Int(measureStart * 44100.0) * 2
guard startIndex < samples.count else { return 0 }
return rms(Array(samples[startIndex...]))
}
let dubbedRMS: Double = try tailRMS(undo: false)
let undoneRMS: Double = try tailRMS(undo: true)
#expect(undoneRMS < dubbedRMS,
"Undo should remove the overdubbed layer's energy (undone \(undoneRMS) < dubbed \(dubbedRMS))")
}
/// Builds an engine with the pedal added (so `effect()` allocates its buffer + recorders)
/// but does NOT start it, so the beat-quantized callbacks can be driven deterministically.
/// Builds an engine with the pedal added (so `effect()` allocates buffers + recorders) but
/// does NOT start it, so beat-quantized callbacks can be driven deterministically. The caller
/// keeps the returned (weak-referenced) engine + clock alive.
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
let url: URL = FileManager.default.temporaryDirectory
@@ -397,8 +151,6 @@ struct LooperPedalTests {
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
// Inject the tempo clock + engine the way PedalBoard.add would. `Pedal.clock` is weak
// (owned by ShoeGaze in production), so the caller must keep the returned clock alive.
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
pedal.clock = clock
pedal.hostEngine = engine
@@ -406,197 +158,186 @@ struct LooperPedalTests {
return (engine, clock, pedal)
}
@Test func beatQuantizedTransportProgressesAndReportsWholeBeatLength() throws {
let sampleRate: Double = 44100.0
let bpm: Double = 120.0 // 22 050 frames per beat
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate)
// Keep the (weak-referenced) clock alive for the whole test.
withExtendedLifetime(clock) {
#expect(pedal.transportState == .empty)
// MARK: - Controls
// A record press with a clock present arms for the next beat, not immediately.
pedal.toggleRecordStop()
#expect(pedal.transportState == .armedRecord)
// Simulate the routine firing on the beat-1 boundary (0.5 s at 120 BPM).
let startSample: SampleTime = SampleTime(sampleRate * 0.5)
pedal.beginRecording(at: startSample)
#expect(pedal.transportState == .recording)
// Stop press arms; simulate the close on the beat-5 boundary (2.5 s → a 4-beat loop).
pedal.toggleRecordStop()
#expect(pedal.transportState == .armedStop)
let stopSample: SampleTime = SampleTime(sampleRate * 2.5)
pedal.finishRecordingAndPlay(at: stopSample)
#expect(pedal.transportState == .playing)
#expect(pedal.loopFrameCount == Int(stopSample - startSample))
#expect(pedal.loopLengthBeats == 4.0, "2.0 s at 120 BPM is exactly 4 beats")
pedal.resetLoop()
#expect(pedal.transportState == .empty)
#expect(pedal.loopLengthBeats == 0.0)
}
@Test func exposesLooperControls() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#expect(pedal.effectSwitches.isEmpty)
#expect(pedal.effectButtons.isEmpty)
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse", "Reset"])
}
@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 looperIsDoubleWidth() throws {
#expect(LooperPedal().widthUnits == 2)
#expect(LooperPedal.trackCount == 4)
}
@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)
// MARK: - Audio behaviour (immediate / un-quantized)
@Test func clearStatePassesDryThrough() throws {
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(samples), "Cleared looper should pass the dry signal through")
}
@Test func recordCloseThenPlaysAfterInputSilenced() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.7) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record track A
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, keep playing
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.8)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Recorded loop should keep playing after the input is silenced")
}
@Test func resetReturnsToClearAndSilence() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(0.2) { pedal.resetLoop() }
try scheduleAction(0.2) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(!hasNonSilentOutput(tail), "After reset + silenced input, no loop content should remain")
}
@Test func playbackLevelAttenuatesLoop() throws {
let recordDuration: Double = 0.1
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.playbackLevel = playbackLevelDb
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
}
let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0))
let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0))
#expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB")
}
@Test func stopPlaybackHaltsAndRecordStopResumes() throws {
@Test func reverseKeepsLoopAudible() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.6) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(0.25) { pedal.reverse = 1.0 }
try scheduleAction(0.25) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible")
}
// MARK: - State machine (headless)
@Test func statesProgressFromClearToPlaying() 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
pedal.clock = nil // immediate transport
#expect(pedal.transportState == .clear)
#expect(pedal.loopButtonCaption == "Record")
pedal.pressLoop() // → recording A
#expect(pedal.transportState == .recordingMaster)
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop() // → playing + overdubbing A
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
#expect(pedal.loopButtonCaption == "Play") // next press ends overdub
pedal.pressLoop() // → playing, overdub off
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.trackHasContent(0))
#expect(pedal.loopButtonCaption == "Overdub") // A has content, next press overdubs
} }
}
@Test func masterLengthQuantizesToWholeBeats() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate) // 22 050 frames / beat
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop() // arm record (routine won't fire; engine idle)
pedal.beginMasterRecording(at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop() // arm close
pedal.closeMasterAndPlay(at: SampleTime(sampleRate * 2.5)) // 2.0 s = 4 beats
#expect(pedal.transportState == .playing)
#expect(pedal.loopFrameCount == Int(sampleRate * 2.0))
#expect(pedal.loopLengthBeats == 4.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.loopFrameCount == 0)
} }
}
@Test func onlyTrackASelectableWhileClear() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
#expect(pedal.selectedTrackIndex == 0)
pedal.selectTrack(2) // ignored while clear
#expect(pedal.selectedTrackIndex == 0)
} }
}
@Test func selectingTrackWhilePlayingEndsOverdubAndSwitches() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.selectTrack(1) // select B — ends A's overdub
#expect(pedal.selectedTrackIndex == 1)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(!pedal.trackHasContent(1))
#expect(pedal.loopButtonCaption == "Record") // empty B, next press records it
pedal.pressLoop() // overdub (record) B
#expect(pedal.overdubbingTrackIndex == 1)
#expect(pedal.trackHasContent(1))
} }
}
@Test func stopResumeAndCueStop() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.playbackPosition01() == nil)
#expect(pedal.loopButtonCaption == "Play")
pedal.toggleRecordStop() // Record / Stop resumes from a stopped loop
pedal.pressLoop() // resume
#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)
// Cue Stop arms while playing (routine waits; engine idle so it never fires here).
#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)
pedal.toggleStopAtLoopEnd()
#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 {
let sampleRate: Double = 44100.0
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(clock) {
// Get to a playing loop so a buffer + non-zero length exist.
pedal.toggleRecordStop()
pedal.beginRecording(at: SampleTime(sampleRate * 0.5))
pedal.toggleRecordStop()
pedal.finishRecordingAndPlay(at: SampleTime(sampleRate * 2.5))
// A snapshot armed under the current generation…
let snapshot: [Double] = [Double](repeating: 0.5, count: 64)
let staleGeneration: Int = pedal.transportGeneration
// …is superseded by a reset (which bumps the generation and clears the buffer).
pedal.resetLoop()
// The deferred restore must now be a no-op: it must not reintroduce audio into the
// buffer the user just cleared.
pedal.applyUndoRestore(snapshot, slot: pedal.activeSlotIndex, generation: staleGeneration)
#expect(pedal.transportState == .empty)
#expect(pedal.loopFrameCount == 0)
}
}
@Test func beatsForSpanRoundsToWholeBeats() throws {
let sampleRate: Double = 48000.0
let bpm: Double = 100.0 // 28 800 frames per beat
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate)
let framesPerBeat: Int = 28_800
#expect(pedal.beatsForSpan(frames: framesPerBeat * 3, clock: clock) == 3.0)
#expect(pedal.beatsForSpan(frames: framesPerBeat * 8, clock: clock) == 8.0)
}
@Test func reverseKeepsLoopAudible() throws {
let recordDuration: Double = 0.1
let reverseAt: Double = 0.2
let totalDuration: Double = 0.6
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
pedal.toggleRecordStop()
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
try scheduleAction(reverseAt) { pedal.reverse = 1.0 }
try scheduleAction(reverseAt) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible")
}
}
@@ -256,7 +256,7 @@ struct MIDIControllerPCTests {
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only
#expect(looper.transportState == .empty)
#expect(looper.transportState == .clear)
// The looper was added via the board, so it carries the shared tempo clock and its
// transport is beat-quantized: the mapped press arms recording for the next beat.