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:
@@ -0,0 +1,153 @@
|
||||
// LegacyMIDIMap.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Decoder for the **pre-UUID** `MIDIMap` format, which addressed pedals and boards by chain
|
||||
/// position (`boardIndex` / `pedalIndex`) rather than by stable id.
|
||||
///
|
||||
/// Used only on load: `ShoeGazeState.init(from:)` tries the current id-based `MIDIMap` first and,
|
||||
/// if that fails, decodes this legacy shape and calls ``migrated(boards:)`` to convert each
|
||||
/// positional binding to the id of the pedal/board now sitting at that position. Because the saved
|
||||
/// positions are stable, this reconstructs correct id-bindings on every load — even though the ids
|
||||
/// themselves are freshly assigned to a legacy rig each time it is decoded.
|
||||
///
|
||||
/// Bindings whose indices fall outside the loaded rig are dropped.
|
||||
struct LegacyMIDIMap: Codable {
|
||||
|
||||
var switches: [LegacySwitchBinding]
|
||||
var ccs: [LegacyCCBinding]
|
||||
|
||||
enum LegacyAction: Codable {
|
||||
case rigBypass
|
||||
case rigMute
|
||||
case allBoards
|
||||
case boardSolo(boardIndex: Int)
|
||||
case boardAudible(boardIndex: Int)
|
||||
case boardBypass(boardIndex: Int)
|
||||
case pedalBypass(boardIndex: Int, pedalIndex: Int)
|
||||
case pedalAction(boardIndex: Int, pedalIndex: Int, kind: MIDIMap.PedalActionKind)
|
||||
case tunerToggle
|
||||
case tapTempo
|
||||
}
|
||||
|
||||
enum LegacyCCTarget: Codable {
|
||||
case pedalControl(
|
||||
boardIndex: Int,
|
||||
pedalIndex: Int,
|
||||
controlIndex: Int,
|
||||
pedalNameHint: String?,
|
||||
controlLabelHint: String?
|
||||
)
|
||||
case boardLevel(boardIndex: Int, boardLabelHint: String?)
|
||||
case rigVolume
|
||||
}
|
||||
|
||||
struct LegacySwitchBinding: Codable {
|
||||
var program: UInt8
|
||||
var channel: UInt8?
|
||||
var action: LegacyAction
|
||||
var displayNameHint: String?
|
||||
}
|
||||
|
||||
struct LegacyCCBinding: Codable {
|
||||
var controller: UInt8
|
||||
var channel: UInt8?
|
||||
var target: LegacyCCTarget
|
||||
var inverted: Bool
|
||||
}
|
||||
|
||||
// MARK: - Migration
|
||||
|
||||
/// Converts this positional map to the current id-based ``MIDIMap`` using the ids of the pedals
|
||||
/// and boards in `boards` (whose ids were freshly assigned when the rig was decoded). Bindings
|
||||
/// addressing an out-of-range board/pedal are dropped.
|
||||
func migrated(boards: [BoardState]) -> MIDIMap {
|
||||
func boardID(_ index: Int) -> UUID? {
|
||||
guard index >= 0, index < boards.count else { return nil }
|
||||
return boards[index].id
|
||||
}
|
||||
func pedalID(_ boardIndex: Int, _ pedalIndex: Int) -> UUID? {
|
||||
guard boardIndex >= 0, boardIndex < boards.count else { return nil }
|
||||
let pedals: [PedalState] = boards[boardIndex].pedals
|
||||
guard pedalIndex >= 0, pedalIndex < pedals.count else { return nil }
|
||||
return pedals[pedalIndex].id
|
||||
}
|
||||
|
||||
let migratedSwitches: [MIDIMap.SwitchBinding] = switches.compactMap { binding in
|
||||
guard let action: MIDIMap.Action = migrate(binding.action, boardID: boardID, pedalID: pedalID) else {
|
||||
return nil
|
||||
}
|
||||
return MIDIMap.SwitchBinding(
|
||||
program: binding.program,
|
||||
channel: binding.channel,
|
||||
action: action,
|
||||
displayNameHint: binding.displayNameHint
|
||||
)
|
||||
}
|
||||
|
||||
let migratedCCs: [MIDIMap.CCBinding] = ccs.compactMap { binding in
|
||||
guard let target: MIDIMap.CCTarget = migrate(binding.target, boardID: boardID, pedalID: pedalID) else {
|
||||
return nil
|
||||
}
|
||||
return MIDIMap.CCBinding(
|
||||
controller: binding.controller,
|
||||
channel: binding.channel,
|
||||
target: target,
|
||||
inverted: binding.inverted
|
||||
)
|
||||
}
|
||||
|
||||
return MIDIMap(switches: migratedSwitches, ccs: migratedCCs)
|
||||
}
|
||||
|
||||
private func migrate(
|
||||
_ action: LegacyAction,
|
||||
boardID: (Int) -> UUID?,
|
||||
pedalID: (Int, Int) -> UUID?
|
||||
) -> MIDIMap.Action? {
|
||||
switch action {
|
||||
case .rigBypass: return .rigBypass
|
||||
case .rigMute: return .rigMute
|
||||
case .allBoards: return .allBoards
|
||||
case .tunerToggle: return .tunerToggle
|
||||
case .tapTempo: return .tapTempo
|
||||
case .boardSolo(let b):
|
||||
guard let id: UUID = boardID(b) else { return nil }
|
||||
return .boardSolo(boardID: id)
|
||||
case .boardAudible(let b):
|
||||
guard let id: UUID = boardID(b) else { return nil }
|
||||
return .boardAudible(boardID: id)
|
||||
case .boardBypass(let b):
|
||||
guard let id: UUID = boardID(b) else { return nil }
|
||||
return .boardBypass(boardID: id)
|
||||
case .pedalBypass(let b, let p):
|
||||
guard let id: UUID = pedalID(b, p) else { return nil }
|
||||
return .pedalBypass(pedalID: id)
|
||||
case .pedalAction(let b, let p, let kind):
|
||||
guard let id: UUID = pedalID(b, p) else { return nil }
|
||||
return .pedalAction(pedalID: id, kind: kind)
|
||||
}
|
||||
}
|
||||
|
||||
private func migrate(
|
||||
_ target: LegacyCCTarget,
|
||||
boardID: (Int) -> UUID?,
|
||||
pedalID: (Int, Int) -> UUID?
|
||||
) -> MIDIMap.CCTarget? {
|
||||
switch target {
|
||||
case .rigVolume:
|
||||
return .rigVolume
|
||||
case .pedalControl(let b, let p, let controlIndex, let nameHint, let labelHint):
|
||||
guard let id: UUID = pedalID(b, p) else { return nil }
|
||||
return .pedalControl(pedalID: id, controlIndex: controlIndex,
|
||||
pedalNameHint: nameHint, controlLabelHint: labelHint)
|
||||
case .boardLevel(let b, let labelHint):
|
||||
guard let id: UUID = boardID(b) else { return nil }
|
||||
return .boardLevel(boardID: id, boardLabelHint: labelHint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -266,26 +266,22 @@ public final class MIDIController {
|
||||
/// address is out of range or a captured display-name hint no longer matches (stale binding).
|
||||
private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? {
|
||||
switch target {
|
||||
case let .pedalControl(boardIndex, pedalIndex, controlIndex, nameHint, labelHint):
|
||||
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return nil }
|
||||
case let .pedalControl(pedalID, controlIndex, _, _):
|
||||
guard let pedal: Pedal = pedal(id: pedalID) else { return nil }
|
||||
let controls: [PedalControl] = pedal.ccMappableControls
|
||||
guard controlIndex >= 0, controlIndex < controls.count else { return nil }
|
||||
let control: PedalControl = controls[controlIndex]
|
||||
if let nameHint: String = nameHint, nameHint != pedal.displayName { return nil }
|
||||
if let labelHint: String = labelHint, labelHint != control.label { return nil }
|
||||
let hinted: MIDIMap.CCTarget = .pedalControl(
|
||||
boardIndex: boardIndex,
|
||||
pedalIndex: pedalIndex,
|
||||
pedalID: pedalID,
|
||||
controlIndex: controlIndex,
|
||||
pedalNameHint: pedal.displayName,
|
||||
controlLabelHint: control.label
|
||||
)
|
||||
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
|
||||
case let .boardLevel(boardIndex, labelHint):
|
||||
guard let board: PedalBoard = board(at: boardIndex),
|
||||
case let .boardLevel(boardID, _):
|
||||
guard let board: PedalBoard = board(id: boardID),
|
||||
let node: UIParamNode = board.masterGainNode else { return nil }
|
||||
if let labelHint: String = labelHint, labelHint != board.label { return nil }
|
||||
let hinted: MIDIMap.CCTarget = .boardLevel(boardIndex: boardIndex, boardLabelHint: board.label)
|
||||
let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label)
|
||||
return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted)
|
||||
case .rigVolume:
|
||||
// Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node.
|
||||
@@ -340,14 +336,14 @@ public final class MIDIController {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
|
||||
for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program {
|
||||
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
|
||||
perform(binding.action, hint: binding.displayNameHint)
|
||||
perform(binding.action)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
|
||||
/// `boardSolo` is exclusive (radio). Stale bindings (chain edited under the positional address)
|
||||
/// are skipped via bounds + display-name checks.
|
||||
private func perform(_ action: MIDIMap.Action, hint: String?) {
|
||||
/// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no
|
||||
/// longer exists (removed pedal/board) simply no-ops.
|
||||
private func perform(_ action: MIDIMap.Action) {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
|
||||
switch action {
|
||||
case .rigBypass:
|
||||
@@ -357,58 +353,79 @@ public final class MIDIController {
|
||||
case .allBoards:
|
||||
// One-shot: cancel any solo and bring every board back up.
|
||||
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
|
||||
case .boardSolo(let boardIndex):
|
||||
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
|
||||
case .boardSolo(let boardID):
|
||||
guard let board: PedalBoard = board(id: boardID) else { return }
|
||||
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
|
||||
case .boardAudible(let boardIndex):
|
||||
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
|
||||
case .boardAudible(let boardID):
|
||||
guard let board: PedalBoard = board(id: boardID) else { return }
|
||||
shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board),
|
||||
crossfadeSeconds: boardActionCrossfade)
|
||||
case .boardBypass(let boardIndex):
|
||||
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
|
||||
case .boardBypass(let boardID):
|
||||
guard let board: PedalBoard = board(id: boardID) else { return }
|
||||
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
|
||||
case .pedalBypass(let boardIndex, let pedalIndex):
|
||||
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return }
|
||||
if let hint: String = hint, hint != pedal.displayName { return }
|
||||
case .pedalBypass(let pedalID):
|
||||
guard let pedal: Pedal = pedal(id: pedalID) else { return }
|
||||
let engagedThreshold: Double = 0.5
|
||||
let node: UIParamNode = pedal.$bypass
|
||||
node.update(node.value < engagedThreshold ? 1.0 : 0.0)
|
||||
case .pedalAction(let pedalID, let kind):
|
||||
guard let pedal: Pedal = pedal(id: pedalID) else { return }
|
||||
performPedalAction(kind, on: pedal)
|
||||
case .tunerToggle:
|
||||
shoeGaze.toggleTunerEngaged()
|
||||
case .tapTempo:
|
||||
shoeGaze.tapTempo()
|
||||
}
|
||||
}
|
||||
|
||||
/// A display-name hint for an action, captured at learn time for stale-binding detection.
|
||||
/// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a
|
||||
/// branch here once the pedal type they target exists.
|
||||
private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) {
|
||||
let toggleThreshold: Double = 0.5
|
||||
switch kind {
|
||||
case .looperRecordStop:
|
||||
(pedal as? LooperPedal)?.toggleRecordStop()
|
||||
case .looperOverdubToggle:
|
||||
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
|
||||
let node: UIParamNode = looper.$overdubOn
|
||||
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
|
||||
case .looperLoopToggle:
|
||||
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
|
||||
let node: UIParamNode = looper.$loopOn
|
||||
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
|
||||
case .looperReset:
|
||||
(pedal as? LooperPedal)?.resetLoop()
|
||||
}
|
||||
}
|
||||
|
||||
/// A display-name hint for an action, captured at learn time for the mapping-sheet UI label.
|
||||
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
|
||||
private func hint(for action: MIDIMap.Action) -> String? {
|
||||
switch action {
|
||||
case .rigBypass, .rigMute, .allBoards:
|
||||
return nil
|
||||
case .boardSolo(let index), .boardAudible(let index), .boardBypass(let index):
|
||||
return board(at: index)?.label
|
||||
case .pedalBypass(let boardIndex, let pedalIndex):
|
||||
return pedal(boardIndex: boardIndex, pedalIndex: pedalIndex)?.displayName
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when a board still matches its captured hint (or no hint was captured).
|
||||
private func matchesBoard(_ board: PedalBoard, _ hint: String?) -> Bool {
|
||||
guard let hint: String = hint else { return true }
|
||||
return board.label == hint
|
||||
}
|
||||
|
||||
/// Resolves a board by index, or `nil` if out of range.
|
||||
private func board(at index: Int) -> PedalBoard? {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze, index >= 0, index < shoeGaze.boards.count else {
|
||||
case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID):
|
||||
return board(id: boardID)?.label
|
||||
case .pedalBypass(let pedalID), .pedalAction(let pedalID, _):
|
||||
return pedal(id: pedalID)?.displayName
|
||||
case .tunerToggle, .tapTempo:
|
||||
return nil
|
||||
}
|
||||
return shoeGaze.boards[index]
|
||||
}
|
||||
|
||||
/// Resolves a pedal by board + pedal index, or `nil` if either index is out of range.
|
||||
private func pedal(boardIndex: Int, pedalIndex: Int) -> Pedal? {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze,
|
||||
boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil }
|
||||
let board: PedalBoard = shoeGaze.boards[boardIndex]
|
||||
guard pedalIndex >= 0, pedalIndex < board.pedals.count else { return nil }
|
||||
return board.pedals[pedalIndex]
|
||||
/// Resolves a board by its stable id, or `nil` if no board in the rig has that id.
|
||||
private func board(id: UUID) -> PedalBoard? {
|
||||
shoeGaze?.boards.first { $0.id == id }
|
||||
}
|
||||
|
||||
/// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no
|
||||
/// pedal in the rig has that id.
|
||||
private func pedal(id: UUID) -> Pedal? {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze else { return nil }
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: - Device detection
|
||||
|
||||
@@ -4,13 +4,18 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and
|
||||
/// which Control Change drives which pedal knob.
|
||||
///
|
||||
/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Controls are
|
||||
/// addressed **positionally** (board index, pedal index, knob index) since boards and pedals have no
|
||||
/// stable identity; the `*Hint` fields carry the resolved display name at learn time so a binding
|
||||
/// that no longer matches (chain edited) can be detected and skipped rather than mis-fire.
|
||||
/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Pedals and
|
||||
/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in
|
||||
/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move,
|
||||
/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A
|
||||
/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry
|
||||
/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is
|
||||
/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type.
|
||||
public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
|
||||
/// Program-Change → action bindings (footswitch toggles). Populated in the switch phase.
|
||||
@@ -45,10 +50,31 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
case rigMute
|
||||
/// Cancels any solo and makes every board audible again (the "All" button).
|
||||
case allBoards
|
||||
case boardSolo(boardIndex: Int)
|
||||
case boardAudible(boardIndex: Int)
|
||||
case boardBypass(boardIndex: Int)
|
||||
case pedalBypass(boardIndex: Int, pedalIndex: Int)
|
||||
case boardSolo(boardID: UUID)
|
||||
case boardAudible(boardID: UUID)
|
||||
case boardBypass(boardID: UUID)
|
||||
case pedalBypass(pedalID: UUID)
|
||||
/// A pedal-specific momentary action beyond generic bypass (e.g. a looper's
|
||||
/// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController`
|
||||
/// resolves the target pedal (by id) and dispatches on `kind` itself.
|
||||
case pedalAction(pedalID: UUID, kind: PedalActionKind)
|
||||
/// Toggles the rig-level tuner on/off.
|
||||
case tunerToggle
|
||||
/// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`).
|
||||
case tapTempo
|
||||
}
|
||||
|
||||
/// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``.
|
||||
/// New pedals with more than a simple bypass toggle add cases here.
|
||||
public enum PedalActionKind: Codable, Equatable, Sendable {
|
||||
/// Looper: `.empty` → begin recording; `.recording` → stop and start looping.
|
||||
case looperRecordStop
|
||||
/// Looper: flips `overdubOn` between `0` and `1`.
|
||||
case looperOverdubToggle
|
||||
/// Looper: flips `loopOn` between `0` and `1`.
|
||||
case looperLoopToggle
|
||||
/// Looper: reset — clears the loop and returns to `.empty`.
|
||||
case looperReset
|
||||
}
|
||||
|
||||
// MARK: - Switch binding
|
||||
@@ -98,15 +124,14 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
|
||||
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
|
||||
case pedalControl(
|
||||
boardIndex: Int,
|
||||
pedalIndex: Int,
|
||||
pedalID: UUID,
|
||||
controlIndex: Int,
|
||||
pedalNameHint: String?,
|
||||
controlLabelHint: String?
|
||||
)
|
||||
|
||||
/// A board's master output level (the board fader).
|
||||
case boardLevel(boardIndex: Int, boardLabelHint: String?)
|
||||
case boardLevel(boardID: UUID, boardLabelHint: String?)
|
||||
|
||||
/// The rig-wide output volume (applies to the whole rig).
|
||||
case rigVolume
|
||||
@@ -115,8 +140,8 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
/// find and replace a binding regardless of the name captured at learn time).
|
||||
public func addresses(_ other: CCTarget) -> Bool {
|
||||
switch (self, other) {
|
||||
case let (.pedalControl(b1, p1, c1, _, _), .pedalControl(b2, p2, c2, _, _)):
|
||||
return b1 == b2 && p1 == p2 && c1 == c2
|
||||
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
|
||||
return p1 == p2 && c1 == c2
|
||||
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
|
||||
return b1 == b2
|
||||
case (.rigVolume, .rigVolume):
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
@@ -59,8 +60,27 @@ open class Pedal: SynthesizerBase {
|
||||
/// safe 48 kHz fallback.
|
||||
public var sampleRate: Double = 48000.0
|
||||
|
||||
// MARK: - Tempo / engine (injected)
|
||||
|
||||
/// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the
|
||||
/// looper's beat-quantized transport). `nil` for pedals added to a board that was
|
||||
/// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned
|
||||
/// by `ShoeGaze` and outlives every pedal.
|
||||
public internal(set) weak var clock: LyrebirdClock?
|
||||
|
||||
/// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by
|
||||
/// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak:
|
||||
/// the engine owns the node tree, not the reverse.
|
||||
public internal(set) weak var hostEngine: SynthesisEngine?
|
||||
|
||||
// MARK: - Identity / routing
|
||||
|
||||
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
|
||||
/// bindings to address the pedal by id rather than by chain position. Defaults to a fresh
|
||||
/// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id
|
||||
/// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits.
|
||||
public internal(set) var id: UUID = UUID()
|
||||
|
||||
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
|
||||
public let displayName: String
|
||||
|
||||
@@ -87,6 +107,11 @@ open class Pedal: SynthesizerBase {
|
||||
/// Override in a widener or stereo-native subclass.
|
||||
open var channelKind: PedalChannelKind { .mono }
|
||||
|
||||
/// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults
|
||||
/// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card.
|
||||
/// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox.
|
||||
open var widthUnits: Int { 1 }
|
||||
|
||||
/// `true` when the board has placed this pedal in a stereo (width-2) region.
|
||||
public var isStereo: Bool { outputBusRight != nil }
|
||||
|
||||
@@ -177,6 +202,16 @@ open class Pedal: SynthesizerBase {
|
||||
[]
|
||||
}
|
||||
|
||||
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
|
||||
/// buttons beneath the switch row.
|
||||
///
|
||||
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
|
||||
/// that need a non-RT side effect beyond writing a single parameter value — see
|
||||
/// ``PedalButton``. Defaults to empty.
|
||||
open var effectButtons: [PedalButton] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// All knobs a generic UI should render for this pedal: effect-specific knobs
|
||||
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
|
||||
/// surfaced separately as a header toggle, not as a knob.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
@@ -59,6 +60,10 @@ public final class PedalBoard {
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the
|
||||
/// looper) can quantize to beats. `nil` for boards created without one.
|
||||
private let clock: LyrebirdClock?
|
||||
|
||||
/// The bus that feeds the first pedal in the chain.
|
||||
public let headBus: AudioBus
|
||||
|
||||
@@ -89,6 +94,11 @@ public final class PedalBoard {
|
||||
/// call chains the first pedal after this node automatically (no `after:` arg needed).
|
||||
public internal(set) var headInputNode: (any Synthesizer)?
|
||||
|
||||
/// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to
|
||||
/// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from
|
||||
/// a saved rig restores the saved id, so a board keeps its identity across edits and reorders.
|
||||
public internal(set) var id: UUID = UUID()
|
||||
|
||||
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
|
||||
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
|
||||
public var label: String = "Board"
|
||||
@@ -153,9 +163,13 @@ public final class PedalBoard {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
|
||||
/// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for
|
||||
/// beat-quantized transport. Optional; `nil` disables quantization for pedals on
|
||||
/// this board.
|
||||
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
||||
public init(engine: SynthesisEngine) throws {
|
||||
public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws {
|
||||
self.engine = engine
|
||||
self.clock = clock
|
||||
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
self.headBus = head
|
||||
self.outputBus = head
|
||||
@@ -196,6 +210,8 @@ public final class PedalBoard {
|
||||
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
|
||||
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
|
||||
pedal.sampleRate = engine.sampleRate
|
||||
pedal.hostEngine = engine
|
||||
pedal.clock = clock
|
||||
|
||||
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
|
||||
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// PedalButton.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
|
||||
/// node-bound toggle, rendered as a stomp-style button.
|
||||
///
|
||||
/// Where ``PedalSwitch`` describes a multi-position segmented control, `PedalButton`
|
||||
/// describes a single button in one of two styles:
|
||||
/// - `.momentary`: runs a closure on each press (e.g. "Record / Stop", "Reset"). Use this
|
||||
/// whenever pressing the button must also perform a non-RT side effect (clearing a
|
||||
/// buffer, requesting a recorder reset) beyond writing a single parameter value.
|
||||
/// - `.toggle`: flips a bound ``UIParamNode`` between `0` and `1` on each press, with no
|
||||
/// side effect required — appropriate only when the live audio graph itself reads the
|
||||
/// node continuously (so toggling the raw value is sufficient).
|
||||
///
|
||||
/// A `Pedal` publishes an array of these via ``Pedal/effectButtons`` so a generic
|
||||
/// pedalboard UI can render a footswitch-style button per action without knowing the
|
||||
/// concrete pedal type.
|
||||
public struct PedalButton {
|
||||
|
||||
/// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`.
|
||||
public enum Style {
|
||||
/// Executes `action` on each press.
|
||||
case momentary
|
||||
/// Flips `node` between `0` and `1` on each press.
|
||||
case toggle
|
||||
}
|
||||
|
||||
/// Short label shown on the button (e.g. "Record", "Reset").
|
||||
public let label: String
|
||||
|
||||
/// Button behavior style.
|
||||
public let style: Style
|
||||
|
||||
/// The live parameter node this button toggles. Non-`nil` only for `.toggle` style.
|
||||
public let node: UIParamNode?
|
||||
|
||||
/// The action run on each press. Non-`nil` only for `.momentary` style.
|
||||
public let action: (() -> Void)?
|
||||
|
||||
/// Creates a momentary action button.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown on the button.
|
||||
/// - action: Closure run on each press.
|
||||
public init(label: String, action: @escaping () -> Void) {
|
||||
self.label = label
|
||||
self.style = .momentary
|
||||
self.node = nil
|
||||
self.action = action
|
||||
}
|
||||
|
||||
/// Creates a toggle button bound to a `UIParamNode`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown on the button.
|
||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property
|
||||
/// (`pedal.$overdubOn`, `pedal.$loopOn`, …).
|
||||
public init(label: String, node: UIParamNode) {
|
||||
self.label = label
|
||||
self.style = .toggle
|
||||
self.node = node
|
||||
self.action = nil
|
||||
}
|
||||
}
|
||||
@@ -93,4 +93,7 @@ public extension PedalType {
|
||||
static let octaveSplitter = PedalType("Octave Splitter")
|
||||
static let bassOctaver = PedalType("Bass Octaver")
|
||||
static let harmonizer = PedalType("Harmonizer")
|
||||
|
||||
// Looper
|
||||
static let looper = PedalType("Looper")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
// LooperPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// A loop-recorder pedal: record a take into a buffer, then play it back looping, with
|
||||
/// overdub, overdub-undo, reverse playback, feedback-decay overdub, and a crossfaded
|
||||
/// total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the transport is
|
||||
/// beat-quantized — record start and loop close both snap to the next beat, so every loop
|
||||
/// is a whole number of beats long.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → RecordBuffer.Audio (primary take, passthrough while recording) ─┐
|
||||
/// dry → RecordBuffer.Audio (overdub, gated by overdubOn × isPlaying, │ (write only)
|
||||
/// old content scaled by feedback) │
|
||||
/// loopBuffer → PlayBuffer.Audio (loop, cubic, rate ±1) │
|
||||
/// primary passthrough ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─┴→ wet
|
||||
/// ```
|
||||
///
|
||||
/// A single fixed generator graph is built once (Lyrebird's node tree does not support
|
||||
/// rebuilding a synth's internal generators). Every transport action is expressed as a
|
||||
/// live parameter change the graph already reads every block (`$overdubOn`, `$loopOn`,
|
||||
/// `$isPlaying`, `$reverse`, `$feedback`, `$playTrigger`), plus, for actions with a genuine
|
||||
/// non-RT side effect (clearing the buffer, narrowing/restoring `loopLength`, snapshotting
|
||||
/// for undo), an explicit method.
|
||||
///
|
||||
/// ## Transport (beat-quantized when a clock is present)
|
||||
/// - ``toggleRecordStop()``: `.empty` → arm/begin recording; `.recording` → close the loop
|
||||
/// and start looping. No-op while `.playing` — use ``resetLoop()`` for a new take.
|
||||
/// - `overdubOn` (via ``toggleOverdub()``): layers new input onto the loop; engaging it first
|
||||
/// snapshots the loop so ``undoOverdub()`` can revert the pass.
|
||||
/// - `loopOn` (switch): crossfaded total mute without stopping the player.
|
||||
/// - `reverse` (switch): flips playback direction (`rate` 1 → −1) without a rebuild.
|
||||
/// - ``undoOverdub()``: restores the loop to the snapshot taken when overdub was last engaged.
|
||||
/// - ``resetLoop()``: clears the buffer and returns to `.empty`.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `crossfadeTime`: Fade time constant, in seconds, for `loopOn` and the record→play handoff.
|
||||
/// - `playbackLevel`: Loop playback gain, in dB.
|
||||
/// - `overdubLevel`: Overdub input gain, in dB.
|
||||
/// - `feedback`: Retained level of existing loop content on each overdub pass, `[0, 1]`.
|
||||
/// `1.0` (default) keeps old layers forever; lower values fade them for a decaying dub.
|
||||
public final class LooperPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Records a loop, then plays it back with overdub, reverse, and a crossfaded mute."
|
||||
}
|
||||
|
||||
/// Double-width card: the looper carries a full transport plus a loop timeline and reads
|
||||
/// more comfortably in a wider enclosure.
|
||||
public override var widthUnits: Int { 2 }
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
|
||||
/// A `Lag.Control` 60 dB settling time, not a fixed-length linear ramp.
|
||||
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
|
||||
|
||||
/// Loop playback gain, in dB.
|
||||
@UIParam public var playbackLevel: Double = 0.0
|
||||
|
||||
/// Overdub input gain, in dB. Scales only the new material being layered in — the
|
||||
/// existing loop content is never attenuated by this knob.
|
||||
@UIParam public var overdubLevel: Double = 0.0
|
||||
|
||||
/// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0`
|
||||
/// keeps prior layers indefinitely; lower values fade them a little on every pass for a
|
||||
/// decaying "sound-on-sound" feedback loop.
|
||||
@UIParam public var feedback: Double = 1.0
|
||||
|
||||
// MARK: - Switches
|
||||
|
||||
/// Overdub gate. `0` = off, `1` = on. Live-gated — has no effect before a loop exists.
|
||||
@UIParam public var overdubOn: Double = 0.0
|
||||
|
||||
/// Total loop mute. `0` = muted (silent), `1` = audible. Transitions are smoothed by
|
||||
/// `crossfadeTime`.
|
||||
@UIParam public var loopOn: Double = 1.0
|
||||
|
||||
/// Playback direction. `0` = forward, `1` = reverse. Read by the player's `rate` input
|
||||
/// as `1 − 2·reverse`, so toggling flips the loop without rebuilding the graph.
|
||||
@UIParam public var reverse: Double = 0.0
|
||||
|
||||
// MARK: - Internal live state
|
||||
|
||||
/// `1` once a take has been recorded and looping playback has started, else `0`.
|
||||
/// Read by the audio graph (gates overdub and the loop crossfade) — not a user knob.
|
||||
@UIParam public var isPlaying: Double = 0.0
|
||||
|
||||
/// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close so playback
|
||||
/// starts phase-aligned to frame 0 (the anchor for the timeline read-out); rearmed to `0`
|
||||
/// on ``resetLoop()``. Read by the player's `trigger` input. Not a user knob.
|
||||
@UIParam public var playTrigger: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum recordable take length, in seconds.
|
||||
private static let maxDurationSeconds: Double = 60.0
|
||||
|
||||
/// Default crossfade duration, in seconds.
|
||||
private static let defaultCrossfadeTime: Double = 0.05
|
||||
|
||||
/// Bipolar span mapping `reverse ∈ {0, 1}` to a playback rate of `{+1, −1}`.
|
||||
private static let reverseRateSpan: Double = 2.0
|
||||
|
||||
/// Forward playback rate, and the rate offset the reverse span is subtracted from.
|
||||
private static let forwardRate: Double = 1.0
|
||||
|
||||
/// Smallest permitted loop length, in frames, so a degenerate zero-length take can't
|
||||
/// produce a divide-by-zero in the player or the timeline read-out.
|
||||
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 (`blockSize ≤ 512`) is a comfortable margin.
|
||||
private static let undoGuardFrames: Int = 1024
|
||||
|
||||
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
|
||||
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Buffer + generators
|
||||
|
||||
/// The loop buffer, sized to `maxDurationSeconds` at the engine sample rate. Allocated
|
||||
/// in `effect(_:)` (called from `build()`), not `init`, because `sampleRate` is only set
|
||||
/// by `PedalBoard.add(_:)` after construction but before the engine builds the graph.
|
||||
private var loopBuffer: LyrebirdBuffer?
|
||||
|
||||
private var primaryRecorder: RecordBuffer.Audio?
|
||||
private var overdubRecorder: RecordBuffer.Audio?
|
||||
private var player: PlayBuffer.Audio?
|
||||
|
||||
// MARK: - Transport state
|
||||
|
||||
private enum Phase {
|
||||
case empty
|
||||
case armedRecord
|
||||
case recording
|
||||
case armedStop
|
||||
case playing
|
||||
}
|
||||
|
||||
private var phase: Phase = .empty
|
||||
|
||||
/// Beat-boundary sample time at which the current take started recording, and at which
|
||||
/// the loop closes. Both are captured from the clock so the loop length is beat-exact.
|
||||
private var recordStartSample: SampleTime = 0
|
||||
|
||||
/// Sample time playback began looping (play-head at frame 0) — the timeline anchor.
|
||||
private var playStartSample: SampleTime = 0
|
||||
|
||||
/// Length of the closed loop in frames (`0` until a take is recorded).
|
||||
private var loopFrames: Int = 0
|
||||
|
||||
/// Length of the closed loop in whole beats (`0` until a beat-quantized take is closed).
|
||||
private var loopBeats: Double = 0.0
|
||||
|
||||
/// Snapshot of the loop taken when overdub was last engaged, for ``undoOverdub()``.
|
||||
private var overdubUndoSnapshot: [Double]?
|
||||
|
||||
/// Background routine that waits for the next beat before applying a transport action.
|
||||
/// Stopped (non-blocking) before starting a new one, and torn down on ``resetLoop()``.
|
||||
private var transportRoutine: LyrebirdRoutine?
|
||||
|
||||
/// Background routine that defers an undo restore until the RT overdub gate has closed.
|
||||
private var undoRoutine: LyrebirdRoutine?
|
||||
|
||||
/// Monotonic transport-action generation. Bumped on every arm and on ``resetLoop()``; a
|
||||
/// deferred beat callback carries the generation it was armed under and is dropped if the
|
||||
/// generation has since advanced — so a callback whose action was superseded (a new press,
|
||||
/// a reset) can never apply to the wrong take. Guards the `DispatchQueue.main.async` hop,
|
||||
/// 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
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a looper pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
|
||||
/// - outputBus: Audio bus to write the output to. Defaults to `0`; set by the board.
|
||||
public init(inputBus: Int = 0, outputBus: Int = 0) {
|
||||
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
|
||||
}
|
||||
|
||||
// MARK: - Knobs / switches / buttons
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Crossfade", node: $crossfadeTime, range: crossfadeTimeRange),
|
||||
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
|
||||
PedalKnob(label: "Overdub", node: $overdubLevel, range: levelRangeDb),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
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: "Loop", node: $loopOn),
|
||||
PedalButton(label: "Reverse", node: $reverse),
|
||||
PedalButton(label: "Reset") { [weak self] in self?.resetLoop() },
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - UI read-outs
|
||||
|
||||
/// Publicly-observable transport phase for the UI (LED colour, armed animation, timeline).
|
||||
public var transportState: LooperTransportState {
|
||||
switch phase {
|
||||
case .empty: return .empty
|
||||
case .armedRecord: return .armedRecord
|
||||
case .recording: return .recording
|
||||
case .armedStop: return .armedStop
|
||||
case .playing: return .playing
|
||||
}
|
||||
}
|
||||
|
||||
/// Closed-loop length in frames (`0` until a take is recorded).
|
||||
public var loopFrameCount: Int { loopFrames }
|
||||
|
||||
/// Closed-loop length in seconds (`0` until a take is recorded).
|
||||
public var loopLengthSeconds: Double { Double(loopFrames) / sampleRate }
|
||||
|
||||
/// Closed-loop length in whole beats (`0` unless the take was beat-quantized).
|
||||
public var loopLengthBeats: Double { loopBeats }
|
||||
|
||||
/// Normalised play-head position in `[0, 1)` while `.playing`, else `nil`.
|
||||
///
|
||||
/// Derived from the engine sample clock and the frame-0 playback anchor, so it tracks the
|
||||
/// audio play-head regardless of tempo. The player's play-head is reset by a `playTrigger`
|
||||
/// edge consumed at the next block boundary, so this read-out may lead the true audio
|
||||
/// play-head by up to one block (≤ ~11 ms) — imperceptible for a UI sweep. Reverse playback
|
||||
/// is reflected by mirroring the forward progress, matching the player's negated `rate`.
|
||||
public func playbackPosition01() -> Double? {
|
||||
guard phase == .playing, loopFrames > 0, let engine: SynthesisEngine = hostEngine else {
|
||||
return nil
|
||||
}
|
||||
let elapsed: SampleTime = engine.currentTime - playStartSample
|
||||
guard elapsed >= 0 else { return 0.0 }
|
||||
let framesInto: Int = Int(elapsed % SampleTime(loopFrames))
|
||||
let forward: Double = Double(framesInto) / Double(loopFrames)
|
||||
return reverse >= 0.5 ? (1.0 - forward) : forward
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
|
||||
loopBuffer = buffer
|
||||
|
||||
let primary: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||
input: dry,
|
||||
buffer: buffer,
|
||||
loop: false,
|
||||
doneAction: .nothing
|
||||
)
|
||||
primary.run = 0.0
|
||||
primaryRecorder = primary
|
||||
|
||||
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||
input: dry,
|
||||
buffer: buffer,
|
||||
loop: true,
|
||||
doneAction: .nothing
|
||||
)
|
||||
// Live-gated: only writes while a loop exists and overdub is switched on. The existing
|
||||
// loop content is scaled by `feedback` on each pass (1.0 = keep, < 1.0 = decay).
|
||||
overdub.$run.source = $overdubOn * $isPlaying
|
||||
overdub.$recLevel.source = DbAmp.Control($overdubLevel)
|
||||
overdub.$preLevel.source = $feedback
|
||||
overdubRecorder = overdub
|
||||
|
||||
// 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: buffer,
|
||||
loop: true,
|
||||
interpolation: .cubic,
|
||||
rate: playbackRate,
|
||||
trigger: $playTrigger,
|
||||
mul: DbAmp.Control($playbackLevel)
|
||||
)
|
||||
player = loopPlayer
|
||||
|
||||
// Loop audible only while playing and not muted; smoothed to avoid clicks on either
|
||||
// the record→play handoff or a loopOn toggle.
|
||||
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
|
||||
|
||||
return (primary * dryGate) + (loopPlayer * smoothedGate)
|
||||
}
|
||||
|
||||
// MARK: - Transport
|
||||
|
||||
/// `.empty` → arms/begins recording. `.recording` → closes the loop and starts looping.
|
||||
/// No-op while `.playing` or already armed.
|
||||
public func toggleRecordStop() {
|
||||
switch phase {
|
||||
case .empty:
|
||||
armRecording()
|
||||
case .recording:
|
||||
armStopAndPlay()
|
||||
case .armedRecord, .armedStop, .playing:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the overdub gate. 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 loop 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's
|
||||
/// lock-free writes into the same buffer.
|
||||
public func undoOverdub() {
|
||||
guard let buffer: LyrebirdBuffer = loopBuffer,
|
||||
let snapshot: [Double] = overdubUndoSnapshot,
|
||||
snapshot.count <= buffer.totalSampleCount else { return }
|
||||
overdubOn = 0.0
|
||||
// Advance the generation and capture it: a later reset / new take / overdub press bumps
|
||||
// the generation and drops this restore, so it can never stomp a buffer the user has
|
||||
// since cleared or re-recorded.
|
||||
transportGeneration += 1
|
||||
let generation: Int = transportGeneration
|
||||
guard let engine: SynthesisEngine = hostEngine else {
|
||||
// No engine (standalone / headless tests): single-threaded, restore immediately.
|
||||
applyUndoRestore(snapshot, 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, generation: generation) }
|
||||
}
|
||||
undoRoutine = routine
|
||||
routine.start(engine: engine)
|
||||
}
|
||||
|
||||
/// Writes an undo snapshot back into the loop buffer, unless its generation has been
|
||||
/// superseded by a reset, a new take, or a subsequent overdub/undo press.
|
||||
func applyUndoRestore(_ snapshot: [Double], generation: Int) {
|
||||
guard generation == transportGeneration,
|
||||
let buffer: LyrebirdBuffer = loopBuffer,
|
||||
snapshot.count <= buffer.totalSampleCount else { return }
|
||||
buffer.setRangeValues(snapshot, startingAt: 0)
|
||||
}
|
||||
|
||||
/// Clears the loop and returns to `.empty`, ready for a fresh take.
|
||||
public func resetLoop() {
|
||||
// Stop (non-blocking) any pending transport/undo routines and advance the generation
|
||||
// so an already-enqueued beat callback is dropped rather than applied to the new take.
|
||||
transportRoutine?.stop()
|
||||
transportRoutine = nil
|
||||
undoRoutine?.stop()
|
||||
undoRoutine = nil
|
||||
transportGeneration += 1
|
||||
primaryRecorder?.run = 0.0
|
||||
primaryRecorder?.requestReset()
|
||||
overdubRecorder?.requestReset()
|
||||
if let buffer: LyrebirdBuffer = loopBuffer {
|
||||
buffer.clear()
|
||||
buffer.setLoopLength(buffer.count)
|
||||
}
|
||||
isPlaying = 0.0
|
||||
overdubOn = 0.0
|
||||
loopOn = 1.0
|
||||
playTrigger = 0.0
|
||||
loopFrames = 0
|
||||
loopBeats = 0.0
|
||||
overdubUndoSnapshot = nil
|
||||
phase = .empty
|
||||
}
|
||||
|
||||
// MARK: - Transport helpers
|
||||
|
||||
/// Snapshots the closed-loop content into `overdubUndoSnapshot`. Called with overdub off,
|
||||
/// so only the loop player reads the buffer concurrently (a lock-free read is safe).
|
||||
private func captureOverdubSnapshot() {
|
||||
guard let buffer: LyrebirdBuffer = loopBuffer, loopFrames > 0 else { return }
|
||||
// Mono buffer: linear storage index == frame index. Called with overdub off (only the
|
||||
// player reads concurrently), so a lock-free read of the storage is safe.
|
||||
let frameCount: Int = min(loopFrames, buffer.totalSampleCount)
|
||||
var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount)
|
||||
for i: Int in 0 ..< frameCount {
|
||||
snapshot[i] = buffer[i]
|
||||
}
|
||||
overdubUndoSnapshot = snapshot
|
||||
}
|
||||
|
||||
/// A transport transition deferred to a beat boundary.
|
||||
private enum QuantizedAction: Sendable {
|
||||
case beginRecording
|
||||
case finishStop
|
||||
}
|
||||
|
||||
/// Begins recording immediately, or — with a clock — on the next beat boundary.
|
||||
private func armRecording() {
|
||||
phase = .armedRecord
|
||||
runQuantized(.beginRecording)
|
||||
}
|
||||
|
||||
/// Closes the loop immediately, or — with a clock — on the next beat boundary.
|
||||
private func armStopAndPlay() {
|
||||
phase = .armedStop
|
||||
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 (and headless tests).
|
||||
private func runQuantized(_ action: QuantizedAction) {
|
||||
transportGeneration += 1
|
||||
let generation: Int = transportGeneration
|
||||
guard let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else {
|
||||
applyQuantizedTransport(action, generation: generation, at: nil)
|
||||
return
|
||||
}
|
||||
transportRoutine?.stop()
|
||||
let target: SampleTime = clock.nextBeat()
|
||||
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
|
||||
try ctx.waitUntil(sampleTime: target)
|
||||
// The wait runs on a background thread; all pedal state changes hop to main. The
|
||||
// generation guard drops this callback if the action was superseded before it fires.
|
||||
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
|
||||
}
|
||||
transportRoutine = routine
|
||||
routine.start(engine: engine)
|
||||
}
|
||||
|
||||
/// Runs the deferred transport transition (on the main thread), unless its generation has
|
||||
/// been superseded by a newer arm or a reset.
|
||||
private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
|
||||
guard generation == transportGeneration else { return }
|
||||
switch action {
|
||||
case .beginRecording: beginRecording(at: beatSample)
|
||||
case .finishStop: finishRecordingAndPlay(at: beatSample)
|
||||
}
|
||||
}
|
||||
|
||||
func beginRecording(at beatSample: SampleTime?) {
|
||||
guard phase == .armedRecord else { return }
|
||||
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
|
||||
primaryRecorder?.run = 1.0
|
||||
phase = .recording
|
||||
}
|
||||
|
||||
func finishRecordingAndPlay(at beatSample: SampleTime?) {
|
||||
guard phase == .armedStop,
|
||||
let primary: RecordBuffer.Audio = primaryRecorder,
|
||||
let buffer: LyrebirdBuffer = loopBuffer else { return }
|
||||
primary.run = 0.0
|
||||
|
||||
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
|
||||
if let clock: LyrebirdClock = clock, beatSample != nil {
|
||||
// Beat-quantized: loop length is the exact whole-beat span between the two beat
|
||||
// boundaries, independent of any recording-position snapshot slop.
|
||||
let spanFrames: Int = Int(closeSample - recordStartSample)
|
||||
loopFrames = max(LooperPedal.minimumLoopFrames, spanFrames)
|
||||
loopBeats = beatsForSpan(frames: loopFrames, clock: clock)
|
||||
} else {
|
||||
// Un-quantized fallback: trim to the recorder's frame count.
|
||||
loopFrames = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount)
|
||||
loopBeats = 0.0
|
||||
}
|
||||
|
||||
buffer.setLoopLength(loopFrames)
|
||||
playStartSample = closeSample
|
||||
playTrigger = 1.0
|
||||
isPlaying = 1.0
|
||||
phase = .playing
|
||||
}
|
||||
|
||||
/// Whole-beat length of a `frames`-long span at the clock's *current* tempo. If the tempo
|
||||
/// changed during the take, `loopFrames` (from raw sample deltas) stays correct while this
|
||||
/// beat count — a UI read-out only, never audio — may misreport. Acceptable.
|
||||
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
|
||||
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
|
||||
guard samplesPerBeat > 0 else { return 0.0 }
|
||||
return (Double(frames) / samplesPerBeat).rounded()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// LooperTransportState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Publicly-observable transport phase of ``LooperPedal``, surfaced for the UI so it can
|
||||
/// colour the record LED, animate the "waiting for the next beat" armed states, and drive
|
||||
/// the loop timeline.
|
||||
///
|
||||
/// The two `armed…` cases exist only when the pedal has a tempo ``LyrebirdClock`` — a
|
||||
/// transport action then waits for the next beat boundary before it takes effect. Without a
|
||||
/// clock the pedal transitions straight between ``empty``, ``recording`` and ``playing``.
|
||||
public enum LooperTransportState: Sendable, Equatable {
|
||||
|
||||
/// No take recorded yet. `Record` begins recording (or arms it, with a clock).
|
||||
case empty
|
||||
|
||||
/// A `Record` has been requested and the pedal is waiting for the next beat to start.
|
||||
case armedRecord
|
||||
|
||||
/// Actively recording the primary take.
|
||||
case recording
|
||||
|
||||
/// A stop has been requested and the pedal is waiting for the next beat to close the loop.
|
||||
case armedStop
|
||||
|
||||
/// Looping playback of the recorded take (overdub / reverse / mute apply here).
|
||||
case playing
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Serialisable snapshot of one `PedalBoard`'s label and full signal-chain topology.
|
||||
///
|
||||
/// `label` is the board's display name. `segments` captures the chain in signal-flow order:
|
||||
@@ -18,6 +20,11 @@
|
||||
/// subset (the whole chain for boards with no split regions) for callers that only need it.
|
||||
public struct BoardState: Codable, Equatable {
|
||||
|
||||
/// Stable per-board identity, persisted so MIDI bindings can address a board by id rather
|
||||
/// than by position. Survives capture → rebuild round-trips. Legacy presets without an id
|
||||
/// decode to a fresh `UUID()`.
|
||||
public let id: UUID
|
||||
|
||||
/// The board's display label (e.g. `"Board 1"`).
|
||||
public let label: String
|
||||
|
||||
@@ -39,9 +46,11 @@ public struct BoardState: Codable, Equatable {
|
||||
/// - label: The board's display label.
|
||||
/// - segments: Ordered signal-chain segments.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
label: String,
|
||||
segments: [BoardSegmentState]
|
||||
) {
|
||||
self.id = id
|
||||
self.label = label
|
||||
self.segments = segments
|
||||
}
|
||||
@@ -55,14 +64,17 @@ public struct BoardState: Codable, Equatable {
|
||||
/// - label: The board's display label.
|
||||
/// - pedals: Ordered list of pedal state snapshots.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
label: String,
|
||||
pedals: [PedalState]
|
||||
) {
|
||||
self.id = id
|
||||
self.label = label
|
||||
self.segments = pedals.map { BoardSegmentState.pedal($0) }
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id
|
||||
case label
|
||||
case segments
|
||||
case pedals
|
||||
@@ -72,6 +84,7 @@ public struct BoardState: Codable, Equatable {
|
||||
/// wrapping each entry as a `.pedal` segment.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
|
||||
self.label = try container.decode(String.self, forKey: .label)
|
||||
if let decodedSegments: [BoardSegmentState] =
|
||||
try container.decodeIfPresent([BoardSegmentState].self, forKey: .segments) {
|
||||
@@ -94,6 +107,7 @@ public struct BoardState: Codable, Equatable {
|
||||
/// Encodes the snapshot using the current `segments` representation.
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(id, forKey: .id)
|
||||
try container.encode(label, forKey: .label)
|
||||
try container.encode(segments, forKey: .segments)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ extension Pedal {
|
||||
let sliderValues: [Double] = effectSliders.map { $0.node.value }
|
||||
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
|
||||
return PedalState(
|
||||
id: id,
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
switchValues: switchValues,
|
||||
@@ -44,6 +45,9 @@ extension Pedal {
|
||||
/// against `displayName` — the caller is responsible for matching types before
|
||||
/// calling this method.
|
||||
public func applyState(_ state: PedalState) {
|
||||
// Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings
|
||||
// address pedals by this id.
|
||||
id = state.id
|
||||
for (knob, value) in zip(knobs, state.knobValues) {
|
||||
knob.node.update(value)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,6 @@ extension PedalBoard {
|
||||
return BoardSegmentState.mergeToMono
|
||||
}
|
||||
}
|
||||
return BoardState(label: label, segments: segmentStates)
|
||||
return BoardState(id: id, label: label, segments: segmentStates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ public enum PedalRegistry {
|
||||
"Bitcrusher": { BitcrusherPedal() },
|
||||
"Granulator": { GranulatorPedal() },
|
||||
"Auto Granulator": { AutoGranulatorPedal() },
|
||||
"Looper": { LooperPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Serialisable snapshot of one pedal's parameter values.
|
||||
///
|
||||
/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to
|
||||
@@ -16,6 +18,12 @@
|
||||
/// knobs at their current value.
|
||||
public struct PedalState: Codable, Equatable {
|
||||
|
||||
/// Stable per-pedal identity, persisted so MIDI bindings can address a pedal by id rather
|
||||
/// than by chain position. Survives capture → rebuild round-trips (an edit rebuilds the board
|
||||
/// from captured segments, carrying each pedal's id forward). Legacy presets without an id
|
||||
/// decode to a fresh `UUID()`.
|
||||
public let id: UUID
|
||||
|
||||
/// The pedal's `displayName` — used as a factory key by `PedalRegistry`.
|
||||
public let type: String
|
||||
|
||||
@@ -47,6 +55,7 @@ public struct PedalState: Codable, Equatable {
|
||||
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
switchValues: [Double] = [],
|
||||
@@ -54,6 +63,7 @@ public struct PedalState: Codable, Equatable {
|
||||
selectorValues: [Double] = [],
|
||||
bypass: Double
|
||||
) {
|
||||
self.id = id
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.switchValues = switchValues
|
||||
@@ -63,6 +73,7 @@ public struct PedalState: Codable, Equatable {
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id
|
||||
case type
|
||||
case knobValues
|
||||
case switchValues
|
||||
@@ -75,6 +86,7 @@ public struct PedalState: Codable, Equatable {
|
||||
/// `selectorValues` existed by defaulting the missing keys to an empty array.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
|
||||
self.type = try container.decode(String.self, forKey: .type)
|
||||
self.knobValues = try container.decode([Double].self, forKey: .knobValues)
|
||||
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
|
||||
|
||||
@@ -17,9 +17,19 @@ public enum RigStore {
|
||||
private static let folderName: String = "ShoeGaze"
|
||||
private static let fileName: String = "autosave-rig.json"
|
||||
|
||||
/// Test-only override for ``autosaveURL``. When non-`nil`, all autosave reads/writes use this
|
||||
/// path instead of the real Application Support location — so a test suite never overwrites or
|
||||
/// deletes the user's actual autosaved rig. Production code leaves this `nil`.
|
||||
///
|
||||
/// - Important: Any test that calls `save`/`restore`/`clear` **must** set this to a temporary
|
||||
/// file first (and reset it after), or it will clobber the running app's autosave.
|
||||
public static var autosaveURLOverride: URL?
|
||||
|
||||
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
|
||||
/// Application Support directory can't be resolved.
|
||||
/// Application Support directory can't be resolved. Returns ``autosaveURLOverride`` verbatim
|
||||
/// when set (tests).
|
||||
public static var autosaveURL: URL? {
|
||||
if let override: URL = autosaveURLOverride { return override }
|
||||
let fileManager: FileManager = FileManager.default
|
||||
guard let base: URL = try? fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
|
||||
@@ -115,6 +115,7 @@ extension ShoeGaze {
|
||||
do {
|
||||
for boardState: BoardState in snapshot.boards {
|
||||
let board: PedalBoard = try addBoard()
|
||||
board.id = boardState.id
|
||||
board.label = boardState.label
|
||||
try rebuildSegments(boardState.segments, into: board)
|
||||
try finalizeBoard(board)
|
||||
@@ -260,9 +261,14 @@ extension ShoeGaze {
|
||||
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
|
||||
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
|
||||
|
||||
// MIDI bindings address pedals/boards by UUID (persisted in PedalState/BoardState and
|
||||
// carried through capture → rebuild), so a rebuild needs no binding reconciliation — the
|
||||
// pedal keeps its id, and its binding resolves to it regardless of chain position.
|
||||
|
||||
// Build the new board FIRST so that any failure leaves the old board intact.
|
||||
let newBoard: PedalBoard = try addBoard()
|
||||
do {
|
||||
newBoard.id = state.id
|
||||
newBoard.label = state.label
|
||||
try rebuildSegments(state.segments, into: newBoard)
|
||||
try finalizeBoard(newBoard)
|
||||
|
||||
@@ -56,15 +56,28 @@ public struct ShoeGazeState: Codable, Equatable {
|
||||
case midiMap
|
||||
}
|
||||
|
||||
/// Decodes a rig snapshot, tolerating an absent OR malformed `midiMap`.
|
||||
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
|
||||
///
|
||||
/// The MIDI map is decoded with `try?` so a binding format that this build can't read (e.g. an
|
||||
/// autosave written by an older schema) drops just the bindings — which are re-learnable —
|
||||
/// rather than throwing and losing the entire rig. `version` and `boards` still decode strictly.
|
||||
/// The MIDI map is decoded in three tiers: (1) the current id-based ``MIDIMap``; (2) failing
|
||||
/// that, the pre-UUID positional ``LegacyMIDIMap``, migrated to id-based via the boards'
|
||||
/// freshly-decoded ids so old rigs keep their bindings; (3) failing both (absent or unreadable),
|
||||
/// `nil` — dropping just the bindings, which are re-learnable, rather than losing the whole rig.
|
||||
/// `version` and `boards` still decode strictly.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.version = try container.decode(Int.self, forKey: .version)
|
||||
self.boards = try container.decode([BoardState].self, forKey: .boards)
|
||||
self.midiMap = try? container.decodeIfPresent(MIDIMap.self, forKey: .midiMap) ?? nil
|
||||
let decodedBoards: [BoardState] = try container.decode([BoardState].self, forKey: .boards)
|
||||
self.boards = decodedBoards
|
||||
|
||||
if !container.contains(.midiMap) {
|
||||
self.midiMap = nil
|
||||
} else if let current: MIDIMap = try? container.decode(MIDIMap.self, forKey: .midiMap) {
|
||||
self.midiMap = current
|
||||
} else if let legacy: LegacyMIDIMap = try? container.decode(LegacyMIDIMap.self, forKey: .midiMap) {
|
||||
// Pre-UUID positional map: convert each binding to the id now at that position.
|
||||
self.midiMap = legacy.migrated(boards: decodedBoards)
|
||||
} else {
|
||||
self.midiMap = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +172,10 @@ extension ShoeGaze {
|
||||
/// incorrect bus; the output track is still written.
|
||||
/// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil`
|
||||
/// if there are no boards; the input track is skipped and a note is printed.
|
||||
private func resolvedInputBusIndex() -> Int? {
|
||||
/// Exposed `internal` (not `private`) so other rig-level features that need the clean
|
||||
/// pre-effects input signal — e.g. `ShoeGaze+Tuner.swift` — can reuse this resolution
|
||||
/// instead of duplicating the `.liveInput`/`.testLoop` switch.
|
||||
internal func resolvedInputBusIndex() -> Int? {
|
||||
switch inputSource {
|
||||
case .liveInput(let channel):
|
||||
do {
|
||||
|
||||
@@ -104,6 +104,9 @@ public final class ChainRouter {
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
/// Shared tempo clock, forwarded to both sub-boards so tempo-aware pedals quantize to beats.
|
||||
private let clock: LyrebirdClock?
|
||||
|
||||
/// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`).
|
||||
private let source: any Synthesizer
|
||||
|
||||
@@ -152,9 +155,11 @@ public final class ChainRouter {
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
inputSource: InputSource = .testLoop
|
||||
inputSource: InputSource = .testLoop,
|
||||
clock: LyrebirdClock? = nil
|
||||
) throws {
|
||||
self.engine = engine
|
||||
self.clock = clock
|
||||
|
||||
// Step 1 — allocate the shared input bus.
|
||||
let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
@@ -186,8 +191,8 @@ public final class ChainRouter {
|
||||
self.source = addedSource
|
||||
|
||||
// Step 3 — create both boards (each allocates its own head bus).
|
||||
let createdBoardA: PedalBoard = try PedalBoard(engine: engine)
|
||||
let createdBoardB: PedalBoard = try PedalBoard(engine: engine)
|
||||
let createdBoardA: PedalBoard = try PedalBoard(engine: engine, clock: clock)
|
||||
let createdBoardB: PedalBoard = try PedalBoard(engine: engine, clock: clock)
|
||||
self.boardA = createdBoardA
|
||||
self.boardB = createdBoardB
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ public final class ShoeGaze {
|
||||
/// The engine that owns all nodes.
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Shared tempo clock for the tempo indicator / tap-tempo and any future
|
||||
/// tempo-synced features. Default `120` BPM. `reconfigureEngine(_:)` rebuilds boards
|
||||
/// against the same `engine` instance, so this clock stays valid across reconfigures.
|
||||
public let clock: LyrebirdClock
|
||||
|
||||
/// All boards managed by this instance.
|
||||
public private(set) var boards: [PedalBoard] = []
|
||||
|
||||
@@ -96,6 +101,34 @@ public final class ShoeGaze {
|
||||
/// (same module, different file) can mutate it.
|
||||
internal var recordTaps: [RecordTap] = []
|
||||
|
||||
// MARK: - Tuner state
|
||||
|
||||
/// `true` while the tuner is engaged (between `engageTuner()` and `disengageTuner()`).
|
||||
public internal(set) var tunerEngaged: Bool = false
|
||||
|
||||
/// Whether ``ShoeGaze/engageTuner()`` also mutes the rig output for the duration.
|
||||
/// Defaults to `true`. Read and applied only at engage time — toggling this while
|
||||
/// already engaged takes effect on the next engage/disengage cycle.
|
||||
public var tunerMutesRig: Bool = true
|
||||
|
||||
/// The active `TunerTap`, or `nil` while disengaged. `internal` so
|
||||
/// `ShoeGaze+Tuner.swift` (same module, different file) can mutate it.
|
||||
internal var tunerTap: TunerTap?
|
||||
|
||||
/// The scratch control bus allocated for `tunerTap`'s unread passthrough output,
|
||||
/// released on disengage.
|
||||
internal var tunerScratchControlBus: ControlBus?
|
||||
|
||||
/// `rigMuted`'s value at the moment `engageTuner()` muted the rig, so
|
||||
/// `disengageTuner()` can restore it rather than always unmuting.
|
||||
internal var tunerRestoreMuteOnDisengage: Bool = false
|
||||
|
||||
// MARK: - Tempo state
|
||||
|
||||
/// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so
|
||||
/// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it.
|
||||
internal var tapTimestamps: [Date] = []
|
||||
|
||||
// MARK: - Scope state
|
||||
|
||||
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
|
||||
@@ -139,6 +172,7 @@ public final class ShoeGaze {
|
||||
) {
|
||||
self.engine = engine
|
||||
self.inputSource = inputSource
|
||||
clock = LyrebirdClock(engine: engine, bpm: ShoeGaze.defaultTempoBpm)
|
||||
installScopeTap()
|
||||
}
|
||||
|
||||
@@ -162,7 +196,7 @@ public final class ShoeGaze {
|
||||
/// - `EngineAddError` if the engine rejects a node insertion.
|
||||
@discardableResult
|
||||
public func addBoard() throws -> PedalBoard {
|
||||
let board: PedalBoard = try PedalBoard(engine: engine)
|
||||
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
|
||||
board.label = "Board \(boards.count + 1)"
|
||||
|
||||
// Route the input source to the board head bus.
|
||||
@@ -463,6 +497,10 @@ public final class ShoeGaze {
|
||||
/// Removes a single board and its associated input source and output master from
|
||||
/// the engine, then releases the board's buses. The other boards are unaffected.
|
||||
///
|
||||
/// > Note: MIDI bindings address boards/pedals by UUID, so a removed board's bindings simply
|
||||
/// > stop resolving (inert, and invisible in the mapping UI since there is no board/pedal to
|
||||
/// > list) — no binding maintenance is needed here.
|
||||
///
|
||||
/// - Important: Same async-removal caveat as ``teardown()`` — call with the engine
|
||||
/// stopped, or accept up to one block of glitch on a still-running engine.
|
||||
///
|
||||
@@ -548,7 +586,7 @@ public final class ShoeGaze {
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
@discardableResult
|
||||
public func makeChainRouter() throws -> ChainRouter {
|
||||
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource)
|
||||
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource, clock: clock)
|
||||
routers.append(router)
|
||||
return router
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// ShoeGaze+Tempo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ShoeGaze + Tempo
|
||||
|
||||
extension ShoeGaze {
|
||||
|
||||
/// Default tempo, in BPM, for a newly-created ``ShoeGaze/clock``.
|
||||
public static let defaultTempoBpm: Double = 120.0
|
||||
|
||||
// MARK: - Tap tempo
|
||||
|
||||
/// Minimum plausible interval between taps, in seconds — guards against a double-tap
|
||||
/// or debounce glitch registering as an implausibly fast tempo (`60 / minTapInterval`
|
||||
/// ≈ 300 BPM cap).
|
||||
private static let minTapInterval: TimeInterval = 0.2
|
||||
|
||||
/// Maximum interval since the last tap before the tap history resets — a pause this
|
||||
/// long means the user is starting a new tap-tempo sequence, not continuing one.
|
||||
private static let tapTimeoutInterval: TimeInterval = 2.0
|
||||
|
||||
/// Number of most-recent inter-tap intervals averaged into the computed tempo.
|
||||
private static let tapHistoryCount: Int = 4
|
||||
|
||||
/// Registers one tap-tempo press. Call this each time the user taps (mouse click,
|
||||
/// screen tap, or MIDI trigger). Averages the last few inter-tap intervals and sets
|
||||
/// ``ShoeGaze/clock``'s `bpm` once at least two taps have landed within
|
||||
/// `tapTimeoutInterval` of each other. A pause longer than `tapTimeoutInterval`
|
||||
/// discards prior taps and starts a fresh sequence.
|
||||
public func tapTempo() {
|
||||
let now: Date = Date()
|
||||
if let last: Date = tapTimestamps.last, now.timeIntervalSince(last) > ShoeGaze.tapTimeoutInterval {
|
||||
tapTimestamps.removeAll()
|
||||
}
|
||||
tapTimestamps.append(now)
|
||||
if tapTimestamps.count > ShoeGaze.tapHistoryCount + 1 {
|
||||
tapTimestamps.removeFirst(tapTimestamps.count - (ShoeGaze.tapHistoryCount + 1))
|
||||
}
|
||||
guard tapTimestamps.count >= 2 else { return }
|
||||
|
||||
let intervals: [TimeInterval] = zip(tapTimestamps, tapTimestamps.dropFirst())
|
||||
.map { $1.timeIntervalSince($0) }
|
||||
.filter { $0 >= ShoeGaze.minTapInterval }
|
||||
guard !intervals.isEmpty else { return }
|
||||
|
||||
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
|
||||
let secondsPerMinute: Double = 60.0
|
||||
clock.bpm = secondsPerMinute / averageInterval
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// LooperTimelineView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// The looper's loop timeline: a transport-state label, a loop-length read-out, and a track
|
||||
/// with a sweeping play-head. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
|
||||
///
|
||||
/// `LooperPedal`'s transport state is plain (non-`@Observable`) RT-adjacent data, so this view
|
||||
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out — rather
|
||||
/// than relying on SwiftUI change tracking.
|
||||
struct LooperTimelineView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let trackHeight: CGFloat = 16
|
||||
private static let trackCornerRadius: CGFloat = 4
|
||||
private static let playheadWidth: CGFloat = 2
|
||||
private static let sectionSpacing: CGFloat = 6
|
||||
private static let labelFontSize: CGFloat = 11
|
||||
private static let trackBrightness: Double = 0.14
|
||||
private static let trackBorderOpacity: Double = 0.35
|
||||
private static let filledOpacity: Double = 0.22
|
||||
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
|
||||
private static let ledDiameter: CGFloat = 9
|
||||
private static let badgeInnerSpacing: CGFloat = 4
|
||||
private static let lengthLabelOpacity: Double = 0.75
|
||||
private static let emptyLedBrightness: Double = 0.3
|
||||
private static let borderLineWidth: CGFloat = 1
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let pedal: LooperPedal
|
||||
|
||||
@State private var position: Double?
|
||||
@State private var state: LooperTransportState = .empty
|
||||
@State private var lengthSeconds: Double = 0.0
|
||||
@State private var lengthBeats: Double = 0.0
|
||||
|
||||
init(pedal: LooperPedal) {
|
||||
self.pedal = pedal
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: LooperTimelineView.sectionSpacing) {
|
||||
HStack(spacing: LooperTimelineView.sectionSpacing) {
|
||||
stateBadge
|
||||
Spacer(minLength: 0)
|
||||
lengthLabel
|
||||
}
|
||||
track
|
||||
}
|
||||
.task {
|
||||
// Poll the pedal's transport read-outs; it isn't @Observable (RT-adjacent state).
|
||||
while !Task.isCancelled {
|
||||
position = pedal.playbackPosition01()
|
||||
state = pedal.transportState
|
||||
lengthSeconds = pedal.loopLengthSeconds
|
||||
lengthBeats = pedal.loopLengthBeats
|
||||
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private var stateBadge: some View {
|
||||
HStack(spacing: LooperTimelineView.badgeInnerSpacing) {
|
||||
Circle()
|
||||
.fill(stateColor)
|
||||
.frame(width: LooperTimelineView.ledDiameter, height: LooperTimelineView.ledDiameter)
|
||||
Text(stateText)
|
||||
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
private var lengthLabel: some View {
|
||||
Text(lengthText)
|
||||
.font(.system(size: LooperTimelineView.labelFontSize, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
|
||||
}
|
||||
|
||||
private var track: some View {
|
||||
GeometryReader { geometry in
|
||||
let width: CGFloat = geometry.size.width
|
||||
let pos: CGFloat = CGFloat(position ?? 0.0)
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.fill(Color(white: LooperTimelineView.trackBrightness))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
|
||||
lineWidth: LooperTimelineView.borderLineWidth)
|
||||
)
|
||||
// Filled region up to the play-head, only while playing.
|
||||
if position != nil {
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
|
||||
.frame(width: max(0, pos * width))
|
||||
Rectangle()
|
||||
.fill(Color.white)
|
||||
.frame(width: LooperTimelineView.playheadWidth)
|
||||
.offset(x: min(max(0, pos * width), width - LooperTimelineView.playheadWidth))
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(height: LooperTimelineView.trackHeight)
|
||||
}
|
||||
|
||||
// MARK: - State mapping
|
||||
|
||||
private var stateColor: Color {
|
||||
switch state {
|
||||
case .empty: return Color(white: LooperTimelineView.emptyLedBrightness)
|
||||
case .armedRecord, .armedStop: return Color.orange
|
||||
case .recording: return Color.red
|
||||
case .playing: return Color.green
|
||||
}
|
||||
}
|
||||
|
||||
private var stateText: String {
|
||||
switch state {
|
||||
case .empty: return "EMPTY"
|
||||
case .armedRecord: return "ARM"
|
||||
case .recording: return "REC"
|
||||
case .armedStop: return "END"
|
||||
case .playing: return "PLAY"
|
||||
}
|
||||
}
|
||||
|
||||
private var lengthText: String {
|
||||
guard lengthSeconds > 0 else { return "--" }
|
||||
let seconds: String = String(format: "%.2fs", lengthSeconds)
|
||||
guard lengthBeats > 0 else { return seconds }
|
||||
return seconds + " · \(Int(lengthBeats)) beat" + (lengthBeats == 1 ? "" : "s")
|
||||
}
|
||||
}
|
||||
@@ -102,23 +102,22 @@ public struct MIDIMappingSheet: View {
|
||||
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
|
||||
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
|
||||
]
|
||||
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
|
||||
let boardIndex: Int = boardPair.offset
|
||||
let board: PedalBoard = boardPair.element
|
||||
rows.append(SwitchRowModel(id: "sw-solo-\(boardIndex)",
|
||||
action: .boardSolo(boardIndex: boardIndex),
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
let boardID: UUID = board.id
|
||||
rows.append(SwitchRowModel(id: "sw-solo-\(boardID)",
|
||||
action: .boardSolo(boardID: boardID),
|
||||
label: "\(board.label) · Solo"))
|
||||
rows.append(SwitchRowModel(id: "sw-aud-\(boardIndex)",
|
||||
action: .boardAudible(boardIndex: boardIndex),
|
||||
rows.append(SwitchRowModel(id: "sw-aud-\(boardID)",
|
||||
action: .boardAudible(boardID: boardID),
|
||||
label: "\(board.label) · Audible"))
|
||||
rows.append(SwitchRowModel(id: "sw-byp-\(boardIndex)",
|
||||
action: .boardBypass(boardIndex: boardIndex),
|
||||
rows.append(SwitchRowModel(id: "sw-byp-\(boardID)",
|
||||
action: .boardBypass(boardID: boardID),
|
||||
label: "\(board.label) · Bypass"))
|
||||
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
|
||||
for pedal: Pedal in board.pedals {
|
||||
rows.append(SwitchRowModel(
|
||||
id: "sw-pb-\(boardIndex)-\(pedalPair.offset)",
|
||||
action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset),
|
||||
label: "\(board.label) · \(pedalPair.element.displayName) · Bypass"))
|
||||
id: "sw-pb-\(pedal.id)",
|
||||
action: .pedalBypass(pedalID: pedal.id),
|
||||
label: "\(board.label) · \(pedal.displayName) · Bypass"))
|
||||
}
|
||||
}
|
||||
return rows
|
||||
@@ -128,23 +127,18 @@ public struct MIDIMappingSheet: View {
|
||||
var rows: [CCRowModel] = [
|
||||
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
|
||||
]
|
||||
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
|
||||
let boardIndex: Int = boardPair.offset
|
||||
let board: PedalBoard = boardPair.element
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
// Board master level (the board fader).
|
||||
rows.append(CCRowModel(
|
||||
id: "cc-blvl-\(boardIndex)",
|
||||
target: .boardLevel(boardIndex: boardIndex, boardLabelHint: nil),
|
||||
id: "cc-blvl-\(board.id)",
|
||||
target: .boardLevel(boardID: board.id, boardLabelHint: nil),
|
||||
label: "\(board.label) · Level"))
|
||||
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
|
||||
let pedalIndex: Int = pedalPair.offset
|
||||
let pedal: Pedal = pedalPair.element
|
||||
for pedal: Pedal in board.pedals {
|
||||
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
|
||||
rows.append(CCRowModel(
|
||||
id: "cc-\(boardIndex)-\(pedalIndex)-\(controlPair.offset)",
|
||||
id: "cc-\(pedal.id)-\(controlPair.offset)",
|
||||
target: .pedalControl(
|
||||
boardIndex: boardIndex,
|
||||
pedalIndex: pedalIndex,
|
||||
pedalID: pedal.id,
|
||||
controlIndex: controlPair.offset,
|
||||
pedalNameHint: nil,
|
||||
controlLabelHint: nil),
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// PedalButtonView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
// MARK: - PedalButtonView
|
||||
|
||||
/// A stomp-style action button rendered from a ``PedalButton`` descriptor.
|
||||
///
|
||||
/// `.momentary` renders a plain `ParameterButton`. `.toggle` renders the same LED +
|
||||
/// footswitch look as the pedal's own bypass control (`PedalView`'s `LEDIndicator` /
|
||||
/// `FootswitchButton`), with a caption label beneath — so a looper's Overdub/Loop toggles
|
||||
/// read as stomp switches with state, not a segmented picker.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// PedalButtonView(pedalButton)
|
||||
/// ```
|
||||
public struct PedalButtonView: View {
|
||||
|
||||
private static let toggleOnThreshold: Double = 0.5
|
||||
private static let sectionSpacing: CGFloat = 6
|
||||
private static let captionFontSize: CGFloat = 11
|
||||
|
||||
private let pedalButton: PedalButton
|
||||
|
||||
/// Creates a button view from a descriptor.
|
||||
///
|
||||
/// - Parameter pedalButton: The button to render.
|
||||
public init(_ pedalButton: PedalButton) {
|
||||
self.pedalButton = pedalButton
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
switch pedalButton.style {
|
||||
case .momentary:
|
||||
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
|
||||
case .toggle:
|
||||
if let node: UIParamNode = pedalButton.node {
|
||||
// Reading `node.value` registers this view for @Observable re-render.
|
||||
let isOn: Bool = node.value >= PedalButtonView.toggleOnThreshold
|
||||
VStack(spacing: PedalButtonView.sectionSpacing) {
|
||||
LEDIndicator(isOn: isOn)
|
||||
FootswitchButton(node: node)
|
||||
Text(pedalButton.label)
|
||||
.font(.system(size: PedalButtonView.captionFontSize))
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,11 @@ private struct ScrewDot: View {
|
||||
|
||||
/// A small circular LED that glows green when the effect is engaged.
|
||||
///
|
||||
/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed.
|
||||
/// The LED is lit when `bypassValue < 0.5`.
|
||||
private struct LEDIndicator: View {
|
||||
/// A small round LED, lit green when `isOn` and dark otherwise. Polarity-agnostic — the
|
||||
/// caller decides what `isOn` means for its own control (e.g. bypass's `value < 0.5`, or a
|
||||
/// plain toggle's `value >= 0.5`). `internal` (not `private`) so other views in this module
|
||||
/// (e.g. `PedalButtonView`) can reuse the same stompbox LED look.
|
||||
struct LEDIndicator: View {
|
||||
|
||||
private static let diameter: CGFloat = 10
|
||||
private static let glowRadius: CGFloat = 6
|
||||
@@ -101,13 +103,11 @@ private struct LEDIndicator: View {
|
||||
private static let dimBrightness: Double = 0.15
|
||||
private static let rimStrokeOpacity: Double = 0.30
|
||||
|
||||
let bypassValue: Double
|
||||
|
||||
private var isEngaged: Bool { bypassValue < 0.5 }
|
||||
let isOn: Bool
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
if isEngaged {
|
||||
if isOn {
|
||||
Circle()
|
||||
.fill(Color.green.opacity(LEDIndicator.glowOpacity))
|
||||
.frame(
|
||||
@@ -117,7 +117,7 @@ private struct LEDIndicator: View {
|
||||
.blur(radius: LEDIndicator.glowRadius / 2)
|
||||
}
|
||||
Circle()
|
||||
.fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness))
|
||||
.fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness))
|
||||
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
|
||||
.overlay(
|
||||
Circle()
|
||||
@@ -132,8 +132,10 @@ private struct LEDIndicator: View {
|
||||
|
||||
// MARK: - Footswitch
|
||||
|
||||
/// A round footswitch-style button that toggles bypass on/off.
|
||||
private struct FootswitchButton: View {
|
||||
/// A round footswitch-style button that flips a `UIParamNode` between `0` and `1`.
|
||||
/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can
|
||||
/// reuse the same stompbox footswitch look for non-bypass toggles.
|
||||
struct FootswitchButton: View {
|
||||
|
||||
private static let diameter: CGFloat = 44
|
||||
private static let strokeWidth: CGFloat = 2.5
|
||||
@@ -291,9 +293,11 @@ public struct PedalView: View {
|
||||
// Content stack
|
||||
VStack(spacing: PedalView.sectionSpacing) {
|
||||
namePlate
|
||||
looperTimeline
|
||||
knobGrid
|
||||
selectorRow
|
||||
switchRow
|
||||
buttonRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
bottomControls
|
||||
@@ -334,6 +338,15 @@ public struct PedalView: View {
|
||||
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
|
||||
}
|
||||
|
||||
/// Loop timeline strip — rendered only for the double-width `LooperPedal`, between the
|
||||
/// name plate and the knob grid. Other pedals render nothing here.
|
||||
@ViewBuilder
|
||||
private var looperTimeline: some View {
|
||||
if let looper: LooperPedal = pedal as? LooperPedal {
|
||||
LooperTimelineView(pedal: looper)
|
||||
}
|
||||
}
|
||||
|
||||
/// Info button tucked just under the top-left corner screw.
|
||||
private var infoButton: some View {
|
||||
Button {
|
||||
@@ -417,6 +430,22 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of stomp-style action buttons drawn from `pedal.effectButtons`, beneath the
|
||||
/// switch row. Renders nothing when the pedal publishes no buttons.
|
||||
@ViewBuilder
|
||||
private var buttonRow: some View {
|
||||
let buttons: [PedalButton] = pedal.effectButtons
|
||||
if !buttons.isEmpty {
|
||||
HStack(spacing: PedalView.knobRowItemSpacing) {
|
||||
Spacer(minLength: 0)
|
||||
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
|
||||
PedalButtonView(pair.element)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row.
|
||||
/// Renders nothing when the pedal publishes no sliders.
|
||||
@ViewBuilder
|
||||
@@ -431,16 +460,19 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank
|
||||
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
|
||||
/// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits`
|
||||
/// (a control-dense pedal such as the looper asks for a double-width card), widened
|
||||
/// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its
|
||||
/// faders are never clipped.
|
||||
private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat {
|
||||
let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits))
|
||||
let sliderCount: Int = sliders.count
|
||||
guard sliderCount > 0 else { return PedalView.enclosureWidth }
|
||||
guard sliderCount > 0 else { return unitWidth }
|
||||
let bankContentWidth: CGFloat =
|
||||
CGFloat(sliderCount) * PedalView.sliderBankItemWidth
|
||||
+ CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing
|
||||
let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding
|
||||
return max(PedalView.enclosureWidth, needed)
|
||||
return max(unitWidth, needed)
|
||||
}
|
||||
|
||||
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
|
||||
@@ -479,9 +511,10 @@ public struct PedalView: View {
|
||||
// re-renders whenever the bypass parameter changes on the main thread
|
||||
// (UIParamNode is @Observable).
|
||||
let bypassValue: Double = pedal.$bypass.value
|
||||
let engagedThreshold: Double = 0.5
|
||||
|
||||
return VStack(spacing: PedalView.bypassSectionSpacing) {
|
||||
LEDIndicator(bypassValue: bypassValue)
|
||||
LEDIndicator(isOn: bypassValue < engagedThreshold)
|
||||
FootswitchButton(node: pedal.$bypass)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,9 +533,12 @@ public struct ShoeGazeBuilderView: View {
|
||||
private var transportRow: some View {
|
||||
_ = transportTick
|
||||
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||||
Text("ShoeGaze Builder")
|
||||
.font(.title2).bold()
|
||||
.foregroundStyle(Color.white)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text("ShoeGaze Builder")
|
||||
.font(.title2).bold()
|
||||
.foregroundStyle(Color.white)
|
||||
currentRigLabel
|
||||
}
|
||||
if shoeGaze.isRecording {
|
||||
// Recording indicator (both platforms; recording is driven from the macOS Record
|
||||
// menu or the iOS controls below).
|
||||
@@ -549,6 +552,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
TempoView(shoeGaze: shoeGaze)
|
||||
TunerView(shoeGaze: shoeGaze)
|
||||
if let midi: MIDIController = midi {
|
||||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||||
}
|
||||
@@ -729,6 +734,11 @@ public struct ShoeGazeBuilderView: View {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
|
||||
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
|
||||
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
|
||||
// re-resolve onto the fresh board's pedals.
|
||||
shoeGaze.midiMap = nil
|
||||
|
||||
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
|
||||
for board: PedalBoard in Array(shoeGaze.boards) {
|
||||
shoeGaze.removeBoard(board)
|
||||
@@ -1096,6 +1106,32 @@ public struct ShoeGazeBuilderView: View {
|
||||
return library.entries.first(where: { $0.id == id })?.name
|
||||
}
|
||||
|
||||
/// A subtitle under the app title showing which rig is loaded. Resolves the name from the
|
||||
/// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig
|
||||
/// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries`
|
||||
/// so it refreshes automatically when a rig is loaded or the library finishes loading.
|
||||
private var currentRigLabel: some View {
|
||||
let hasSource: Bool = currentRigID != nil
|
||||
let name: String
|
||||
if let resolved: String = currentRigName() {
|
||||
name = resolved
|
||||
} else if hasSource {
|
||||
// Source id exists but the library hasn't resolved it yet (still loading).
|
||||
name = library.isLoaded ? "Unknown rig" : "Loading…"
|
||||
} else {
|
||||
name = "Unsaved rig"
|
||||
}
|
||||
return HStack(spacing: 5) {
|
||||
Image(systemName: hasSource ? "guitars.fill" : "guitars")
|
||||
.font(.caption2)
|
||||
Text(name)
|
||||
.font(.caption)
|
||||
.lineLimit(1)
|
||||
}
|
||||
.foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5))
|
||||
.help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet")
|
||||
}
|
||||
|
||||
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
|
||||
private func defaultNewRigName() -> String {
|
||||
let base: String = "Rig"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// TempoView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that
|
||||
/// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger).
|
||||
///
|
||||
/// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter
|
||||
/// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT
|
||||
/// state, not push-notified UI state.
|
||||
public struct TempoView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz
|
||||
/// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink.
|
||||
private static let flashDutyCycle: Double = 0.15
|
||||
private static let minBpm: Double = 30.0
|
||||
private static let maxBpm: Double = 300.0
|
||||
private static let bpmStep: Double = 1.0
|
||||
private static let ledDiameter: CGFloat = 16
|
||||
private static let panelSpacing: CGFloat = 10
|
||||
private static let rowSpacing: CGFloat = 14
|
||||
private static let tapAreaSize: CGFloat = 64
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
|
||||
@State private var displayedBpm: Double
|
||||
@State private var ledOn: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: TempoView.panelSpacing) {
|
||||
HStack(spacing: TempoView.rowSpacing) {
|
||||
led
|
||||
Text("\(Int(displayedBpm.rounded())) BPM")
|
||||
.font(.system(size: 18, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
Stepper(
|
||||
"",
|
||||
value: Binding(
|
||||
get: { displayedBpm },
|
||||
set: { newValue in
|
||||
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
|
||||
shoeGaze.clock.bpm = clamped
|
||||
displayedBpm = clamped
|
||||
}
|
||||
),
|
||||
in: TempoView.minBpm ... TempoView.maxBpm,
|
||||
step: TempoView.bpmStep
|
||||
)
|
||||
.labelsHidden()
|
||||
}
|
||||
|
||||
tapArea
|
||||
}
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
let beat: Double = shoeGaze.clock.currentBeat
|
||||
let phase: Double = beat - beat.rounded(.down)
|
||||
ledOn = phase < TempoView.flashDutyCycle
|
||||
displayedBpm = shoeGaze.clock.bpm
|
||||
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private var led: some View {
|
||||
Circle()
|
||||
.fill(ledOn ? Color.red : Color.red.opacity(0.15))
|
||||
.frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter)
|
||||
}
|
||||
|
||||
private var tapArea: some View {
|
||||
Button {
|
||||
shoeGaze.tapTempo()
|
||||
displayedBpm = shoeGaze.clock.bpm
|
||||
} label: {
|
||||
Text("TAP")
|
||||
.font(.system(size: 14, weight: .bold, design: .rounded))
|
||||
.frame(width: TempoView.tapAreaSize, height: TempoView.tapAreaSize)
|
||||
.background(Color.white.opacity(0.08))
|
||||
.clipShape(Circle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// TunerView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Chromatic tuner panel: an engage toggle, a mute-rig-while-tuning toggle, and a live
|
||||
/// note/cents readout.
|
||||
///
|
||||
/// Polls ``ShoeGaze/currentPitchHz`` on a `.task` loop (matching `LyrebirdEngineStatusView`'s
|
||||
/// CPU-meter convention) since the value is computed from RT-thread state on demand, not an
|
||||
/// `@Observable`-tracked property. Polling only runs while the tuner is engaged.
|
||||
public struct TunerView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let pollIntervalNanoseconds: UInt64 = 250_000_000 // 4 Hz, at most
|
||||
private static let inTuneCentsThreshold: Double = 5.0
|
||||
private static let closeCentsThreshold: Double = 15.0
|
||||
/// Below this YIN confidence the reading is treated as untracked — the last stable pitch
|
||||
/// is latched and the display dims, rather than chasing a transient/attack estimate.
|
||||
private static let trackingConfidenceThreshold: Double = 0.8
|
||||
/// Opacity applied to the latched readout while not actively tracking.
|
||||
private static let untrackedOpacity: Double = 0.35
|
||||
private static let panelSpacing: CGFloat = 10
|
||||
private static let rowSpacing: CGFloat = 14
|
||||
private static let noteFontSize: CGFloat = 34
|
||||
private static let statusFontSize: CGFloat = 10
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
|
||||
/// Last pitch accepted at or above the confidence threshold (latched through dropouts).
|
||||
@State private var latchedPitch: TunerPitchReading?
|
||||
/// `true` when the most recent poll was above the confidence threshold.
|
||||
@State private var isTracking: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameter shoeGaze: The session whose tuner state this view controls and displays.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: TunerView.panelSpacing) {
|
||||
HStack(spacing: TunerView.rowSpacing) {
|
||||
Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") {
|
||||
shoeGaze.toggleTunerEngaged()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(shoeGaze.tunerEngaged ? .green : .gray)
|
||||
|
||||
Toggle("Mute rig", isOn: Binding(
|
||||
get: { shoeGaze.tunerMutesRig },
|
||||
set: { shoeGaze.tunerMutesRig = $0 }
|
||||
))
|
||||
.toggleStyle(.switch)
|
||||
}
|
||||
|
||||
if shoeGaze.tunerEngaged {
|
||||
readout
|
||||
}
|
||||
}
|
||||
.task(id: shoeGaze.tunerEngaged) {
|
||||
while shoeGaze.tunerEngaged && !Task.isCancelled {
|
||||
updateReading()
|
||||
try? await Task.sleep(nanoseconds: TunerView.pollIntervalNanoseconds)
|
||||
}
|
||||
if !shoeGaze.tunerEngaged {
|
||||
latchedPitch = nil
|
||||
isTracking = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls freq + confidence. Above the confidence threshold, updates the latched pitch
|
||||
/// and marks tracking active; below it, leaves the latched pitch in place (so restrikes
|
||||
/// don't make the reading ramp) and marks tracking inactive.
|
||||
private func updateReading() {
|
||||
let confidence: Double = shoeGaze.currentPitchConfidence ?? 0.0
|
||||
let hz: Double = shoeGaze.currentPitchHz ?? 0.0
|
||||
if confidence >= TunerView.trackingConfidenceThreshold && hz > 0 {
|
||||
latchedPitch = TunerPitchReading(hz: hz)
|
||||
isTracking = true
|
||||
} else {
|
||||
isTracking = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Readout
|
||||
|
||||
@ViewBuilder
|
||||
private var readout: some View {
|
||||
if let pitch: TunerPitchReading = latchedPitch {
|
||||
VStack(spacing: 6) {
|
||||
Text(pitch.noteName)
|
||||
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(TunerView.color(forCents: pitch.cents))
|
||||
TunerCentsMeter(cents: pitch.cents)
|
||||
Text(isTracking ? "TRACKING" : "…")
|
||||
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(0.5))
|
||||
}
|
||||
.opacity(isTracking ? 1.0 : TunerView.untrackedOpacity)
|
||||
} else {
|
||||
VStack(spacing: 6) {
|
||||
Text("—")
|
||||
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(Color.white.opacity(0.4))
|
||||
Text("play a note")
|
||||
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(0.4))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func color(forCents cents: Double) -> Color {
|
||||
let magnitude: Double = abs(cents)
|
||||
if magnitude <= TunerView.inTuneCentsThreshold { return .green }
|
||||
if magnitude <= TunerView.closeCentsThreshold { return .yellow }
|
||||
return .red
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TunerCentsMeter
|
||||
|
||||
/// A horizontal -50…+50 cents meter: a track with a centre "in tune" tick and a vertical
|
||||
/// marker positioned at the current deviation, coloured with the same red/yellow/green
|
||||
/// thresholds as the note readout.
|
||||
struct TunerCentsMeter: View {
|
||||
|
||||
private static let range: Double = 50.0
|
||||
private static let trackWidth: CGFloat = 140
|
||||
private static let trackHeight: CGFloat = 4
|
||||
private static let markerWidth: CGFloat = 3
|
||||
private static let markerHeight: CGFloat = 18
|
||||
private static let centerTickWidth: CGFloat = 1.5
|
||||
private static let centerTickHeight: CGFloat = 10
|
||||
|
||||
let cents: Double
|
||||
|
||||
private var clampedFraction: Double {
|
||||
// Maps [-range, +range] to [0, 1]; values beyond the range pin to the edge.
|
||||
let clamped: Double = min(max(cents, -TunerCentsMeter.range), TunerCentsMeter.range)
|
||||
return (clamped + TunerCentsMeter.range) / (2.0 * TunerCentsMeter.range)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
let width: CGFloat = geometry.size.width
|
||||
let markerX: CGFloat = width * clampedFraction
|
||||
|
||||
ZStack(alignment: .leading) {
|
||||
// Track.
|
||||
RoundedRectangle(cornerRadius: TunerCentsMeter.trackHeight / 2)
|
||||
.fill(Color.white.opacity(0.15))
|
||||
.frame(height: TunerCentsMeter.trackHeight)
|
||||
.frame(maxWidth: .infinity)
|
||||
|
||||
// Centre "in tune" reference tick.
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(0.5))
|
||||
.frame(width: TunerCentsMeter.centerTickWidth, height: TunerCentsMeter.centerTickHeight)
|
||||
.position(x: width / 2, y: TunerCentsMeter.trackHeight / 2)
|
||||
|
||||
// Deviation marker.
|
||||
Rectangle()
|
||||
.fill(TunerView.color(forCents: cents))
|
||||
.frame(width: TunerCentsMeter.markerWidth, height: TunerCentsMeter.markerHeight)
|
||||
.position(x: markerX, y: TunerCentsMeter.trackHeight / 2)
|
||||
}
|
||||
}
|
||||
.frame(width: TunerCentsMeter.trackWidth, height: TunerCentsMeter.markerHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TunerPitchReading
|
||||
|
||||
/// Converts a detected frequency into the nearest chromatic note name, octave, and cents
|
||||
/// deviation. Standard 12-TET sharp spelling — a tuner display doesn't need the full
|
||||
/// spelling-aware `NoteName`/`Scale` theory toolkit (that's for compositional notation).
|
||||
struct TunerPitchReading {
|
||||
private static let chromaticNames: [String] = [
|
||||
"C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
|
||||
]
|
||||
private static let semitonesPerOctave: Int = 12
|
||||
private static let midiOctaveOffset: Int = 1 // MIDI note 0 = C-1
|
||||
private static let centsPerSemitone: Double = 100.0
|
||||
|
||||
let noteName: String
|
||||
let cents: Double
|
||||
|
||||
init(hz: Double) {
|
||||
let midi: Double = hzToMidi(hz)
|
||||
let nearestMidi: Int = Int(midi.rounded())
|
||||
cents = (midi - Double(nearestMidi)) * TunerPitchReading.centsPerSemitone
|
||||
let pitchClass: Int = ((nearestMidi % TunerPitchReading.semitonesPerOctave)
|
||||
+ TunerPitchReading.semitonesPerOctave) % TunerPitchReading.semitonesPerOctave
|
||||
let octave: Int = nearestMidi / TunerPitchReading.semitonesPerOctave - TunerPitchReading.midiOctaveOffset
|
||||
noteName = "\(TunerPitchReading.chromaticNames[pitchClass])\(octave)"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user