e36074e9d3
Two blocking findings from external review: 1. UIParamNode itself ramps from previousOutputValue (seeded at the compile-time default, advanced only by RT render — update() doesn't touch it) to the target over the first block. So a node told to start muted still ramped full-gain→0 across block 0; the earlier "hard gate" only moved the leak from Lag to the param's own ramp. The mutedInputRendersSilent test passed by accident (the test-loop tone is quiet in that first block). Fix: prime previousOutputValue to the target. Race-free before a node is spliced into the graph (addBoard) and safe on a spliced node while the engine is stopped; a running engine keeps the ramp as a click-free live toggle. New setInputMuteGain(_:muted:seedRamp:) / primeInputMute helpers; setInputMuted seeds only when engine.isRunning == false. 2. EngineConfigView.startEngine called setInputMuted(true) AFTER engine.start(), so the engine came up unmuted for the first blocks. Moved it before start() (engine stopped there, so the gain is seeded with no ramp). Also: correct the setInputMuted doc (abrupt kill-switch, not "smoothed"). Regression test stoppedMutePrimesNodesSoTheresNoStartRamp asserts the ramp start equals the target (no pending ramp) after a stopped mute and for a board added while muted. 464 tests pass; both app targets build. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
865 lines
41 KiB
Swift
865 lines
41 KiB
Swift
// ShoeGaze.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Foundation
|
|
import Observation
|
|
import LyrebirdSynth
|
|
import LyrebirdUI
|
|
|
|
// MARK: - ShoeGaze
|
|
|
|
/// Top-level manager for a collection of `PedalBoard`s connected to a `SynthesisEngine`.
|
|
///
|
|
/// `ShoeGaze` allocates and connects input sources, board chains, and a master output
|
|
/// stage. The caller owns the `SynthesisEngine` lifecycle (`engine.start()` /
|
|
/// `engine.stop()`).
|
|
///
|
|
/// ## Typical usage
|
|
///
|
|
/// ```swift
|
|
/// let driver = CoreAudioDriver()
|
|
/// let engine = SynthesisEngine(
|
|
/// blockSize: 512, sampleRate: 44100,
|
|
/// numOutputChannels: 2, numInputChannels: 0, driver: driver
|
|
/// )
|
|
/// let sg = try ShoeGaze(engine: engine)
|
|
/// let board = try sg.addBoard()
|
|
/// try board.add(OverdrivePedal())
|
|
/// try board.add(ReverbPedal())
|
|
/// try engine.start()
|
|
/// ```
|
|
///
|
|
/// ## Input routing
|
|
///
|
|
/// When `inputSource == .testLoop`, a **single** shared `TestLoopSource` writes a global
|
|
/// test bus, and each board gets a `TestLoopTap` (added `.after(_:)` the source) copying that
|
|
/// bus into the board's head bus. One shared source keeps every board phase-locked and survives
|
|
/// board add/remove, so the arpeggio never restarts into a polyrhythm.
|
|
///
|
|
/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` synthesizer
|
|
/// copies hardware input `channel` (engine bus `numOutputChannels + channel`) to the
|
|
/// board's head bus. This ensures the first pedal reads from a board-owned bus, not the
|
|
/// raw hardware input bus. The engine must be created with `numInputChannels > channel`;
|
|
/// otherwise `addBoard()` throws `ShoeGazeError.liveInputRequiresInputChannels` (no input
|
|
/// channels) or `.inputChannelOutOfRange` (channel too high).
|
|
///
|
|
/// ## Master stage
|
|
///
|
|
/// Each board's output bus is read by a `BoardOutputMaster` synth added **after**
|
|
/// the board's last pedal via `.after(_:)`. The master pans the mono board signal
|
|
/// to stereo and writes to hardware buses 0 (left) and 1 (right).
|
|
@MainActor
|
|
@Observable
|
|
public final class ShoeGaze {
|
|
|
|
// MARK: - Public state
|
|
|
|
/// 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] = []
|
|
|
|
/// Input source policy. Affects how `addBoard()` routes signal to the head bus.
|
|
public var inputSource: InputSource
|
|
|
|
/// The rig's MIDI foot-controller bindings, or `nil` when none are set. Embedded in the rig
|
|
/// snapshot by `captureState()` and restored by `loadRig`, so the map travels with the rig.
|
|
/// Read and mutated by `MIDIController`; survives an input-source switch (same rig).
|
|
public var midiMap: MIDIMap?
|
|
|
|
/// The id of the rig-library entry this working session derives from, or `nil` for an unsaved
|
|
/// session. Session provenance only — NOT part of a saved/exported rig; it is written into the
|
|
/// autosave envelope (see `RigStore`) alongside the graph so the sidebar highlight and the
|
|
/// restored graph can never diverge. The UI mirrors this into the rig-library selection.
|
|
public var currentRigID: UUID?
|
|
|
|
// MARK: - Recording state
|
|
|
|
/// The folder into which `startRecording()` writes timestamped WAV files.
|
|
///
|
|
/// Set this before calling `startRecording()`. If `nil`, `startRecording()` throws
|
|
/// `ShoeGazeError.recordingFolderNotSet`. The folder is created if it does not exist.
|
|
public var recordingFolder: URL?
|
|
|
|
/// `true` while recording is in progress (between `startRecording()` and `stopRecording()`).
|
|
///
|
|
/// The setter is `internal` so that `ShoeGaze+Recording.swift` (same module, different file)
|
|
/// can toggle this flag; external callers only observe the value through this `public` getter.
|
|
public internal(set) var isRecording: Bool = false
|
|
|
|
/// Active `RecordTap` instances (output + optional input). Populated by `startRecording()`,
|
|
/// cleared by `stopRecording()`. `internal` so the extension in `ShoeGaze+Recording.swift`
|
|
/// (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
|
|
|
|
/// `true` when the tempo indicator (BPM readout / TAP / beat LED) is shown and tempo-synced
|
|
/// features are available. Toggle with ``setTempoEnabled(_:)``; when turned off, every
|
|
/// tempo-dependent pedal switch (e.g. the looper's Sync-to-Tempo mode) is forced to its
|
|
/// first (off) position so nothing keeps quantizing to a hidden clock.
|
|
public private(set) var tempoEnabled: Bool = true
|
|
|
|
/// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so
|
|
/// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it.
|
|
internal var tapTimestamps: [Date] = []
|
|
|
|
/// Shows or hides the tempo indicator and, when hiding, deactivates every tempo-synced
|
|
/// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option.
|
|
public func setTempoEnabled(_ enabled: Bool) {
|
|
tempoEnabled = enabled
|
|
guard !enabled else {
|
|
// Re-enabling: bring every tempo-synced parameter back in line with the current tempo.
|
|
applyTempoSyncToAllPedals()
|
|
return
|
|
}
|
|
for pedal: Pedal in allPedals() {
|
|
for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent {
|
|
if let off: PedalSwitch.Option = pedalSwitch.options.first {
|
|
pedalSwitch.node.update(off.value)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Sets the shared clock's tempo and recomputes every tempo-synced pedal parameter to match.
|
|
/// Route **all** BPM changes (stepper, tap tempo, MIDI) through here so synced delay times and
|
|
/// LFO rates follow the tempo. Recompute is skipped while tempo is disabled.
|
|
///
|
|
/// - Parameter bpm: The new tempo in beats per minute. A non-positive value is ignored (the
|
|
/// clock requires a positive tempo); callers that also want an upper bound clamp before calling.
|
|
public func setBpm(_ bpm: Double) {
|
|
guard bpm > 0 else { return }
|
|
clock.bpm = bpm
|
|
guard tempoEnabled else { return }
|
|
applyTempoSyncToAllPedals()
|
|
}
|
|
|
|
/// Recomputes every tempo-synced parameter on every live pedal from the current tempo.
|
|
/// `internal` so the preset-restore path (`ShoeGaze+Preset.swift`) can re-sync after a rig load.
|
|
internal func applyTempoSyncToAllPedals() {
|
|
for pedal: Pedal in allPedals() {
|
|
pedal.applyTempoSync()
|
|
}
|
|
}
|
|
|
|
// MARK: - Scope state
|
|
|
|
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
|
|
///
|
|
/// Rebuilt by ``installScopeTap(bufferSize:)`` whenever the engine layout changes (so the
|
|
/// tapped bus indices follow the current input/output channel counts). `nil` until first
|
|
/// installed. The setter is `internal` so ``installScopeTap(bufferSize:)`` (same module,
|
|
/// different file) can assign it; external callers observe it through this `public` getter.
|
|
public internal(set) var scopeTap: ScopeCapture?
|
|
|
|
// MARK: - Private
|
|
|
|
/// The single shared test-loop source feeding every board in `.testLoop` mode, and the bus
|
|
/// it writes. One global source keeps all boards phase-locked (no per-board polyrhythm) and
|
|
/// survives board add/remove so its arpeggio never restarts. `nil` outside `.testLoop` mode.
|
|
private var globalTestSource: TestLoopSource?
|
|
private var globalTestBus: AudioBus?
|
|
|
|
/// Per-board taps copying the global test bus into each board's head bus.
|
|
private var testLoopTaps: [TestLoopTap] = []
|
|
private var inputPassThroughs: [HardwareInputPassThrough] = []
|
|
private var outputMasters: [BoardOutputMaster] = []
|
|
|
|
/// All chain routers created via ``makeChainRouter()``.
|
|
/// Routers are torn down (in reverse-creation order) by ``teardown()``.
|
|
private var routers: [ChainRouter] = []
|
|
|
|
// MARK: - Init
|
|
|
|
/// Creates a `ShoeGaze` manager backed by the given engine.
|
|
///
|
|
/// The caller retains ownership of `engine` and is responsible for calling
|
|
/// `engine.start()` and `engine.stop()`.
|
|
///
|
|
/// - Parameters:
|
|
/// - engine: The `SynthesisEngine` to add synthesizers and boards to.
|
|
/// - inputSource: How the board head bus is fed. Defaults to `.testLoop`.
|
|
public init(
|
|
engine: SynthesisEngine,
|
|
inputSource: InputSource = .testLoop
|
|
) {
|
|
self.engine = engine
|
|
self.inputSource = inputSource
|
|
clock = LyrebirdClock(engine: engine, bpm: ShoeGaze.defaultTempoBpm)
|
|
installScopeTap()
|
|
}
|
|
|
|
// MARK: - Board management
|
|
|
|
/// Stops the audio engine as a deliberate user action: notifies every pedal via
|
|
/// ``Pedal/engineDidStop()`` (so stateful pedals like the looper return to a clean state and
|
|
/// post a notice) and then stops the engine. Use this for the user-facing Stop control — not
|
|
/// for transient stop-around-rebuild sequences, which call `engine.stop()` directly so
|
|
/// pedals keep their state across the restart.
|
|
public func stopEngine() {
|
|
for pedal: Pedal in allPedals() {
|
|
pedal.engineDidStop()
|
|
}
|
|
engine.stop()
|
|
}
|
|
|
|
/// Every live `Pedal` across all main boards and chain-router branches.
|
|
private func allPedals() -> [Pedal] {
|
|
var result: [Pedal] = []
|
|
for board: PedalBoard in boards {
|
|
result.append(contentsOf: pedals(in: board))
|
|
}
|
|
for router: ChainRouter in routers {
|
|
result.append(contentsOf: pedals(in: router.boardA))
|
|
result.append(contentsOf: pedals(in: router.boardB))
|
|
}
|
|
return result
|
|
}
|
|
|
|
/// Every live `Pedal` in one board, including pedals inside its parallel and stereo-split
|
|
/// branch sections (branch pedals live in their section objects, not as top-level segments).
|
|
private func pedals(in board: PedalBoard) -> [Pedal] {
|
|
var result: [Pedal] = []
|
|
for segment: BoardSegment in board.orderedSegments {
|
|
switch segment {
|
|
case .pedal(let pedal):
|
|
result.append(pedal)
|
|
case .parallel(let section):
|
|
result.append(contentsOf: section.branchA.pedals)
|
|
result.append(contentsOf: section.branchB.pedals)
|
|
case .stereoSplit(let section), .stereoUnzip(let section):
|
|
result.append(contentsOf: section.left.pedals)
|
|
result.append(contentsOf: section.right.pedals)
|
|
case .mergeToMono:
|
|
break
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
/// Allocates a new `PedalBoard` connected to the engine, wires the input source,
|
|
/// and returns the board ready for pedals to be added via `board.add(_:)`.
|
|
///
|
|
/// Call this before adding pedals. After all pedals have been added to the returned
|
|
/// board, call `finalizeBoard(_:)` to connect the output master.
|
|
///
|
|
/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` is added
|
|
/// that copies hardware input bus `numOutputChannels + channel` to the board head bus.
|
|
/// The engine must have been created with `numInputChannels > channel`.
|
|
///
|
|
/// - Returns: A configured `PedalBoard` with its head bus allocated and input source wired.
|
|
/// - Throws:
|
|
/// - `ShoeGazeError.liveInputRequiresInputChannels` if `.liveInput` is selected but
|
|
/// the engine has `numInputChannels == 0`.
|
|
/// - `BusAllocatorError.noFreeBus` if no mono bus is available.
|
|
/// - `EngineAddError` if the engine rejects a node insertion.
|
|
@discardableResult
|
|
public func addBoard() throws -> PedalBoard {
|
|
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
|
|
board.label = "Board \(boards.count + 1)"
|
|
|
|
// Route the input source to the board head bus.
|
|
switch inputSource {
|
|
case .testLoop:
|
|
// All boards share one global test source so they stay phase-locked. Each board
|
|
// gets a tap copying the shared test bus into its head bus, added `.after(_:)` the
|
|
// source so it sees the source's output for the current block.
|
|
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
|
|
let tap: TestLoopTap = TestLoopTap(
|
|
inputBusIndex: testBus.index,
|
|
outputBusIndex: board.headBus.index
|
|
)
|
|
// Prime the mute gain before splicing the node in, so its very first render block
|
|
// reflects the current mute state with no ramp (see `primeInputMute`).
|
|
primeInputMute(tap.inputMuteNode, muted: inputMuted)
|
|
try engine.add(tap, position: NodePosition.after(source))
|
|
testLoopTaps.append(tap)
|
|
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first
|
|
// pedal after it automatically (without needing an explicit `after:`).
|
|
board.headInputNode = tap
|
|
|
|
case .liveInput(let channel):
|
|
// Hardware input channel `channel` lives at bus numOutputChannels + channel.
|
|
// A HardwareInputPassThrough copies it to the board's head bus so all pedals
|
|
// read from a board-owned bus (not the raw hardware input bus).
|
|
let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
|
|
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
|
|
inputBusIndex: hardwareInputBusIndex,
|
|
outputBusIndex: board.headBus.index
|
|
)
|
|
// Prime the mute gain before splicing the node in (see `primeInputMute`).
|
|
primeInputMute(passThrough.inputMuteNode, muted: inputMuted)
|
|
try engine.add(passThrough)
|
|
inputPassThroughs.append(passThrough)
|
|
board.headInputNode = passThrough
|
|
}
|
|
|
|
// Only record the board after all wiring has succeeded. This prevents
|
|
// orphaning a board (with an allocated head bus) in `boards` if the
|
|
// input-source add or the guard above throws.
|
|
boards.append(board)
|
|
return board
|
|
}
|
|
|
|
/// Lazily creates the single shared test-loop source and its bus, returning both.
|
|
///
|
|
/// Created once per `.testLoop` session and reused by every board's tap, so the arpeggio
|
|
/// phase is continuous across board add/remove (no per-board polyrhythm). Torn down by
|
|
/// ``teardown()`` (and thus by ``setInputSource(_:)`` when leaving test-loop mode).
|
|
///
|
|
/// The source and bus are committed to `globalTestSource` / `globalTestBus` only after the
|
|
/// engine add succeeds — if `engine.add` throws, the freshly allocated bus is released so it
|
|
/// is never orphaned.
|
|
private func ensureGlobalTestSource() throws -> (source: TestLoopSource, bus: AudioBus) {
|
|
if let source: TestLoopSource = globalTestSource, let bus: AudioBus = globalTestBus {
|
|
return (source, bus)
|
|
}
|
|
let testBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
let source: TestLoopSource = TestLoopSource(
|
|
targetBus: testBus.index,
|
|
sampleRate: engine.sampleRate
|
|
)
|
|
do {
|
|
// Plain add → head of mainGroup (evaluates before its taps and any pedal).
|
|
try engine.add(source)
|
|
} catch {
|
|
engine.busAllocator.releaseAudioBus(testBus)
|
|
throw error
|
|
}
|
|
globalTestBus = testBus
|
|
globalTestSource = source
|
|
return (source, testBus)
|
|
}
|
|
|
|
/// Connects the output master for a previously prepared board and adds it to the engine.
|
|
///
|
|
/// Call this after all pedals have been added to the board via `board.add(_:)`.
|
|
/// The master reads the board's current `outputBus` and routes it to hardware
|
|
/// outputs 0 and 1 in stereo.
|
|
///
|
|
/// If the board has no pedals, the master is added `.after(headInputNode)` so it
|
|
/// evaluates after the input source has written the head bus. If no head input node
|
|
/// is present either, a plain add is used as a last resort.
|
|
///
|
|
/// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added.
|
|
/// - Throws: `EngineAddError` if the engine rejects the master node.
|
|
public func finalizeBoard(_ board: PedalBoard) throws {
|
|
let master: BoardOutputMaster = BoardOutputMaster(
|
|
boardOutputBusIndex: board.outputBus.index,
|
|
boardOutputBusRightIndex: board.outputBusRight?.index,
|
|
dryInputBusIndex: board.headBus.index
|
|
)
|
|
// The master evaluates after the entire chain (pedals, splitters, mergers).
|
|
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers
|
|
// plain-pedal chains and parallel sections containing routing nodes alike.
|
|
if let tail: any Synthesizer = board.tailNode {
|
|
// Normal case: chain after the last node in the board.
|
|
try engine.add(master, position: .after(tail))
|
|
} else {
|
|
// No nodes and no head input node (unusual): plain add.
|
|
try engine.add(master)
|
|
}
|
|
outputMasters.append(master)
|
|
// Expose the master to the board so the UI can bind a master-volume knob
|
|
// and `removeBoard(_:)` can tear down just this board's master.
|
|
board.outputMaster = master
|
|
board.masterGainNode = master.gainNode
|
|
board.selectGainNode = master.selectGainNode
|
|
board.crossfadeTimeNode = master.crossfadeTimeNode
|
|
board.boardBypassNode = master.boardBypassNode
|
|
board.rigBypassNode = master.rigBypassNode
|
|
board.rigVolumeNode = master.rigVolumeNode
|
|
board.rigMuteNode = master.rigMuteNode
|
|
|
|
// If a board is currently soloed, a newly-finalized board must come up silent
|
|
// (select-gain 0) so it doesn't leak audio past the active solo.
|
|
if let soloIndex: Int = activeBoardIndex,
|
|
let newIndex: Int = boards.firstIndex(where: { $0 === board }),
|
|
newIndex != soloIndex {
|
|
master.selectGainNode.update(0.0)
|
|
}
|
|
|
|
// A board finalized while the rig is bypassed must come up bypassed too, so it doesn't
|
|
// leak processed audio past the global bypass.
|
|
if rigBypassed {
|
|
master.rigBypassNode.update(1.0)
|
|
}
|
|
// Bring a newly-finalized board up at the current rig volume / mute.
|
|
master.rigVolumeNode.update(rigVolume)
|
|
master.rigMuteNode.update(rigMuted ? 1.0 : 0.0)
|
|
}
|
|
|
|
// MARK: - Board selection / crossfade
|
|
|
|
/// The index of the currently soloed board in ``boards``, or `nil` when all boards
|
|
/// are audible (the default — every board's output sums to the hardware output).
|
|
public private(set) var activeBoardIndex: Int?
|
|
|
|
/// `true` when the whole rig is bypassed — every board passes its dry input straight through.
|
|
/// A live performance toggle (not persisted); cleared on input-source / engine rebuild.
|
|
public private(set) var rigBypassed: Bool = false
|
|
|
|
/// Rig-wide output volume in [0, 1], applied to every board's output. Survives an input-source
|
|
/// rebuild (re-applied to each rebuilt board in `finalizeBoard`).
|
|
public private(set) var rigVolume: Double = 1.0
|
|
|
|
/// `true` when the rig output is muted (hard-silenced, not bypassed). Survives a rebuild.
|
|
public private(set) var rigMuted: Bool = false
|
|
|
|
/// `true` when the **input** feeding every board is muted — the incoming guitar / mic signal,
|
|
/// distinct from ``rigMuted`` (the output). Defaults `false` (audible); the app re-asserts it
|
|
/// muted on each user engine start (see `EngineConfigView`) so a fresh start is silent until the
|
|
/// player un-mutes, without forcing silence on headless / offline library use. See
|
|
/// ``setInputMuted(_:)``.
|
|
public private(set) var inputMuted: Bool = false
|
|
|
|
/// Identities of boards currently in per-board full bypass. Observable so UI toggles refresh;
|
|
/// authoritative bypass value lives on each board's `boardBypassNode`. Transient (not persisted).
|
|
public private(set) var bypassedBoards: Set<ObjectIdentifier> = []
|
|
|
|
/// Crossfades so only `board` is audible, fading the others out.
|
|
///
|
|
/// Sets every board's crossfade time to `crossfadeSeconds`, then ramps the selected
|
|
/// board's select-gain to `1` and all others to `0`. Each board's `BoardOutputMaster`
|
|
/// lags the select-gain, so the transition is a click-free crossfade of that duration.
|
|
/// The per-board master-volume knob is unaffected.
|
|
///
|
|
/// - Parameters:
|
|
/// - board: The board to make audible. No-op if not managed by this instance.
|
|
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
|
public func selectBoard(_ board: PedalBoard, crossfadeSeconds: Double) {
|
|
guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
|
for (offset, managed): (Int, PedalBoard) in boards.enumerated() {
|
|
managed.crossfadeTimeNode?.update(crossfadeSeconds)
|
|
managed.selectGainNode?.update(offset == index ? 1.0 : 0.0)
|
|
}
|
|
activeBoardIndex = index
|
|
}
|
|
|
|
/// Crossfades all boards back to audible (the default summed state).
|
|
///
|
|
/// - Parameter crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
|
public func selectAllBoards(crossfadeSeconds: Double) {
|
|
for managed: PedalBoard in boards {
|
|
managed.crossfadeTimeNode?.update(crossfadeSeconds)
|
|
managed.selectGainNode?.update(1.0)
|
|
}
|
|
activeBoardIndex = nil
|
|
}
|
|
|
|
/// Solos `board` exclusively — identical to ``selectBoard(_:crossfadeSeconds:)``.
|
|
///
|
|
/// Provided as the "Solo" verb alongside ``setBoard(_:audible:crossfadeSeconds:)`` so
|
|
/// callers can express *make only this board audible* without conflating it with the
|
|
/// independent per-board enable used by Blend-style mixing.
|
|
///
|
|
/// - Parameters:
|
|
/// - board: The board to solo. No-op if not managed by this instance.
|
|
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
|
public func soloBoard(_ board: PedalBoard, crossfadeSeconds: Double) {
|
|
selectBoard(board, crossfadeSeconds: crossfadeSeconds)
|
|
}
|
|
|
|
/// Sets a single board audible or silent **without** disturbing the others.
|
|
///
|
|
/// Unlike ``selectBoard(_:crossfadeSeconds:)`` (which is exclusive), this toggles one
|
|
/// board's select-gain in place, so arbitrary subsets of boards can play at once — the
|
|
/// "Blend" mixing model. Because the audible set is no longer a single soloed board,
|
|
/// ``activeBoardIndex`` is cleared to `nil`.
|
|
///
|
|
/// - Parameters:
|
|
/// - board: The board to enable or silence. No-op if not managed by this instance.
|
|
/// - audible: `true` to fade the board in, `false` to fade it out.
|
|
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
|
|
public func setBoard(_ board: PedalBoard, audible: Bool, crossfadeSeconds: Double) {
|
|
guard boards.contains(where: { $0 === board }) else { return }
|
|
board.crossfadeTimeNode?.update(crossfadeSeconds)
|
|
board.selectGainNode?.update(audible ? 1.0 : 0.0)
|
|
activeBoardIndex = nil
|
|
}
|
|
|
|
/// Whether `board`'s output is currently audible (its select-gain target is on).
|
|
///
|
|
/// Reads the live select-gain target, so it reflects the latest
|
|
/// ``selectBoard(_:crossfadeSeconds:)`` / ``setBoard(_:audible:crossfadeSeconds:)`` /
|
|
/// ``selectAllBoards(crossfadeSeconds:)`` call (the value the crossfade is ramping
|
|
/// toward), independent of where the crossfade currently sits.
|
|
///
|
|
/// - Parameter board: A board managed by this instance.
|
|
/// - Returns: `true` when the board's select-gain target is on; `false` when silenced
|
|
/// or when the board has no output master yet.
|
|
public func isBoardAudible(_ board: PedalBoard) -> Bool {
|
|
let selectGainOnThreshold: Double = 0.5
|
|
return (board.selectGainNode?.value ?? 0.0) > selectGainOnThreshold
|
|
}
|
|
|
|
// MARK: - Full bypass (board / rig)
|
|
|
|
/// Fully bypasses or re-engages a single board. When bypassed, the board's dry input passes
|
|
/// straight through, skipping every pedal; the board's master volume and select-gain still
|
|
/// apply. The transition is a click-free crossfade. Independent of ``setRigBypassed(_:)``.
|
|
///
|
|
/// - Parameters:
|
|
/// - board: A board managed by this instance. No-op otherwise.
|
|
/// - bypassed: `true` to bypass (dry), `false` to re-engage the pedal chain.
|
|
public func setBoard(_ board: PedalBoard, bypassed: Bool) {
|
|
guard boards.contains(where: { $0 === board }) else { return }
|
|
board.boardBypassNode?.update(bypassed ? 1.0 : 0.0)
|
|
if bypassed {
|
|
bypassedBoards.insert(ObjectIdentifier(board))
|
|
} else {
|
|
bypassedBoards.remove(ObjectIdentifier(board))
|
|
}
|
|
}
|
|
|
|
/// Whether `board` is currently in per-board full bypass.
|
|
///
|
|
/// - Parameter board: A board managed by this instance.
|
|
/// - Returns: `true` when the board's per-board bypass is engaged.
|
|
public func isBoardBypassed(_ board: PedalBoard) -> Bool {
|
|
bypassedBoards.contains(ObjectIdentifier(board))
|
|
}
|
|
|
|
/// Fully bypasses or re-engages the entire rig — every board passes its dry input straight
|
|
/// through at once. Independent of any per-board bypass (either routes a board to dry). The
|
|
/// transition is a click-free crossfade on every board.
|
|
///
|
|
/// - Parameter bypassed: `true` to bypass the whole rig, `false` to re-engage.
|
|
public func setRigBypassed(_ bypassed: Bool) {
|
|
for managed: PedalBoard in boards {
|
|
managed.rigBypassNode?.update(bypassed ? 1.0 : 0.0)
|
|
}
|
|
rigBypassed = bypassed
|
|
}
|
|
|
|
/// Toggles rig-wide full bypass. See ``setRigBypassed(_:)``.
|
|
public func toggleRigBypassed() {
|
|
setRigBypassed(!rigBypassed)
|
|
}
|
|
|
|
/// Sets the rig-wide output volume (clamped to [0, 1]), applied to every board. Smoothed per
|
|
/// board to avoid clicks.
|
|
///
|
|
/// - Parameter volume: Output volume in [0, 1].
|
|
public func setRigVolume(_ volume: Double) {
|
|
let clamped: Double = min(max(volume, 0.0), 1.0)
|
|
for managed: PedalBoard in boards {
|
|
managed.rigVolumeNode?.update(clamped)
|
|
}
|
|
rigVolume = clamped
|
|
}
|
|
|
|
/// Mutes or un-mutes the rig output — a hard gate to silence, distinct from the dry-passthrough
|
|
/// ``setRigBypassed(_:)``. Applied to every board, smoothed to avoid clicks.
|
|
///
|
|
/// - Parameter muted: `true` to silence the output, `false` to restore it.
|
|
public func setRigMuted(_ muted: Bool) {
|
|
for managed: PedalBoard in boards {
|
|
managed.rigMuteNode?.update(muted ? 1.0 : 0.0)
|
|
}
|
|
rigMuted = muted
|
|
}
|
|
|
|
/// Toggles the rig output mute. See ``setRigMuted(_:)``.
|
|
public func toggleRigMuted() {
|
|
setRigMuted(!rigMuted)
|
|
}
|
|
|
|
/// Mutes or un-mutes the **input** feeding every board — the incoming guitar / mic signal,
|
|
/// distinct from the rig-output ``setRigMuted(_:)``. Applied to every board's input writer
|
|
/// (test-loop tap or hardware pass-through) as an abrupt kill-switch gate (unlagged, so a
|
|
/// muted input is exactly silent — see the note in `HardwareInputPassThrough.build()`).
|
|
///
|
|
/// The app re-asserts this muted on each user engine start (see `EngineConfigView`) so a fresh
|
|
/// start is silent until the player un-mutes — preventing accidental input noise.
|
|
///
|
|
/// - Parameter muted: `true` to silence the input, `false` to let it through.
|
|
public func setInputMuted(_ muted: Bool) {
|
|
// Seed the ramp start only while the engine is stopped: then the next Start renders the new
|
|
// mute state from block zero with no audible→muted (or muted→audible) ramp — which is exactly
|
|
// what "muted on Start" needs. While the engine is running, seeding `previousOutputValue`
|
|
// would race the RT thread; leaving it lets the one-block ramp act as a click-free toggle.
|
|
let seedRamp: Bool = !engine.isRunning
|
|
for tap: TestLoopTap in testLoopTaps {
|
|
setInputMuteGain(tap.inputMuteNode, muted: muted, seedRamp: seedRamp)
|
|
}
|
|
for passThrough: HardwareInputPassThrough in inputPassThroughs {
|
|
setInputMuteGain(passThrough.inputMuteNode, muted: muted, seedRamp: seedRamp)
|
|
}
|
|
inputMuted = muted
|
|
}
|
|
|
|
/// Primes a freshly-created input-mute node (not yet spliced into the graph) to the given mute
|
|
/// state so its first render block has no ramp. Race-free because the node is not yet evaluated
|
|
/// by the RT thread. See ``setInputMuteGain(_:muted:seedRamp:)``.
|
|
private func primeInputMute(_ node: UIParamNode, muted: Bool) {
|
|
setInputMuteGain(node, muted: muted, seedRamp: true)
|
|
}
|
|
|
|
/// Sets an input node's mute gain. `update` stores the atomic target the RT thread ramps toward
|
|
/// from `previousOutputValue`; that seed is only advanced by RT render, so `update` alone leaves
|
|
/// a one-block ramp from the node's prior value. When `seedRamp` is `true` (node not yet spliced,
|
|
/// or engine stopped) we also seed `previousOutputValue` to the target so there is no ramp.
|
|
private func setInputMuteGain(_ node: UIParamNode, muted: Bool, seedRamp: Bool) {
|
|
let value: Double = muted ? 1.0 : 0.0
|
|
node.update(value)
|
|
if seedRamp { node.previousOutputValue = value }
|
|
}
|
|
|
|
/// Toggles the input mute. See ``setInputMuted(_:)``.
|
|
public func toggleInputMuted() {
|
|
setInputMuted(!inputMuted)
|
|
}
|
|
|
|
/// The live mute-gain values of every board input writer (test-loop taps and hardware
|
|
/// pass-throughs). `1` = muted, `0` = audible. Exposed for tests to confirm the RT nodes are
|
|
/// actually driven by ``setInputMuted(_:)``, not just the ``inputMuted`` flag.
|
|
var inputMuteNodeValues: [Double] {
|
|
testLoopTaps.map { $0.inputMuteNode.value }
|
|
+ inputPassThroughs.map { $0.inputMuteNode.value }
|
|
}
|
|
|
|
/// The `previousOutputValue` (ramp start) of every board input-mute node. Exposed for tests to
|
|
/// confirm a stopped-engine mute is *primed* — ramp start equal to the target — so the next
|
|
/// render can't ramp from the prior value and leak a block. See ``setInputMuteGain(_:muted:seedRamp:)``.
|
|
var inputMutePreviousValues: [Double] {
|
|
testLoopTaps.map { $0.inputMuteNode.previousOutputValue }
|
|
+ inputPassThroughs.map { $0.inputMuteNode.previousOutputValue }
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// - Parameter board: A board previously returned by ``addBoard()``. No-op if the
|
|
/// board is not managed by this instance.
|
|
public func removeBoard(_ board: PedalBoard) {
|
|
guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
|
|
|
// Stop any active recording before removing the board. The record taps in .testLoop
|
|
// mode read the first board's headBus; in .liveInput mode they read a hardware input
|
|
// bus that is valid until the board's input pass-through is removed. Either way,
|
|
// removing a board while recording could leave the input tap reading a released or
|
|
// reused bus. Stopping first ensures all taps are removed before any bus is freed.
|
|
if isRecording {
|
|
stopRecording()
|
|
}
|
|
|
|
// Remove the board's output master (writer of the hardware output bus).
|
|
if let master: BoardOutputMaster = board.outputMaster {
|
|
engine.remove(master)
|
|
outputMasters.removeAll { $0 === master }
|
|
}
|
|
|
|
// Remove the board's input node (writer of the head bus). In `.testLoop` mode this is a
|
|
// tap; the shared global source is left running so the remaining boards keep their
|
|
// phase-locked test signal.
|
|
if let tap: TestLoopTap = board.headInputNode as? TestLoopTap {
|
|
engine.remove(tap)
|
|
testLoopTaps.removeAll { $0 === tap }
|
|
} else if let passThrough: HardwareInputPassThrough = board.headInputNode as? HardwareInputPassThrough {
|
|
engine.remove(passThrough)
|
|
inputPassThroughs.removeAll { $0 === passThrough }
|
|
}
|
|
|
|
// Remove the pedals and release the board's buses.
|
|
board.teardown()
|
|
boards.remove(at: index)
|
|
bypassedBoards.remove(ObjectIdentifier(board))
|
|
|
|
// Keep the soloed-board index valid: clear it if the soloed board was removed,
|
|
// otherwise shift it down when a board before it was removed.
|
|
if let active: Int = activeBoardIndex {
|
|
if active == index {
|
|
activeBoardIndex = nil
|
|
} else if active > index {
|
|
activeBoardIndex = active - 1
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Chain router
|
|
|
|
/// Creates a ``ChainRouter`` that routes one shared input to two independent
|
|
/// ``PedalBoard`` chains and merges their outputs through a single master stage.
|
|
///
|
|
/// The router is tracked internally and torn down automatically by ``teardown()``.
|
|
/// Do **not** also add the router's boards via ``addBoard()`` — the router owns
|
|
/// their lifecycle.
|
|
///
|
|
/// Typical usage:
|
|
///
|
|
/// ```swift
|
|
/// let router = try shoeGaze.makeChainRouter()
|
|
/// try router.boardA.add(OverdrivePedal())
|
|
/// try router.boardB.add(DelayPedal())
|
|
/// try router.finalize()
|
|
/// router.mode = .both
|
|
/// try engine.start()
|
|
/// ```
|
|
///
|
|
/// > Note: In `.testLoop` mode a `ChainRouter` allocates **its own** test source (shared by
|
|
/// > the router's two boards via the splitter, so those two stay phase-locked to each other).
|
|
/// > That source is independent of the global test source used by ``addBoard()``-created
|
|
/// > boards, so a router's boards are *not* phase-locked to the main board list. Routers are
|
|
/// > a separate multi-board path (not used by the standard builder UI); unifying them onto the
|
|
/// > global source is intentionally out of scope here.
|
|
///
|
|
/// - Returns: A ``ChainRouter`` with both boards ready to receive pedals.
|
|
/// - Throws:
|
|
/// - `ShoeGazeError.liveInputRequiresInputChannels` when `inputSource == .liveInput`
|
|
/// but `engine.numInputChannels == 0`.
|
|
/// - `BusAllocatorError.noFreeBus` if no mono bus is available.
|
|
/// - `EngineAddError` if the engine rejects any node insertion.
|
|
@discardableResult
|
|
public func makeChainRouter() throws -> ChainRouter {
|
|
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource, clock: clock)
|
|
routers.append(router)
|
|
return router
|
|
}
|
|
|
|
// MARK: - Internal board reordering
|
|
|
|
/// Moves `board` to `targetIndex` within `boards`, locating it by identity.
|
|
///
|
|
/// This is an internal helper that mutates `boards` directly — valid only because
|
|
/// `ShoeGaze` is `@MainActor` (no concurrent access). Reordering only permutes the
|
|
/// `boards` array; it does not touch the engine graph, so it is safe to call while the
|
|
/// engine is running.
|
|
///
|
|
/// - Parameters:
|
|
/// - board: The `PedalBoard` to reposition. No-op if not found in `boards`.
|
|
/// - index: The desired destination index. Clamped to `boards.count` after removal
|
|
/// so it is always a valid insertion point.
|
|
public func moveBoard(_ board: PedalBoard, to index: Int) {
|
|
guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return }
|
|
// Track the soloed board by identity so its index follows the reorder.
|
|
let soloedBoard: PedalBoard? = activeBoardIndex.flatMap { idx in
|
|
idx < boards.count ? boards[idx] : nil
|
|
}
|
|
let removed: PedalBoard = boards.remove(at: sourceIndex)
|
|
let destination: Int = min(index, boards.count)
|
|
boards.insert(removed, at: destination)
|
|
if let soloedBoard {
|
|
activeBoardIndex = boards.firstIndex(where: { $0 === soloedBoard })
|
|
}
|
|
}
|
|
|
|
// MARK: - Teardown
|
|
|
|
/// Removes all nodes (test sources, input pass-throughs, pedals, masters) from
|
|
/// the engine and releases all allocated buses.
|
|
///
|
|
/// - Important: Call only after the engine has been stopped, or accept one block
|
|
/// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal;
|
|
/// the actual dequeue happens on the next render block. Releasing buses immediately
|
|
/// after enqueue means a still-running engine could write to a reallocated bus for
|
|
/// one block. The buses are pooled (not freed), so worst case is a transient glitch,
|
|
/// not a crash. Stop the engine first to avoid this.
|
|
///
|
|
/// All engine nodes that write board buses are removed **before** any
|
|
/// `board.teardown()` releases buses back to the allocator, preserving the
|
|
/// remove-before-release ordering.
|
|
public func teardown() {
|
|
// Step 0: Stop any active recording before removing board nodes. This ensures
|
|
// the record taps are removed and their DiskOut handles are closed before the
|
|
// board buses they reference are released.
|
|
stopRecording()
|
|
|
|
// Notify pedals the rig is being torn down (rig load / clear / input-source change), so
|
|
// stateful pedals like the looper stop their background routines cleanly and post a
|
|
// notice before their instances are discarded.
|
|
for pedal: Pedal in allPedals() {
|
|
pedal.rigWillTeardown()
|
|
}
|
|
|
|
// Step 1: Remove all engine nodes that write to board buses.
|
|
// Order within this step does not matter; all must finish before bus release.
|
|
for tap: TestLoopTap in testLoopTaps {
|
|
engine.remove(tap)
|
|
}
|
|
testLoopTaps.removeAll()
|
|
|
|
// Remove the shared global test source and release its bus (after its taps are removed,
|
|
// preserving remove-before-release ordering).
|
|
if let source: TestLoopSource = globalTestSource {
|
|
engine.remove(source)
|
|
}
|
|
globalTestSource = nil
|
|
if let testBus: AudioBus = globalTestBus {
|
|
engine.busAllocator.releaseAudioBus(testBus)
|
|
}
|
|
globalTestBus = nil
|
|
|
|
for passThrough: HardwareInputPassThrough in inputPassThroughs {
|
|
engine.remove(passThrough)
|
|
}
|
|
inputPassThroughs.removeAll()
|
|
|
|
for master: BoardOutputMaster in outputMasters {
|
|
engine.remove(master)
|
|
}
|
|
outputMasters.removeAll()
|
|
|
|
// Step 2: Remove pedals from the engine and release all board-owned buses.
|
|
// board.teardown() removes pedals from the engine and then releases buses,
|
|
// so bus release only happens after all writers have been dequeued.
|
|
for board: PedalBoard in boards {
|
|
board.teardown()
|
|
}
|
|
boards.removeAll()
|
|
|
|
// Step 3: Tear down all chain routers. Each router removes its own nodes and
|
|
// releases its buses (master → merger → splitter → source → board buses →
|
|
// router buses), maintaining the remove-before-release ordering.
|
|
for router: ChainRouter in routers {
|
|
router.teardown()
|
|
}
|
|
routers.removeAll()
|
|
|
|
// Live performance toggles are transient — a rebuild starts from a clean slate. Board
|
|
// identities also change across a rebuild, so the per-board bypass set would be stale.
|
|
activeBoardIndex = nil
|
|
rigBypassed = false
|
|
bypassedBoards.removeAll()
|
|
}
|
|
}
|