Add looper pedal: beat-quantized transport, undo, reverse, timeline

Extend the looper into a double-width tempo-aware pedal:

- Beat-quantized transport: record start and loop close both snap to the
  next beat via a LyrebirdRoutine waiting on the shared clock; loop length
  is an exact whole-beat span. Falls back to immediate/unquantized when no
  clock is present.
- Loop-length read-outs (frames/seconds/beats), transport state, and a
  sample-clock-derived play-head position for the UI timeline.
- Overdub undo (pre-dub snapshot + restore), reverse playback (live rate
  flip), and feedback-decay overdub (overdub preLevel via a Feedback knob).
- Inject the shared LyrebirdClock + SynthesisEngine into Pedal via
  PedalBoard/ChainRouter so tempo-aware pedals can reach them.
- New double-width LooperTimelineView (state badge, length read-out,
  sweeping play-head) wired into PedalView via Pedal.widthUnits.

Concurrency hardening from RT-safety review: a transportGeneration counter
drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop()
cannot recall once enqueued; the undo restore is deferred past the RT
overdub gate-close; transport routines use non-blocking stop().

Note: this commit also snapshots pre-existing uncommitted work-in-progress
already in the tree (MIDI control refactor, Tuner, Tempo, preset changes),
which is interleaved with the looper changes through shared files and could
not be split into a separately-building commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 09:22:20 -07:00
parent 097253b410
commit 947dfe427a
47 changed files with 3263 additions and 176 deletions
@@ -0,0 +1,99 @@
// ShoeGaze+Tuner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// MARK: - ShoeGaze + Tuner
extension ShoeGaze {
// MARK: - Engage / disengage
/// Engages the tuner: taps the clean pre-effects input and, if ``tunerMutesRig`` is on,
/// mutes the rig output for the duration (restoring the prior mute state on disengage).
///
/// A no-op if already engaged. Prints a note and does nothing if no input bus can be
/// resolved (mirrors `startRecording()`'s tolerant `.liveInput`/`.testLoop` fallback).
public func engageTuner() {
guard !tunerEngaged else { return }
guard let busIndex: Int = resolvedInputBusIndex() else {
print("[ShoeGaze] engageTuner: no input bus available — tuner not engaged.")
return
}
do {
// The scratch control bus is allocated once and kept for the session's
// lifetime rather than released on every disengage: `engine.remove(_:)` only
// enqueues the tap's removal for the next render block, so releasing (and
// thus making reallocatable) the bus synchronously here would race a
// not-yet-dequeued write from the outgoing tap.
let scratchBus: ControlBus
if let existing: ControlBus = tunerScratchControlBus {
scratchBus = existing
} else {
scratchBus = try engine.busAllocator.allocateControlBus()
tunerScratchControlBus = scratchBus
}
let tap: TunerTap = TunerTap(inputBusIndex: busIndex, scratchControlBus: scratchBus)
try engine.add(tap, position: .after(engine.mainGroup))
tunerTap = tap
} catch {
print("[ShoeGaze] engageTuner: could not add tuner tap. (\(error))")
return
}
if tunerMutesRig {
tunerRestoreMuteOnDisengage = rigMuted
setRigMuted(true)
}
tunerEngaged = true
}
/// Disengages the tuner and removes its tap. Restores the rig's prior mute state if
/// ``engageTuner()`` muted it.
///
/// The scratch control bus is intentionally NOT released here — see the comment in
/// ``engageTuner()``.
public func disengageTuner() {
guard tunerEngaged else { return }
if let tap: TunerTap = tunerTap {
_ = engine.remove(tap)
}
tunerTap = nil
if tunerMutesRig {
setRigMuted(tunerRestoreMuteOnDisengage)
}
tunerEngaged = false
}
/// Flips ``tunerEngaged`` — convenience for a single stomp-style toggle/MIDI action.
public func toggleTunerEngaged() {
if tunerEngaged {
disengageTuner()
} else {
engageTuner()
}
}
// MARK: - Live pitch read
/// The most recently detected pitch, in Hz, or `nil` while the tuner is not engaged.
/// Safe to poll from a SwiftUI `.task` loop on the main thread.
public var currentPitchHz: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedFrequencyHz
}
/// The YIN tracking confidence in `[0, 1]` for the current pitch, or `nil` while the
/// tuner is not engaged. `1.0` = certain, `0.0` = no stable pitch. The UI latches its
/// display when this drops below its threshold (e.g. during a note attack/restrike).
public var currentPitchConfidence: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedConfidence
}
}
@@ -0,0 +1,103 @@
// TunerPitchCapture.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Synchronization
/// Wraps a YIN `FreqTracker` and atomically snapshots its per-block frequency **and
/// confidence** into plain `Double`s readable from any thread — the same RT-writes/non-RT-
/// polls contract as `ParameterNode`'s atomic value storage, sized down to two scalars.
///
/// YIN (via `FreqTracker`) is far steadier than zero-crossing detection on a plucked/
/// harmonic-rich guitar signal, and its confidence output lets the UI latch the last stable
/// reading through low-confidence transients (note attacks, restrikes) instead of ramping
/// toward the new pitch. No smoothing is applied here — the raw YIN estimate is stable
/// enough, and any smoothing would re-introduce the ramp-on-restrike the latch is meant to
/// avoid.
///
/// Bypasses the `ControlGenerator` sub-block ramp path (matching `SendTrigger.Control`'s
/// convention for side-effecting analysis generators).
final class TunerPitchCapture: GeneratorBase, ControlGenerator {
var previousOutputValue: Double = 0.0
/// Input decimation factor for the YIN tracker. Lowers the effective analysis rate so a
/// fixed 512-sample window reaches down to the low guitar / bass range. At 48 kHz, 8×
/// gives an effective 6 kHz rate → ~23 Hz detection floor. The caller (`TunerTap`) must
/// band-limit the input below the decimated Nyquist (`sampleRate / 16`) first.
static let decimation: Int = 8
/// YIN analysis window, in decimated samples (512 is `FreqTracker`'s RT-safe maximum).
private static let fftSize: Int = 512
/// Minimum tracked frequency in Hz — below standard bass E1 (≈41 Hz) for headroom.
private static let minFreqHz: Double = 38.0
/// Maximum tracked frequency in Hz — above guitar high-E (E4 ≈330 Hz) with room for
/// upper strings / light bends, and well below the decimated Nyquist.
private static let maxFreqHz: Double = 660.0
private let tracker: FreqTracker
private let _hzBits: Atomic<UInt64>
private let _confidenceBits: Atomic<UInt64>
/// The most recent tracked frequency, in Hz. Safe to read from any thread.
var detectedFrequencyHz: Double {
Double(bitPattern: _hzBits.load(ordering: .acquiring))
}
/// The most recent tracking confidence in `[0, 1]`. Safe to read from any thread.
var detectedConfidence: Double {
Double(bitPattern: _confidenceBits.load(ordering: .acquiring))
}
/// - Parameter input: Signal to analyse for pitch — must already be band-limited below
/// the decimated Nyquist (see `TunerTap`, which applies the anti-alias lowpass).
init(input: any ValidGeneratorInput) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
tracker = FreqTracker(
in: resolvedInput,
fftSize: TunerPitchCapture.fftSize,
minFreq: TunerPitchCapture.minFreqHz,
maxFreq: TunerPitchCapture.maxFreqHz,
decimation: TunerPitchCapture.decimation
)
_hzBits = Atomic(Double(0.0).bitPattern)
_confidenceBits = Atomic(Double(0.0).bitPattern)
super.init()
_setupSubBlockBuffer()
}
// Bypass sub-block loop — one capture per audio block. `FreqTracker` processes the full
// block internally (per-sample ring fill + periodic YIN hops).
func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// `_checkCount` only bounds the top; guard the empty block so the `count - 1` last-sample
// reads below can't index `-1` (engine blockSize is ≥1 today, so this is defensive).
guard count > 0 else { return _result }
// FreqTracker is a two-channel AudioGenerator: channel 0 = Hz, channel 1 = confidence.
// Both rows are fully populated for `count` samples.
let trackerBlock: [[Double]] = tracker.calculatedSamples(graph: graph, count: count)
let hz: Double = trackerBlock[0][count - 1]
let confidence: Double = trackerBlock[1][count - 1]
_hzBits.store(hz.bitPattern, ordering: .releasing)
_confidenceBits.store(confidence.bitPattern, ordering: .releasing)
previousOutputValue = hz
for i: Int in 0..<count {
_result[0][i] = trackerBlock[0][i]
}
return _result
}
}
@@ -0,0 +1,60 @@
// TunerTap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// An internal synthesizer that taps the clean pre-effects input bus and runs a
/// `TunerPitchCapture` on it, so `ShoeGaze` can poll the current detected pitch from the
/// main thread while the tuner is engaged.
///
/// Mirrors `RecordTap`'s shape: reads one bus via `input(bus:)`, wires an analysis generator,
/// and writes to a dedicated scratch `ControlBus` purely so the engine evaluates it every
/// block — nothing downstream reads that bus.
final class TunerTap: SynthesizerBase {
/// Anti-alias lowpass cutoff, in Hz, ahead of the decimating YIN tracker. Must sit below
/// the decimated Nyquist (`sampleRate / (2 × decimation)`; ≈3 kHz at 48 kHz / 8×) so
/// decimation doesn't fold high harmonics back into the analysis band. `1200` Hz clears
/// every guitar/bass fundamental (highest is E4 ≈330 Hz) and their first harmonics — which
/// help YIN lock — while giving solid anti-alias margin.
private static let lowpassCutoffHz: Double = 1200.0
/// Butterworth Q (maximally flat, no resonant peak) for the anti-alias lowpass.
private static let lowpassQ: Double = 0.707
/// Index of the input bus to analyse.
private let inputBusIndex: Int
/// Scratch control bus the capture generator's passthrough writes to. Unread by anything
/// else — its only purpose is to give the engine a reason to evaluate the generator.
private let scratchControlBus: ControlBus
/// The pitch-capture generator created during `build()`. `nil` until `build()` has run.
private(set) var pitchCapture: TunerPitchCapture?
/// Creates a tuner tap.
///
/// - Parameters:
/// - inputBusIndex: Audio bus to analyse.
/// - scratchControlBus: A control bus reserved for this tap's unread passthrough output.
init(inputBusIndex: Int, scratchControlBus: ControlBus) {
self.inputBusIndex = inputBusIndex
self.scratchControlBus = scratchControlBus
super.init()
}
override func build() {
let source: In.Audio = input(bus: inputBusIndex)
let filtered: RBJLowPass.Audio = RBJLowPass.Audio(
input: source,
freq: TunerTap.lowpassCutoffHz,
q: TunerTap.lowpassQ
)
let capture: TunerPitchCapture = TunerPitchCapture(input: filtered)
pitchCapture = capture
output(bus: scratchControlBus, source: capture)
}
}