8c601e2029
Each board previously got its own TestLoopSource, so multiple boards ran independently-phased arpeggios and any rebuild restarted them out of sync — audible polyrhythms. Now a single global TestLoopSource writes a shared test bus, and each board gets a lightweight TestLoopTap (added .after the source) copying that bus into its head bus. The shared source survives board add/remove, so the test signal stays phase-locked and never restarts. - ShoeGaze: globalTestSource + globalTestBus (lazy via ensureGlobalTestSource), per-board testLoopTaps; teardown removes taps + source and releases the bus. - New TestLoopTap (generic bus copy, like HardwareInputPassThrough). - ShoeGazeError.testBusUnavailable for an exhausted bus pool. - Test: testLoop boards share the source via taps; removal leaves others intact. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
536 lines
25 KiB
Swift
536 lines
25 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
|
|
|
|
/// 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
|
|
|
|
// 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: - 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
|
|
installScopeTap()
|
|
}
|
|
|
|
// MARK: - Board management
|
|
|
|
/// 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)
|
|
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
|
|
)
|
|
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
|
|
)
|
|
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
|
|
)
|
|
// 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
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
|
|
// 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?
|
|
|
|
/// 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
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// - 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)
|
|
|
|
// 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)
|
|
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()
|
|
|
|
// 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()
|
|
}
|
|
}
|