Files
ShoeGaze/Sources/LyrebirdShoeGaze/ShoeGaze.swift
T
2026-06-22 21:07:13 -07:00

411 lines
18 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 `TestLoopSource` is added to the engine
/// **before** the first pedal on each board (plain `engine.add` places it at the
/// head of `mainGroup`, so it evaluates first).
///
/// 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
private var testLoopSources: [TestLoopSource] = []
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:
let source: TestLoopSource = TestLoopSource(
targetBus: board.headBus.index,
sampleRate: engine.sampleRate
)
// Plain add → head of mainGroup (evaluates before any pedal).
try engine.add(source)
testLoopSources.append(source)
// Record the source as the head input node so PedalBoard.add(_:) can chain
// the first pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = source
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
}
/// 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
}
/// 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 source (writer of the head bus).
if let testLoop: TestLoopSource = board.headInputNode as? TestLoopSource {
engine.remove(testLoop)
testLoopSources.removeAll { $0 === testLoop }
} 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)
}
// 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()
/// ```
///
/// - 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). The method is `internal` rather than
/// `public` so callers outside the ShoeGaze module cannot disrupt board ordering.
///
/// - 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.
internal func moveBoard(_ board: PedalBoard, to index: Int) {
guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return }
let removed: PedalBoard = boards.remove(at: sourceIndex)
let destination: Int = min(index, boards.count)
boards.insert(removed, at: destination)
}
// 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 source: TestLoopSource in testLoopSources {
engine.remove(source)
}
testLoopSources.removeAll()
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()
}
}