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:
@@ -384,11 +384,11 @@ public final class MIDIController {
|
|||||||
let toggleThreshold: Double = 0.5
|
let toggleThreshold: Double = 0.5
|
||||||
switch kind {
|
switch kind {
|
||||||
case .looperRecordStop:
|
case .looperRecordStop:
|
||||||
(pedal as? LooperPedal)?.toggleRecordStop()
|
// The smart Loop footswitch drives record / set-end / overdub / play by state.
|
||||||
|
(pedal as? LooperPedal)?.pressLoop()
|
||||||
case .looperOverdubToggle:
|
case .looperOverdubToggle:
|
||||||
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
|
// Overdub is toggled by the same Loop press once a loop is playing.
|
||||||
let node: UIParamNode = looper.$overdubOn
|
(pedal as? LooperPedal)?.pressLoop()
|
||||||
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
|
|
||||||
case .looperLoopToggle:
|
case .looperLoopToggle:
|
||||||
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
|
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
|
||||||
let node: UIParamNode = looper.$loopOn
|
let node: UIParamNode = looper.$loopOn
|
||||||
|
|||||||
@@ -49,19 +49,32 @@ public struct PedalButton {
|
|||||||
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
|
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
|
||||||
public let indicator: UIParamNode?
|
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.
|
/// 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`
|
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
|
||||||
/// for a plain button.
|
/// for a plain button.
|
||||||
|
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
|
||||||
/// - action: Closure run on each press.
|
/// - 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.label = label
|
||||||
self.style = .momentary
|
self.style = .momentary
|
||||||
self.node = nil
|
self.node = nil
|
||||||
self.action = action
|
self.action = action
|
||||||
self.indicator = indicator
|
self.indicator = indicator
|
||||||
|
self.dynamicLabel = dynamicLabel
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a toggle button bound to a `UIParamNode`.
|
/// Creates a toggle button bound to a `UIParamNode`.
|
||||||
@@ -70,11 +83,13 @@ public struct PedalButton {
|
|||||||
/// - label: Short label shown on the button.
|
/// - label: Short label shown on the button.
|
||||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property
|
/// - node: The `UIParamNode` projected value of an `@UIParam` property
|
||||||
/// (`pedal.$overdubOn`, `pedal.$loopOn`, …).
|
/// (`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.label = label
|
||||||
self.style = .toggle
|
self.style = .toggle
|
||||||
self.node = node
|
self.node = node
|
||||||
self.action = nil
|
self.action = nil
|
||||||
self.indicator = nil
|
self.indicator = nil
|
||||||
|
self.dynamicLabel = dynamicLabel
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,187 +8,144 @@ import Foundation
|
|||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A multi-slot loop-recorder pedal: record independent loops into any of several slots, then
|
/// A synchronized multitrack loop pedal. Track A's first take defines the master loop length;
|
||||||
/// switch between them, with overdub, overdub-undo, reverse playback, feedback-decay overdub,
|
/// tracks B–D are overdub layers recorded onto the same grid. All recorded tracks play at once,
|
||||||
/// and a crossfaded total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the
|
/// summed to one output and locked in phase. When the board supplies a tempo ``LyrebirdClock``
|
||||||
/// transport is beat-quantized — record start and loop close both snap to the next beat, so
|
/// the master take is beat-quantized so every loop is a whole number of beats long.
|
||||||
/// every loop is a whole number of beats long.
|
|
||||||
///
|
///
|
||||||
/// Signal chain (inside `effect(_:)`), per slot `i` plus one shared player:
|
/// ## The Loop footswitch drives the transport by state
|
||||||
/// ```
|
/// - **Clear** (nothing recorded; only track A selectable): press → record A; press → set the
|
||||||
/// dry → RecordBuffer.Audio primary[i] (take capture, run-gated by transport) ─┐ (write only,
|
/// loop end (quantized) and drop into overdub on A when it wraps; press → end overdub, keep
|
||||||
/// dry → RecordBuffer.Audio overdub[i] (gated by overdubOn × isPlaying × slot i) │ RootRegistering)
|
/// playing; further presses toggle overdub ↔ play on the selected track.
|
||||||
/// buffers[activeSlot] → PlayBuffer.Audio (loop, cubic, rate ±1, swapped ───┤
|
/// - **Playing, track B–D selected**: press toggles overdub on that track, aligned to A's
|
||||||
/// on slot change via setBuffer) │
|
/// play-head. Recording an empty track is just overdub onto silence.
|
||||||
/// dry ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─────────────────────────┴→ wet
|
/// - 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
|
/// ## Audio graph (built once in `effect(_:)`)
|
||||||
/// (gated so inactive slots keep their content); the shared player's source buffer is swapped
|
/// One `PlayBuffer` per track, all summed; one always-running overdub `RecordBuffer` per track
|
||||||
/// to the active slot with ``PlayBuffer/Audio/setBuffer(_:engine:)``. Every transport action is
|
/// whose `recLevel` is gated so only the selected, overdubbing track layers new input; a
|
||||||
/// a live parameter change the graph already reads each block, plus explicit methods for the
|
/// non-looping master recorder for track A's length-defining take. The overdub recorders run
|
||||||
/// genuine non-RT side effects (clearing a buffer, narrowing `loopLength`, snapshotting for undo,
|
/// continuously while playing (reset to the top at play-start) so their write head stays locked
|
||||||
/// swapping the player's buffer).
|
/// to the shared play-head — overdub can be toggled on any track without drifting out of phase.
|
||||||
///
|
|
||||||
/// ## 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).
|
|
||||||
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 {
|
||||||
"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 }
|
public override var widthUnits: Int { 2 }
|
||||||
|
|
||||||
// MARK: - Knobs
|
// MARK: - Knobs
|
||||||
|
|
||||||
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
|
/// 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
|
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
|
||||||
|
|
||||||
/// 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.
|
/// Overdub input gain, in dB.
|
||||||
@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 existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
|
||||||
/// keeps prior layers indefinitely; lower values fade them for a decaying feedback loop.
|
/// layers indefinitely; lower values fade them for a decaying 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 — affects only the active, playing slot.
|
|
||||||
@UIParam public var overdubOn: Double = 0.0
|
|
||||||
|
|
||||||
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
|
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
|
||||||
@UIParam public var loopOn: Double = 1.0
|
@UIParam public var loopOn: Double = 1.0
|
||||||
|
|
||||||
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
|
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
|
||||||
@UIParam public var reverse: Double = 0.0
|
@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
|
@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
|
@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
|
@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`.
|
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed.
|
||||||
/// Also the single source of truth for ``isStopAtLoopEndArmed``.
|
|
||||||
@UIParam public var cueStopArmed: Double = 0.0
|
@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
|
// MARK: - Constants
|
||||||
|
|
||||||
/// Number of independent loop slots. Each slot allocates its own `maxDurationSeconds`
|
/// Number of loop tracks (A–D).
|
||||||
/// buffer, so per-instance memory is roughly `slotCount × maxDurationSeconds × sampleRate ×
|
public static let trackCount: Int = 4
|
||||||
/// 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.
|
/// Maximum recordable master length, in seconds (each track allocates a buffer this long, so
|
||||||
|
/// per-instance memory is roughly `trackCount × maxDurationSeconds × sampleRate × 8 bytes`).
|
||||||
private static let maxDurationSeconds: Double = 60.0
|
private static let maxDurationSeconds: Double = 60.0
|
||||||
|
|
||||||
/// Default crossfade duration, in seconds.
|
|
||||||
private static let defaultCrossfadeTime: Double = 0.05
|
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
|
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
|
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
|
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 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: - 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 buffers: [LyrebirdBuffer] = []
|
||||||
|
private var players: [PlayBuffer.Audio] = []
|
||||||
private var primaryRecorders: [RecordBuffer.Audio] = []
|
|
||||||
private var overdubRecorders: [RecordBuffer.Audio] = []
|
private var overdubRecorders: [RecordBuffer.Audio] = []
|
||||||
|
private var overdubGates: [ParameterNode] = []
|
||||||
|
|
||||||
/// Per-slot overdub gate (`1` for the active slot, `0` otherwise), multiplied into each
|
/// Non-looping recorder for track A's length-defining first take.
|
||||||
/// overdub recorder's `run` so only the active slot layers new material.
|
private var masterRecorder: RecordBuffer.Audio?
|
||||||
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]?] = []
|
|
||||||
|
|
||||||
// MARK: - Transport state
|
// MARK: - Transport state
|
||||||
|
|
||||||
private enum Phase {
|
private enum Phase {
|
||||||
case empty
|
case clear
|
||||||
case armedRecord
|
case armedRecord
|
||||||
case recording
|
case recordingMaster
|
||||||
case armedStop
|
case armedClose
|
||||||
case playing
|
case playing
|
||||||
case stopped
|
case stopped
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transport phase of the *active* slot.
|
private var phase: Phase = .clear
|
||||||
private var phase: Phase = .empty
|
|
||||||
|
|
||||||
/// 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 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?
|
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?
|
private var stopRoutine: LyrebirdRoutine?
|
||||||
|
|
||||||
/// Monotonic action generation. Bumped on every arm, slot switch, overdub press, and reset;
|
/// Monotonic action generation guarding deferred beat/stop callbacks (see the single-track
|
||||||
/// a deferred beat/undo callback carries the generation it was armed under and is dropped if
|
/// history — `LyrebirdRoutine.stop()` cannot recall an already-enqueued main-thread hop).
|
||||||
/// 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.)
|
|
||||||
private(set) var transportGeneration: Int = 0
|
private(set) var transportGeneration: Int = 0
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
@@ -202,7 +159,7 @@ public final class LooperPedal: Pedal {
|
|||||||
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
|
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Knobs / switches / buttons
|
// MARK: - Knobs / buttons
|
||||||
|
|
||||||
public override var effectKnobs: [PedalKnob] {
|
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] {
|
public override var effectTransportButtons: [PedalButton] {
|
||||||
[
|
[
|
||||||
PedalButton(label: "Loop", node: $loopOn),
|
PedalButton(label: "Loop", indicator: $overdubIndicator,
|
||||||
PedalButton(label: "Stop", indicator: $stoppedIndicator) { [weak self] in self?.stopPlayback() },
|
dynamicLabel: { [weak self] in self?.loopButtonCaption ?? "Loop" }) { [weak self] in self?.pressLoop() },
|
||||||
PedalButton(label: "Cue Stop", indicator: $cueStopArmed) { [weak self] in self?.toggleStopAtLoopEnd() },
|
PedalButton(label: "Stop", indicator: $stoppedIndicator,
|
||||||
PedalButton(label: "Reverse", node: $reverse),
|
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,
|
||||||
/// Momentary action row.
|
dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }),
|
||||||
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: "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 of the active slot (LED colour, armed state, timeline).
|
/// Publicly-observable transport phase for the state indicator, LEDs, and timeline.
|
||||||
public var transportState: LooperTransportState {
|
public var transportState: LooperTransportState {
|
||||||
switch phase {
|
switch phase {
|
||||||
case .empty: return .empty
|
case .clear: return .clear
|
||||||
case .armedRecord: return .armedRecord
|
case .armedRecord: return .armedRecord
|
||||||
case .recording: return .recording
|
case .recordingMaster: return .recordingMaster
|
||||||
case .armedStop: return .armedStop
|
case .armedClose: return .armedClose
|
||||||
case .playing: return .playing
|
case .playing: return .playing
|
||||||
case .stopped: return .stopped
|
case .stopped: return .stopped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `true` while a "stop at loop end" is armed and waiting for the boundary.
|
/// Index of the selected track, `0 ..< trackCount`.
|
||||||
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
|
public var selectedTrackIndex: Int { selectedTrack }
|
||||||
|
|
||||||
/// Index of the active loop slot, in `0 ..< slotCount`.
|
/// The track currently overdubbing, or `nil`.
|
||||||
public var activeSlotIndex: Int { activeSlot }
|
public var overdubbingTrackIndex: Int? { overdubbingTrack }
|
||||||
|
|
||||||
/// `true` if slot `index` holds a recorded loop.
|
/// `true` if track `index` holds recorded material.
|
||||||
public func slotHasContent(_ index: Int) -> Bool {
|
public func trackHasContent(_ index: Int) -> Bool {
|
||||||
index >= 0 && index < loopFrames.count && loopFrames[index] > 0
|
index >= 0 && index < trackHasContent.count && trackHasContent[index]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Active-slot loop length in frames (`0` until a take is recorded).
|
/// `true` while a stop-at-loop-end is armed.
|
||||||
public var loopFrameCount: Int { loopFrames.indices.contains(activeSlot) ? loopFrames[activeSlot] : 0 }
|
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
|
||||||
|
|
||||||
/// Active-slot loop length in seconds.
|
/// Master loop length in frames (`0` until track A is closed).
|
||||||
public var loopLengthSeconds: Double { Double(loopFrameCount) / sampleRate }
|
public var loopFrameCount: Int { masterLength }
|
||||||
|
|
||||||
/// Active-slot loop length in whole beats (`0` unless the take was beat-quantized).
|
/// Master loop length in seconds.
|
||||||
public var loopLengthBeats: Double { loopBeats.indices.contains(activeSlot) ? loopBeats[activeSlot] : 0.0 }
|
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
|
||||||
|
|
||||||
/// Normalised play-head position in `[0, 1)` while the active slot is `.playing`, else `nil`.
|
/// Master loop length in whole beats (`0` unless beat-quantized).
|
||||||
///
|
public var loopLengthBeats: Double { masterBeats }
|
||||||
/// 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`
|
/// Normalised play-head position in `[0, 1)` while playing, else `nil`. Shared by all tracks.
|
||||||
/// 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`.
|
|
||||||
public func playbackPosition01() -> Double? {
|
public func playbackPosition01() -> Double? {
|
||||||
guard phase == .playing, loopFrameCount > 0,
|
guard phase == .playing, masterLength > 0, let engine: SynthesisEngine = hostEngine else {
|
||||||
let engine: SynthesisEngine = hostEngine,
|
return nil
|
||||||
playStartSample.indices.contains(activeSlot) else { return nil }
|
}
|
||||||
let elapsed: SampleTime = engine.currentTime - playStartSample[activeSlot]
|
let elapsed: SampleTime = engine.currentTime - playStartSample
|
||||||
guard elapsed >= 0 else { return 0.0 }
|
guard elapsed >= 0 else { return 0.0 }
|
||||||
let framesInto: Int = Int(elapsed % SampleTime(loopFrameCount))
|
let framesInto: Int = Int(elapsed % SampleTime(masterLength))
|
||||||
let forward: Double = Double(framesInto) / Double(loopFrameCount)
|
let forward: Double = Double(framesInto) / Double(masterLength)
|
||||||
return reverse >= 0.5 ? (1.0 - forward) : forward
|
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
|
// MARK: - Effect
|
||||||
|
|
||||||
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 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)
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
|
||||||
buffers.append(buffer)
|
buffers.append(buffer)
|
||||||
|
|
||||||
let primary: RecordBuffer.Audio = RecordBuffer.Audio(
|
let gate: ParameterNode = ParameterNode(0.0)
|
||||||
input: dry,
|
overdubGates.append(gate)
|
||||||
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 overdub: RecordBuffer.Audio = RecordBuffer.Audio(
|
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||||
input: dry,
|
input: dry,
|
||||||
@@ -315,76 +301,102 @@ public final class LooperPedal: Pedal {
|
|||||||
loop: true,
|
loop: true,
|
||||||
doneAction: .nothing
|
doneAction: .nothing
|
||||||
)
|
)
|
||||||
// Live-gated: writes only while this slot is active, playing, and overdub is on.
|
// Always running while playing; its write head stays locked to the shared play-head.
|
||||||
// Existing content is scaled by `feedback` each pass (1.0 = keep, < 1.0 = decay).
|
// `recLevel` is zero unless this track is the one being overdubbed; `preLevel` is 1
|
||||||
overdub.$run.source = $overdubOn * $isPlaying * gate
|
// (identity — keep existing content) except while overdubbing, when it is `feedback`.
|
||||||
overdub.$recLevel.source = DbAmp.Control($overdubLevel)
|
overdub.$run.source = $isPlaying
|
||||||
overdub.$preLevel.source = $feedback
|
overdub.$recLevel.source = gate * DbAmp.Control($overdubLevel)
|
||||||
|
overdub.$preLevel.source = (unity - gate) + gate * $feedback
|
||||||
overdubRecorders.append(overdub)
|
overdubRecorders.append(overdub)
|
||||||
}
|
|
||||||
|
|
||||||
loopFrames = [Int](repeating: 0, count: LooperPedal.slotCount)
|
let player: PlayBuffer.Audio = PlayBuffer.Audio(
|
||||||
loopBeats = [Double](repeating: 0.0, count: LooperPedal.slotCount)
|
buffer: buffer,
|
||||||
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,
|
loop: true,
|
||||||
interpolation: .cubic,
|
interpolation: .cubic,
|
||||||
rate: playbackRate,
|
rate: playbackRate,
|
||||||
trigger: $playTrigger,
|
trigger: $playTrigger,
|
||||||
mul: DbAmp.Control($playbackLevel)
|
mul: DbAmp.Control($playbackLevel)
|
||||||
)
|
)
|
||||||
player = loopPlayer
|
players.append(player)
|
||||||
|
|
||||||
// Loop 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
|
|
||||||
|
|
||||||
// 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
|
let master: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||||
|
input: dry,
|
||||||
|
buffer: buffers[0],
|
||||||
|
loop: false,
|
||||||
|
doneAction: .nothing
|
||||||
|
)
|
||||||
|
master.run = 0.0
|
||||||
|
masterRecorder = master
|
||||||
|
|
||||||
/// `.empty` → arm/begin recording the active slot. `.recording` → close the loop and start
|
trackHasContent = [Bool](repeating: false, count: LooperPedal.trackCount)
|
||||||
/// looping. No-op while `.playing` or already armed.
|
|
||||||
public func toggleRecordStop() {
|
// 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 dryGate: any ValidGeneratorInput = unity - 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: - Loop footswitch
|
||||||
|
|
||||||
|
/// The smart transport press. Behaviour depends on the current phase and selected track.
|
||||||
|
public func pressLoop() {
|
||||||
switch phase {
|
switch phase {
|
||||||
case .empty:
|
case .clear: armMasterRecording()
|
||||||
armRecording()
|
case .recordingMaster: armCloseMaster()
|
||||||
case .recording:
|
case .playing: toggleOverdubSelected()
|
||||||
armStopAndPlay()
|
case .stopped: resumePlayback()
|
||||||
case .stopped:
|
case .armedRecord, .armedClose:
|
||||||
resumePlayback()
|
|
||||||
case .armedRecord, .armedStop, .playing:
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Immediately halts loop playback of the active slot. The recorded content is retained —
|
/// Selects the active track (the one Loop records / overdubs into). Tapping a timeline dot
|
||||||
/// press Record / Stop (or switch slots) to start it again. Cancels any armed "stop at end".
|
/// 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() {
|
public func stopPlayback() {
|
||||||
guard phase == .playing else { return }
|
guard phase == .playing else { return }
|
||||||
transportGeneration += 1
|
transportGeneration += 1
|
||||||
stopRoutine?.stop()
|
stopRoutine?.stop()
|
||||||
stopRoutine = nil
|
stopRoutine = nil
|
||||||
cueStopArmed = 0.0
|
cueStopArmed = 0.0
|
||||||
|
overdubbingTrack = nil
|
||||||
|
updateOverdubGates()
|
||||||
isPlaying = 0.0
|
isPlaying = 0.0
|
||||||
stoppedIndicator = 1.0
|
stoppedIndicator = 1.0
|
||||||
phase = .stopped
|
phase = .stopped
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Arms (or, if already armed, cancels) a stop that fires when the active loop next reaches
|
/// Arms (or cancels) a stop that fires when the loop next reaches its end. No-op unless
|
||||||
/// its end. No-op unless a loop is playing. With no engine to schedule against, stops now.
|
/// playing. With no engine to schedule against, stops now.
|
||||||
public func toggleStopAtLoopEnd() {
|
public func toggleStopAtLoopEnd() {
|
||||||
if isStopAtLoopEndArmed {
|
if isStopAtLoopEndArmed {
|
||||||
stopRoutine?.stop()
|
stopRoutine?.stop()
|
||||||
@@ -393,18 +405,16 @@ public final class LooperPedal: Pedal {
|
|||||||
transportGeneration += 1
|
transportGeneration += 1
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
guard phase == .playing, loopFrameCount > 0, playStartSample.indices.contains(activeSlot) else { return }
|
guard phase == .playing, masterLength > 0 else { return }
|
||||||
transportGeneration += 1
|
transportGeneration += 1
|
||||||
let generation: Int = transportGeneration
|
let generation: Int = transportGeneration
|
||||||
guard let engine: SynthesisEngine = hostEngine else {
|
guard let engine: SynthesisEngine = hostEngine else {
|
||||||
stopPlayback()
|
stopPlayback()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Sample time of the next loop boundary after now.
|
let frames: SampleTime = SampleTime(masterLength)
|
||||||
let anchor: SampleTime = playStartSample[activeSlot]
|
let elapsed: SampleTime = max(0, engine.currentTime - playStartSample)
|
||||||
let frames: SampleTime = SampleTime(loopFrameCount)
|
let boundary: SampleTime = playStartSample + (elapsed / frames + 1) * frames
|
||||||
let elapsed: SampleTime = max(0, engine.currentTime - anchor)
|
|
||||||
let boundary: SampleTime = anchor + (elapsed / frames + 1) * frames
|
|
||||||
cueStopArmed = 1.0
|
cueStopArmed = 1.0
|
||||||
stopRoutine?.stop()
|
stopRoutine?.stop()
|
||||||
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
|
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
|
||||||
@@ -419,172 +429,94 @@ public final class LooperPedal: Pedal {
|
|||||||
func applyStopAtLoopEnd(generation: Int) {
|
func applyStopAtLoopEnd(generation: Int) {
|
||||||
guard generation == transportGeneration, phase == .playing else { return }
|
guard generation == transportGeneration, phase == .playing else { return }
|
||||||
cueStopArmed = 0.0
|
cueStopArmed = 0.0
|
||||||
|
overdubbingTrack = nil
|
||||||
|
updateOverdubGates()
|
||||||
isPlaying = 0.0
|
isPlaying = 0.0
|
||||||
stoppedIndicator = 1.0
|
stoppedIndicator = 1.0
|
||||||
phase = .stopped
|
phase = .stopped
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resumes looping playback of a stopped slot from its head.
|
/// Returns the pedal to the clear state: all tracks cleared, track A selected, length reset.
|
||||||
private func resumePlayback() {
|
/// If sound is playing it acts as an immediate stop-and-clear.
|
||||||
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.
|
|
||||||
public func resetLoop() {
|
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?.stop()
|
||||||
transportRoutine = nil
|
transportRoutine = nil
|
||||||
undoRoutine?.stop()
|
|
||||||
undoRoutine = nil
|
|
||||||
stopRoutine?.stop()
|
stopRoutine?.stop()
|
||||||
stopRoutine = nil
|
stopRoutine = nil
|
||||||
cueStopArmed = 0.0
|
|
||||||
stoppedIndicator = 0.0
|
|
||||||
transportGeneration += 1
|
transportGeneration += 1
|
||||||
|
|
||||||
if primaryRecorders.indices.contains(activeSlot) {
|
masterRecorder?.run = 0.0
|
||||||
primaryRecorders[activeSlot].run = 0.0
|
masterRecorder?.requestReset()
|
||||||
primaryRecorders[activeSlot].requestReset()
|
for recorder: RecordBuffer.Audio in overdubRecorders {
|
||||||
|
recorder.requestReset()
|
||||||
}
|
}
|
||||||
if overdubRecorders.indices.contains(activeSlot) {
|
for buffer: LyrebirdBuffer in buffers {
|
||||||
overdubRecorders[activeSlot].requestReset()
|
buffer.clear()
|
||||||
|
buffer.setLoopLength(buffer.count)
|
||||||
}
|
}
|
||||||
if buffers.indices.contains(activeSlot) {
|
for i: Int in trackHasContent.indices {
|
||||||
buffers[activeSlot].clear()
|
trackHasContent[i] = false
|
||||||
buffers[activeSlot].setLoopLength(buffers[activeSlot].count)
|
|
||||||
}
|
}
|
||||||
|
selectedTrack = 0
|
||||||
|
overdubbingTrack = nil
|
||||||
|
masterLength = 0
|
||||||
|
masterBeats = 0.0
|
||||||
isPlaying = 0.0
|
isPlaying = 0.0
|
||||||
overdubOn = 0.0
|
|
||||||
loopOn = 1.0
|
loopOn = 1.0
|
||||||
playTrigger = 0.0
|
playTrigger = 0.0
|
||||||
if loopFrames.indices.contains(activeSlot) { loopFrames[activeSlot] = 0 }
|
stoppedIndicator = 0.0
|
||||||
if loopBeats.indices.contains(activeSlot) { loopBeats[activeSlot] = 0.0 }
|
cueStopArmed = 0.0
|
||||||
if overdubUndoSnapshots.indices.contains(activeSlot) { overdubUndoSnapshots[activeSlot] = nil }
|
updateOverdubGates()
|
||||||
phase = .empty
|
phase = .clear
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Transport helpers
|
// MARK: - Transport helpers
|
||||||
|
|
||||||
/// Snapshots the active slot's closed-loop content into `overdubUndoSnapshots`. Called with
|
private func updateOverdubGates() {
|
||||||
/// overdub off, so only the loop player reads the buffer concurrently (a lock-free read is safe).
|
for i: Int in overdubGates.indices {
|
||||||
private func captureOverdubSnapshot() {
|
overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0
|
||||||
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]
|
|
||||||
}
|
}
|
||||||
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
|
private func toggleOverdubSelected() {
|
||||||
/// edge even when the trigger was already high (e.g. switching between recorded slots).
|
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() {
|
private func pulsePlayTrigger() {
|
||||||
playTrigger = 0.0
|
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
|
let generation: Int = transportGeneration
|
||||||
DispatchQueue.main.async { [weak self] in
|
DispatchQueue.main.async { [weak self] in
|
||||||
guard let self, self.transportGeneration == generation else { return }
|
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 {
|
private enum QuantizedAction: Sendable {
|
||||||
case beginRecording
|
case beginMaster
|
||||||
case finishStop
|
case closeMaster
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Begins recording immediately, or — with a clock — on the next beat boundary.
|
private func armMasterRecording() {
|
||||||
private func armRecording() {
|
selectedTrack = 0 // only track A in the clear state
|
||||||
|
updateOverdubGates()
|
||||||
phase = .armedRecord
|
phase = .armedRecord
|
||||||
runQuantized(.beginRecording)
|
runQuantized(.beginMaster)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Closes the loop immediately, or — with a clock — on the next beat boundary.
|
private func armCloseMaster() {
|
||||||
private func armStopAndPlay() {
|
phase = .armedClose
|
||||||
phase = .armedStop
|
runQuantized(.closeMaster)
|
||||||
runQuantized(.finishStop)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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) {
|
private func runQuantized(_ action: QuantizedAction) {
|
||||||
transportGeneration += 1
|
transportGeneration += 1
|
||||||
let generation: Int = transportGeneration
|
let generation: Int = transportGeneration
|
||||||
@@ -623,61 +552,50 @@ public final class LooperPedal: Pedal {
|
|||||||
let target: SampleTime = clock.nextBeat()
|
let target: SampleTime = clock.nextBeat()
|
||||||
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)
|
||||||
// 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) }
|
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
|
||||||
}
|
}
|
||||||
transportRoutine = routine
|
transportRoutine = routine
|
||||||
routine.start(engine: engine)
|
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?) {
|
private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
|
||||||
guard generation == transportGeneration else { return }
|
guard generation == transportGeneration else { return }
|
||||||
switch action {
|
switch action {
|
||||||
case .beginRecording: beginRecording(at: beatSample)
|
case .beginMaster: beginMasterRecording(at: beatSample)
|
||||||
case .finishStop: finishRecordingAndPlay(at: beatSample)
|
case .closeMaster: closeMasterAndPlay(at: beatSample)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func beginRecording(at beatSample: SampleTime?) {
|
func beginMasterRecording(at beatSample: SampleTime?) {
|
||||||
guard phase == .armedRecord, primaryRecorders.indices.contains(activeSlot) else { return }
|
guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return }
|
||||||
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
|
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
|
||||||
primaryRecorders[activeSlot].run = 1.0
|
master.run = 1.0
|
||||||
phase = .recording
|
phase = .recordingMaster
|
||||||
}
|
}
|
||||||
|
|
||||||
func finishRecordingAndPlay(at beatSample: SampleTime?) {
|
func closeMasterAndPlay(at beatSample: SampleTime?) {
|
||||||
guard phase == .armedStop, primaryRecorders.indices.contains(activeSlot),
|
guard phase == .armedClose, let master: RecordBuffer.Audio = masterRecorder, !buffers.isEmpty else { return }
|
||||||
buffers.indices.contains(activeSlot) else { return }
|
master.run = 0.0
|
||||||
let primary: RecordBuffer.Audio = primaryRecorders[activeSlot]
|
|
||||||
let buffer: LyrebirdBuffer = buffers[activeSlot]
|
|
||||||
primary.run = 0.0
|
|
||||||
|
|
||||||
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
|
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
|
||||||
if let clock: LyrebirdClock = clock, beatSample != nil {
|
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)
|
let spanFrames: Int = Int(closeSample - recordStartSample)
|
||||||
loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, spanFrames)
|
masterLength = max(LooperPedal.minimumLoopFrames, spanFrames)
|
||||||
loopBeats[activeSlot] = beatsForSpan(frames: loopFrames[activeSlot], clock: clock)
|
masterBeats = beatsForSpan(frames: masterLength, clock: clock)
|
||||||
} else {
|
} else {
|
||||||
// Un-quantized fallback: trim to the recorder's frame count.
|
masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount)
|
||||||
loopFrames[activeSlot] = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
|
masterBeats = 0.0
|
||||||
loopBeats[activeSlot] = 0.0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.setLoopLength(loopFrames[activeSlot])
|
for buffer: LyrebirdBuffer in buffers {
|
||||||
playStartSample[activeSlot] = closeSample
|
buffer.setLoopLength(masterLength)
|
||||||
playTrigger = 1.0
|
}
|
||||||
isPlaying = 1.0
|
if trackHasContent.indices.contains(0) { trackHasContent[0] = true }
|
||||||
phase = .playing
|
// 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
|
/// Whole-beat length of a `frames`-long span at the clock's current tempo (UI read-out only).
|
||||||
/// 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.
|
|
||||||
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
|
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
|
||||||
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
|
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
|
||||||
guard samplesPerBeat > 0 else { return 0.0 }
|
guard samplesPerBeat > 0 else { return 0.0 }
|
||||||
|
|||||||
@@ -4,30 +4,31 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
/// Publicly-observable transport phase of ``LooperPedal``, surfaced for the UI so it can
|
/// Publicly-observable transport phase of the multitrack ``LooperPedal``, surfaced for the UI
|
||||||
/// colour the record LED, animate the "waiting for the next beat" armed states, and drive
|
/// so it can colour the state indicator, animate the "waiting for the next beat" armed states,
|
||||||
/// the loop timeline.
|
/// and drive the loop timeline.
|
||||||
///
|
///
|
||||||
/// The two `armed…` cases exist only when the pedal has a tempo ``LyrebirdClock`` — a
|
/// The pedal is a synchronized multitrack looper: track A's first take defines the master loop
|
||||||
/// transport action then waits for the next beat boundary before it takes effect. Without a
|
/// length, and tracks B–D are overdub layers recorded onto the same grid, all playing at once.
|
||||||
/// clock the pedal transitions straight between ``empty``, ``recording`` and ``playing``.
|
|
||||||
public enum LooperTransportState: Sendable, Equatable {
|
public enum LooperTransportState: Sendable, Equatable {
|
||||||
|
|
||||||
/// No take recorded yet. `Record` begins recording (or arms it, with a clock).
|
/// No material recorded on any track. Only track A can be selected; press Loop to record it.
|
||||||
case empty
|
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
|
case armedRecord
|
||||||
|
|
||||||
/// Actively recording the primary take.
|
/// Recording track A's first take, which defines the master loop length.
|
||||||
case recording
|
case recordingMaster
|
||||||
|
|
||||||
/// A stop has been requested and the pedal is waiting for the next beat to close the loop.
|
/// A Loop press closed the master take and the pedal is waiting for the next beat to set the
|
||||||
case armedStop
|
/// 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
|
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
|
case stopped
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,12 +7,12 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
/// The looper's loop timeline: a transport-state label, a loop-length read-out, and a track
|
/// The looper's loop timeline: a transport-state badge, tappable A–D track dots, a loop-length
|
||||||
/// with a sweeping play-head. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
|
/// 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
|
/// `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
|
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out.
|
||||||
/// than relying on SwiftUI change tracking.
|
|
||||||
struct LooperTimelineView: View {
|
struct LooperTimelineView: View {
|
||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
@@ -29,28 +29,32 @@ struct LooperTimelineView: View {
|
|||||||
private static let ledDiameter: CGFloat = 9
|
private static let ledDiameter: CGFloat = 9
|
||||||
private static let badgeInnerSpacing: CGFloat = 4
|
private static let badgeInnerSpacing: CGFloat = 4
|
||||||
private static let lengthLabelOpacity: Double = 0.75
|
private static let lengthLabelOpacity: Double = 0.75
|
||||||
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 dotSpacing: CGFloat = 4
|
||||||
private static let slotDotDiameter: CGFloat = 18
|
private static let dotDiameter: CGFloat = 18
|
||||||
private static let slotLabelFontSize: CGFloat = 10
|
private static let dotLabelFontSize: CGFloat = 10
|
||||||
private static let slotDotBrightness: Double = 0.16
|
private static let dotBrightness: Double = 0.16
|
||||||
private static let slotFilledOpacity: Double = 0.55
|
private static let dotFilledOpacity: Double = 0.55
|
||||||
private static let slotEmptyOpacity: Double = 0.45
|
private static let dotEmptyOpacity: Double = 0.45
|
||||||
private static let slotActiveRingWidth: CGFloat = 1.5
|
private static let activeRingWidth: CGFloat = 1.5
|
||||||
private static let slotLabels: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
|
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
|
// MARK: - Properties
|
||||||
|
|
||||||
private let pedal: LooperPedal
|
private let pedal: LooperPedal
|
||||||
|
|
||||||
@State private var position: Double?
|
@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 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 selectedTrack: Int = 0
|
||||||
@State private var slotContent: [Bool] = Array(repeating: false, count: LooperPedal.slotCount)
|
@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 stopArmed: Bool = false
|
||||||
|
@State private var stateDescription: String = ""
|
||||||
|
|
||||||
init(pedal: LooperPedal) {
|
init(pedal: LooperPedal) {
|
||||||
self.pedal = pedal
|
self.pedal = pedal
|
||||||
@@ -63,22 +67,24 @@ struct LooperTimelineView: View {
|
|||||||
HStack(spacing: LooperTimelineView.sectionSpacing) {
|
HStack(spacing: LooperTimelineView.sectionSpacing) {
|
||||||
stateBadge
|
stateBadge
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
slotDots
|
trackDots
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
lengthLabel
|
lengthLabel
|
||||||
}
|
}
|
||||||
track
|
track
|
||||||
|
stateIndicator
|
||||||
}
|
}
|
||||||
.task {
|
.task {
|
||||||
// Poll the pedal's transport read-outs; it isn't @Observable (RT-adjacent state).
|
|
||||||
while !Task.isCancelled {
|
while !Task.isCancelled {
|
||||||
position = pedal.playbackPosition01()
|
position = pedal.playbackPosition01()
|
||||||
state = pedal.transportState
|
state = pedal.transportState
|
||||||
lengthSeconds = pedal.loopLengthSeconds
|
lengthSeconds = pedal.loopLengthSeconds
|
||||||
lengthBeats = pedal.loopLengthBeats
|
lengthBeats = pedal.loopLengthBeats
|
||||||
activeSlot = pedal.activeSlotIndex
|
selectedTrack = pedal.selectedTrackIndex
|
||||||
slotContent = (0 ..< LooperPedal.slotCount).map { pedal.slotHasContent($0) }
|
overdubbingTrack = pedal.overdubbingTrackIndex
|
||||||
|
trackContent = (0 ..< LooperPedal.trackCount).map { pedal.trackHasContent($0) }
|
||||||
stopArmed = pedal.isStopAtLoopEndArmed
|
stopArmed = pedal.isStopAtLoopEndArmed
|
||||||
|
stateDescription = pedal.stateDescription
|
||||||
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
|
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -86,26 +92,33 @@ 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.
|
/// One tappable labelled dot per track: filled when it holds a loop, white-ringed when
|
||||||
private var slotDots: some View {
|
/// selected, red-ringed while overdubbing. Tapping selects the track.
|
||||||
HStack(spacing: LooperTimelineView.slotDotSpacing) {
|
private var trackDots: some View {
|
||||||
ForEach(0 ..< LooperPedal.slotCount, id: \.self) { index in
|
HStack(spacing: LooperTimelineView.dotSpacing) {
|
||||||
let isActive: Bool = index == activeSlot
|
ForEach(0 ..< LooperPedal.trackCount, id: \.self) { index in
|
||||||
let hasContent: Bool = index < slotContent.count && slotContent[index]
|
let isSelected: Bool = index == selectedTrack
|
||||||
Text(LooperTimelineView.slotLabels[index])
|
let isOverdub: Bool = index == overdubbingTrack
|
||||||
.font(.system(size: LooperTimelineView.slotLabelFontSize,
|
let hasContent: Bool = index < trackContent.count && trackContent[index]
|
||||||
weight: .bold, design: .monospaced))
|
Button {
|
||||||
.foregroundStyle(hasContent ? Color.white : Color.white.opacity(LooperTimelineView.slotEmptyOpacity))
|
pedal.selectTrack(index)
|
||||||
.frame(width: LooperTimelineView.slotDotDiameter, height: LooperTimelineView.slotDotDiameter)
|
} 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(
|
.background(
|
||||||
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.slotFilledOpacity)
|
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.dotFilledOpacity)
|
||||||
: Color(white: LooperTimelineView.slotDotBrightness))
|
: Color(white: LooperTimelineView.dotBrightness))
|
||||||
)
|
)
|
||||||
.overlay(
|
.overlay(
|
||||||
Circle().stroke(isActive ? Color.white : Color.clear,
|
Circle().stroke(isOverdub ? LooperTimelineView.overdubRingColor
|
||||||
lineWidth: LooperTimelineView.slotActiveRingWidth)
|
: (isSelected ? Color.white : Color.clear),
|
||||||
|
lineWidth: LooperTimelineView.activeRingWidth)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,6 +144,14 @@ struct LooperTimelineView: View {
|
|||||||
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
|
.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 {
|
private var track: some View {
|
||||||
GeometryReader { geometry in
|
GeometryReader { geometry in
|
||||||
let width: CGFloat = geometry.size.width
|
let width: CGFloat = geometry.size.width
|
||||||
@@ -143,7 +164,6 @@ struct LooperTimelineView: View {
|
|||||||
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
|
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
|
||||||
lineWidth: LooperTimelineView.borderLineWidth)
|
lineWidth: LooperTimelineView.borderLineWidth)
|
||||||
)
|
)
|
||||||
// Filled region up to the play-head, only while playing.
|
|
||||||
if position != nil {
|
if position != nil {
|
||||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||||
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
|
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
|
||||||
@@ -162,9 +182,9 @@ struct LooperTimelineView: View {
|
|||||||
|
|
||||||
private var stateColor: Color {
|
private var stateColor: Color {
|
||||||
switch state {
|
switch state {
|
||||||
case .empty: return Color(white: LooperTimelineView.emptyLedBrightness)
|
case .clear: return Color(white: 0.3)
|
||||||
case .armedRecord, .armedStop: return Color.orange
|
case .armedRecord, .armedClose: return Color.orange
|
||||||
case .recording: return Color.red
|
case .recordingMaster: return Color.red
|
||||||
case .playing: return Color.green
|
case .playing: return Color.green
|
||||||
case .stopped: return Color.orange
|
case .stopped: return Color.orange
|
||||||
}
|
}
|
||||||
@@ -172,10 +192,10 @@ struct LooperTimelineView: View {
|
|||||||
|
|
||||||
private var stateText: String {
|
private var stateText: String {
|
||||||
switch state {
|
switch state {
|
||||||
case .empty: return "EMPTY"
|
case .clear: return "CLEAR"
|
||||||
case .armedRecord: return "ARM"
|
case .armedRecord: return "ARM"
|
||||||
case .recording: return "REC"
|
case .recordingMaster: return "REC"
|
||||||
case .armedStop: return "END"
|
case .armedClose: return "END"
|
||||||
case .playing: return "PLAY"
|
case .playing: return "PLAY"
|
||||||
case .stopped: return "STOP"
|
case .stopped: return "STOP"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,9 +47,7 @@ public struct PedalButtonView: View {
|
|||||||
VStack(spacing: PedalButtonView.sectionSpacing) {
|
VStack(spacing: PedalButtonView.sectionSpacing) {
|
||||||
LEDIndicator(isOn: isOn)
|
LEDIndicator(isOn: isOn)
|
||||||
FootswitchButton(action: pedalButton.action ?? {})
|
FootswitchButton(action: pedalButton.action ?? {})
|
||||||
Text(pedalButton.label)
|
caption
|
||||||
.font(.system(size: PedalButtonView.captionFontSize))
|
|
||||||
.foregroundStyle(Color.white)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
|
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
|
||||||
@@ -61,11 +59,48 @@ public struct PedalButtonView: View {
|
|||||||
VStack(spacing: PedalButtonView.sectionSpacing) {
|
VStack(spacing: PedalButtonView.sectionSpacing) {
|
||||||
LEDIndicator(isOn: isOn)
|
LEDIndicator(isOn: isOn)
|
||||||
FootswitchButton(node: node)
|
FootswitchButton(node: node)
|
||||||
|
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)
|
Text(pedalButton.label)
|
||||||
.font(.system(size: PedalButtonView.captionFontSize))
|
.font(.system(size: PedalButtonView.captionFontSize))
|
||||||
.foregroundStyle(Color.white)
|
.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)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,9 +16,8 @@ struct LooperPedalTests {
|
|||||||
|
|
||||||
// MARK: - Test fixtures
|
// MARK: - Test fixtures
|
||||||
|
|
||||||
/// A constant-frequency sine source with a live-settable amplitude, so tests can
|
/// A constant-frequency sine source with a live-settable amplitude, so tests can silence the
|
||||||
/// silence the live input at an exact scheduled time and attribute any remaining
|
/// live input at an exact scheduled time and attribute any remaining output to the looper.
|
||||||
/// output unambiguously to the looper's own playback.
|
|
||||||
private final class ToneSource: SynthesizerBase {
|
private final class ToneSource: SynthesizerBase {
|
||||||
let ampNode: ParameterNode = ParameterNode(0.3)
|
let ampNode: ParameterNode = ParameterNode(0.3)
|
||||||
var amplitude: Double {
|
var amplitude: Double {
|
||||||
@@ -39,12 +38,8 @@ struct LooperPedalTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A no-audio synth that posts a `TriggerEvent` (via `SendTrigger.Control`) at an exact
|
/// Posts a `TriggerEvent` at an exact sample-accurate time within a single NRT render, so a
|
||||||
/// sample-accurate time within a single continuous NRT render. `build()` runs eagerly at
|
/// test can flip a looper transport action mid-render.
|
||||||
/// `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.
|
|
||||||
private final class TimedTrigger: SynthesizerBase {
|
private final class TimedTrigger: SynthesizerBase {
|
||||||
private let fireTime: Double
|
private let fireTime: Double
|
||||||
private let triggerID: Int32
|
private let triggerID: Int32
|
||||||
@@ -70,7 +65,8 @@ struct LooperPedalTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register
|
/// 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(
|
private func render(
|
||||||
totalDuration: Double,
|
totalDuration: Double,
|
||||||
toneAmplitude: Double = 0.3,
|
toneAmplitude: Double = 0.3,
|
||||||
@@ -87,15 +83,13 @@ struct LooperPedalTests {
|
|||||||
defer { try? FileManager.default.removeItem(at: url) }
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
|
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
|
||||||
let numAudioBuses: Int = 64
|
|
||||||
let numControlBuses: Int = 512
|
|
||||||
let engine: SynthesisEngine = SynthesisEngine(
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
blockSize: 512,
|
blockSize: 512,
|
||||||
sampleRate: sampleRate,
|
sampleRate: sampleRate,
|
||||||
numOutputChannels: 2,
|
numOutputChannels: 2,
|
||||||
numInputChannels: 0,
|
numInputChannels: 0,
|
||||||
numAudioBuses: numAudioBuses,
|
numAudioBuses: 64,
|
||||||
numControlBuses: numControlBuses,
|
numControlBuses: 512,
|
||||||
driver: driver
|
driver: driver
|
||||||
)
|
)
|
||||||
let listener: TriggerListener = TriggerListener(engine: engine)
|
let listener: TriggerListener = TriggerListener(engine: engine)
|
||||||
@@ -124,8 +118,6 @@ struct LooperPedalTests {
|
|||||||
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
|
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
|
||||||
try engine.add(trigger)
|
try engine.add(trigger)
|
||||||
listener.addHandler(id: id) { _, _ in
|
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() }
|
MainActor.assumeIsolated { action() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,247 +128,9 @@ struct LooperPedalTests {
|
|||||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Tests
|
/// 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
|
||||||
@Test func emptyPhasePassesDryThrough() throws {
|
/// keeps the returned (weak-referenced) engine + clock alive.
|
||||||
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.
|
|
||||||
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
|
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
|
||||||
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
|
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
|
||||||
let url: URL = FileManager.default.temporaryDirectory
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
@@ -397,8 +151,6 @@ struct LooperPedalTests {
|
|||||||
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
try engine.add(source)
|
try engine.add(source)
|
||||||
try engine.add(pedal, position: NodePosition.after(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)
|
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
|
||||||
pedal.clock = clock
|
pedal.clock = clock
|
||||||
pedal.hostEngine = engine
|
pedal.hostEngine = engine
|
||||||
@@ -406,197 +158,186 @@ struct LooperPedalTests {
|
|||||||
return (engine, clock, pedal)
|
return (engine, clock, pedal)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func beatQuantizedTransportProgressesAndReportsWholeBeatLength() throws {
|
// MARK: - Controls
|
||||||
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)
|
|
||||||
|
|
||||||
// A record press with a clock present arms for the next beat, not immediately.
|
@Test func exposesLooperControls() throws {
|
||||||
pedal.toggleRecordStop()
|
let pedal: LooperPedal = LooperPedal()
|
||||||
#expect(pedal.transportState == .armedRecord)
|
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
|
||||||
|
#expect(pedal.effectSwitches.isEmpty)
|
||||||
// Simulate the routine firing on the beat-1 boundary (0.5 s at 120 BPM).
|
#expect(pedal.effectButtons.isEmpty)
|
||||||
let startSample: SampleTime = SampleTime(sampleRate * 0.5)
|
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse", "Reset"])
|
||||||
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 slotsHoldIndependentLoopsAndSwitch() throws {
|
@Test func looperIsDoubleWidth() throws {
|
||||||
let sampleRate: Double = 44100.0
|
#expect(LooperPedal().widthUnits == 2)
|
||||||
var captured: LooperPedal?
|
#expect(LooperPedal.trackCount == 4)
|
||||||
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
|
// MARK: - Audio behaviour (immediate / un-quantized)
|
||||||
// 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.
|
@Test func clearStatePassesDryThrough() throws {
|
||||||
let aStart: Int = Int(0.85 * sampleRate) * stride
|
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
|
||||||
let backOnA: [Float] = Array(samples[aStart...])
|
#expect(hasNonSilentOutput(samples), "Cleared looper should pass the dry signal through")
|
||||||
#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 {
|
@Test func recordCloseThenPlaysAfterInputSilenced() throws {
|
||||||
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
|
let recordDuration: Double = 0.1
|
||||||
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
|
let samples: [Float] = try render(totalDuration: 0.7) { _, source, pedal, scheduleAction in
|
||||||
withExtendedLifetime(clock) {
|
pedal.pressLoop() // record track A
|
||||||
#expect(pedal.activeSlotIndex == 0)
|
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
|
||||||
for expected: Int in [1, 2, 3, 0] {
|
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, keep playing
|
||||||
pedal.cycleSlot()
|
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
|
||||||
#expect(pedal.activeSlotIndex == expected)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
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 stopPlaybackHaltsAndRecordStopResumes() throws {
|
@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 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) =
|
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
|
||||||
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
|
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
|
||||||
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
|
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
|
||||||
pedal.clock = nil // immediate (un-quantized) transport
|
pedal.clock = nil // immediate transport
|
||||||
pedal.toggleRecordStop() // recording
|
#expect(pedal.transportState == .clear)
|
||||||
pedal.toggleRecordStop() // close → playing
|
#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)
|
#expect(pedal.transportState == .playing)
|
||||||
|
|
||||||
pedal.stopPlayback()
|
pedal.stopPlayback()
|
||||||
#expect(pedal.transportState == .stopped)
|
#expect(pedal.transportState == .stopped)
|
||||||
#expect(pedal.isPlaying == 0.0)
|
#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.transportState == .playing)
|
||||||
#expect(pedal.isPlaying == 1.0)
|
#expect(pedal.isPlaying == 1.0)
|
||||||
} }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stopAtLoopEndArmsAndCancels() throws {
|
// Cue Stop arms while playing (routine waits; engine idle so it never fires here).
|
||||||
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)
|
#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()
|
pedal.toggleStopAtLoopEnd()
|
||||||
#expect(pedal.isStopAtLoopEndArmed)
|
#expect(pedal.isStopAtLoopEndArmed)
|
||||||
pedal.stopPlayback()
|
pedal.toggleStopAtLoopEnd()
|
||||||
#expect(pedal.transportState == .stopped)
|
|
||||||
#expect(!pedal.isStopAtLoopEndArmed)
|
#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) {
|
withExtendedLifetime(sg) {
|
||||||
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
|
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
|
||||||
controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only
|
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
|
// 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.
|
// transport is beat-quantized: the mapped press arms recording for the next beat.
|
||||||
|
|||||||
Reference in New Issue
Block a user