353 lines
16 KiB
Swift
353 lines
16 KiB
Swift
// PedalBoard.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import LyrebirdSynth
|
|
import LyrebirdUI
|
|
|
|
/// A linear signal chain of `Pedal` instances sharing a dedicated mono bus path, with
|
|
/// optional parallel sections created via `split()` and `merge()`.
|
|
///
|
|
/// `PedalBoard` manages bus allocation and the engine node-tree insertion order
|
|
/// so that signal flows:
|
|
///
|
|
/// ```
|
|
/// headBus → pedal[0] → pedal[1] → … → pedal[N-1] → outputBus (tail)
|
|
/// ```
|
|
///
|
|
/// Parallel branches can be inserted at any point in the chain:
|
|
///
|
|
/// ```
|
|
/// headBus → pre-pedals → Splitter → branchA pedals ─┐
|
|
/// → branchB pedals ─┤
|
|
/// Merger → post-pedals → outputBus
|
|
/// ```
|
|
///
|
|
/// ## Evaluation order
|
|
///
|
|
/// Lyrebird evaluates the node tree top-to-bottom. Every node is inserted `.after` its
|
|
/// predecessor so signal flows correctly:
|
|
///
|
|
/// ```
|
|
/// headInputNode → pedal[0] → … → Splitter → branchA[0] → … → branchB[0] → … → Merger → …
|
|
/// ```
|
|
///
|
|
/// Both branch chains share a single tail tracking pointer so all branch pedals appear in
|
|
/// a flat linear sequence in the tree, regardless of which branch the caller adds pedals
|
|
/// to first. The merger is always inserted after the shared tail — i.e. after the last pedal
|
|
/// added across either branch — ensuring all branch pedals have evaluated before the merge.
|
|
///
|
|
/// ## Bus allocation
|
|
///
|
|
/// - One mono bus is allocated for the board head (`headBus`).
|
|
/// - Each `add(_:)` call allocates a new mono bus for the pedal's output.
|
|
/// - `split()` allocates two branch-input buses (one per branch) and one bus per pedal
|
|
/// added to each branch.
|
|
/// - `merge()` allocates one post-merge output bus.
|
|
/// - Hardware output buses (indices 0..<numOutputChannels) are managed by the engine
|
|
/// and are never requested from the bus allocator here.
|
|
///
|
|
/// ## Thread safety
|
|
///
|
|
/// `PedalBoard` is `@MainActor`. All methods must be called from the main thread.
|
|
@MainActor
|
|
public final class PedalBoard {
|
|
|
|
// MARK: - State
|
|
|
|
private let engine: SynthesisEngine
|
|
|
|
/// The bus that feeds the first pedal in the chain.
|
|
public let headBus: AudioBus
|
|
|
|
/// All pedals in order of insertion (signal-flow order) in the main chain (not branches).
|
|
public private(set) var pedals: [Pedal] = []
|
|
|
|
/// The bus that the last node in the chain writes to.
|
|
/// Before any node is added, this is `headBus` (the board is a pass-through).
|
|
public private(set) var outputBus: AudioBus
|
|
|
|
/// The node that writes the head bus (e.g. a `TestLoopSource` or input pass-through).
|
|
/// Set by `ShoeGaze` after adding the input source. When non-nil, the first `add(_:)`
|
|
/// call chains the first pedal after this node automatically (no `after:` arg needed).
|
|
public internal(set) var headInputNode: (any Synthesizer)?
|
|
|
|
/// 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"
|
|
|
|
/// The live master-gain `UIParamNode` for this board's output stage. `nil` until
|
|
/// `ShoeGaze.finalizeBoard(_:)` connects the output master. Bind a master-volume knob here.
|
|
public internal(set) var masterGainNode: UIParamNode?
|
|
|
|
/// The live board-select gain `UIParamNode` (`1` = audible, `0` = silenced), driven by
|
|
/// `ShoeGaze.selectBoard(_:crossfadeSeconds:)`. `nil` until `finalizeBoard(_:)`.
|
|
public internal(set) var selectGainNode: UIParamNode?
|
|
|
|
/// The live crossfade-time `UIParamNode` (seconds) for board-select transitions.
|
|
/// `nil` until `finalizeBoard(_:)`.
|
|
public internal(set) var crossfadeTimeNode: UIParamNode?
|
|
|
|
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
|
|
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
|
|
internal var outputMaster: BoardOutputMaster?
|
|
|
|
// MARK: - Private tracking
|
|
|
|
/// Tracks all allocated inter-node buses so they can be released on teardown.
|
|
private var allocatedBuses: [AudioBus] = []
|
|
|
|
/// The last node (pedal, splitter, or merger) inserted into the board. Used as the
|
|
/// `.after(_:)` predecessor for the next inserted node. Falls back to `headInputNode`
|
|
/// when no node has been added yet.
|
|
private var lastNode: (any Synthesizer)?
|
|
|
|
/// All splitter and merger nodes owned by the board (for removal on teardown).
|
|
private var routingNodes: [any Synthesizer] = []
|
|
|
|
/// All branch chains owned by the board (for teardown).
|
|
private var branchChains: [BranchChain] = []
|
|
|
|
// MARK: - Init
|
|
|
|
/// Creates a pedalboard that allocates its head bus and prepares for pedal insertion.
|
|
///
|
|
/// - Parameters:
|
|
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
|
|
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
|
public init(engine: SynthesisEngine) throws {
|
|
self.engine = engine
|
|
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
self.headBus = head
|
|
self.outputBus = head
|
|
self.allocatedBuses.append(head)
|
|
}
|
|
|
|
// MARK: - Tail node
|
|
|
|
/// The last node inserted into the board (pedal, splitter, or merger), or `nil` if no
|
|
/// node has been added yet. Used by `ShoeGaze.finalizeBoard(_:)` to position the master
|
|
/// synth after the entire chain.
|
|
///
|
|
/// Falls back to `headInputNode` when no node has been inserted; `finalizeBoard` handles
|
|
/// the case where both are `nil` by using a plain `engine.add`.
|
|
public var tailNode: (any Synthesizer)? { lastNode ?? headInputNode }
|
|
|
|
// MARK: - Adding pedals
|
|
|
|
/// Appends a pedal to the end of the signal chain and adds it to the engine.
|
|
///
|
|
/// The pedal's `inputBus` is set to the current tail bus index; a new mono bus is
|
|
/// allocated for its `outputBus`. After this call, `outputBus` advances to the
|
|
/// newly allocated output bus.
|
|
///
|
|
/// Signal order is maintained by inserting each node `.after(_:)` the previous one
|
|
/// in the engine's node tree. For the first pedal in the chain, pass `after:` the
|
|
/// node that writes the head bus (e.g. the input source) so evaluation order is
|
|
/// preserved: source evaluates first, then the pedal, then subsequent pedals.
|
|
/// Subsequent calls do not need `after:` — the board tracks `lastNode` internally.
|
|
///
|
|
/// - Parameters:
|
|
/// - pedal: The `Pedal` instance to append.
|
|
/// - after: The `Synthesizer` that the first pedal should evaluate after. Only used
|
|
/// when this is the first node added to the board. Ignored for subsequent nodes
|
|
/// (the board chains them after the previous node automatically).
|
|
/// - Throws:
|
|
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for output.
|
|
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
|
|
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
|
|
let pedalInputBus: AudioBus = outputBus
|
|
let pedalOutputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
allocatedBuses.append(pedalOutputBus)
|
|
|
|
pedal.inputBus = pedalInputBus.index
|
|
pedal.outputBus = pedalOutputBus.index
|
|
pedal.sampleRate = engine.sampleRate
|
|
|
|
// Maintain evaluation order: each node evaluates immediately after the previous.
|
|
// `lastNode` tracks the most recently inserted node (pedal, splitter, or merger).
|
|
// Falls back to the caller-supplied `predecessor` or `headInputNode` for the first
|
|
// node. If none is available, plain add is used as a last resort.
|
|
if let previous: any Synthesizer = lastNode {
|
|
try engine.add(pedal, position: .after(previous))
|
|
} else if let pred: any Synthesizer = predecessor ?? headInputNode {
|
|
try engine.add(pedal, position: .after(pred))
|
|
} else {
|
|
try engine.add(pedal)
|
|
}
|
|
|
|
pedals.append(pedal)
|
|
lastNode = pedal
|
|
outputBus = pedalOutputBus
|
|
}
|
|
|
|
// MARK: - Parallel routing
|
|
|
|
/// Inserts a parallel section into the board at the current tail position.
|
|
///
|
|
/// Creates a ``Splitter`` that routes the current tail bus into two independent
|
|
/// branch buses. Returns a ``ParallelSection`` with empty ``BranchChain``s;
|
|
/// add pedals to each branch via `section.branchA.add(_:)` and
|
|
/// `section.branchB.add(_:)`, then call ``merge(_:)`` to combine the branches.
|
|
///
|
|
/// ## Evaluation order
|
|
///
|
|
/// The splitter is inserted after the current tail node (`lastNode` or `headInputNode`).
|
|
/// Both branch chains share a ``SharedTail`` that starts at the splitter. Every subsequent
|
|
/// `BranchChain.add(_:)` advances the shared tail so pedals from either branch always
|
|
/// append after the previous insertion, forming a flat linear chain:
|
|
///
|
|
/// ```
|
|
/// Splitter → [branchA/B pedals in insertion order] → (Merger, added by merge(_:))
|
|
/// ```
|
|
///
|
|
/// - Returns: A ``ParallelSection`` with the splitter and two empty branch chains.
|
|
/// - Throws:
|
|
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
|
|
/// - `EngineAddError` if the engine rejects the splitter add.
|
|
public func split() throws -> ParallelSection {
|
|
let preBus: AudioBus = outputBus
|
|
|
|
let branchAInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
let branchBInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
// Branch input buses are tracked (and released) by each BranchChain, not here.
|
|
// Do not append to allocatedBuses to avoid a double-release on teardown.
|
|
|
|
let splitter: Splitter = Splitter(
|
|
inputBus: preBus.index,
|
|
outputBusA: branchAInBus.index,
|
|
outputBusB: branchBInBus.index
|
|
)
|
|
|
|
if let previous: any Synthesizer = lastNode {
|
|
try engine.add(splitter, position: .after(previous))
|
|
} else if let head: any Synthesizer = headInputNode {
|
|
try engine.add(splitter, position: .after(head))
|
|
} else {
|
|
try engine.add(splitter)
|
|
}
|
|
|
|
routingNodes.append(splitter)
|
|
lastNode = splitter
|
|
|
|
// Both branch chains share a single tail pointer so their pedals form a flat linear
|
|
// sequence in the node tree rather than two sibling sub-trees both rooted at the
|
|
// splitter. This guarantees all branch pedals evaluate before the merger regardless
|
|
// of whether the caller adds pedals to branchA first, branchB first, or interleaved.
|
|
let tail: SharedTail = SharedTail(node: splitter)
|
|
|
|
let chainA: BranchChain = BranchChain(
|
|
engine: engine,
|
|
inputBus: branchAInBus,
|
|
sampleRate: engine.sampleRate,
|
|
sharedTail: tail
|
|
)
|
|
let chainB: BranchChain = BranchChain(
|
|
engine: engine,
|
|
inputBus: branchBInBus,
|
|
sampleRate: engine.sampleRate,
|
|
sharedTail: tail
|
|
)
|
|
branchChains.append(chainA)
|
|
branchChains.append(chainB)
|
|
|
|
return ParallelSection(splitter: splitter, branchA: chainA, branchB: chainB, sharedTail: tail)
|
|
}
|
|
|
|
/// Combines the two branches of a ``ParallelSection`` back into the main board chain.
|
|
///
|
|
/// Creates a ``Merger`` that sums the tail buses of both branches into a new output bus.
|
|
/// The merger is inserted after the section's shared tail node — the last node inserted
|
|
/// across either branch. Because both branch chains share a single ``SharedTail`` pointer,
|
|
/// this is always the most recently added pedal from either branch, guaranteeing all branch
|
|
/// pedals have evaluated before the merger reads their output buses.
|
|
///
|
|
/// After `merge(_:)` returns, subsequent `board.add(_:)` calls chain after the merger.
|
|
///
|
|
/// - Parameter section: A ``ParallelSection`` returned by ``split()`` with pedals added to
|
|
/// each branch. Passing the same section twice or a section from a different board is
|
|
/// undefined behaviour.
|
|
/// - Throws:
|
|
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the post-merge bus.
|
|
/// - `EngineAddError` if the engine rejects the merger add.
|
|
public func merge(_ section: ParallelSection) throws {
|
|
let branchAOut: Int = section.branchA.tailBusIndex
|
|
let branchBOut: Int = section.branchB.tailBusIndex
|
|
|
|
let postBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
|
allocatedBuses.append(postBus)
|
|
|
|
let merger: Merger = Merger(
|
|
inputBusA: branchAOut,
|
|
inputBusB: branchBOut,
|
|
outputBus: postBus.index
|
|
)
|
|
|
|
// Insert merger after the shared tail — the last node inserted across either branch.
|
|
// Because both branch chains share a single `SharedTail` pointer, `sharedTail.node`
|
|
// is always the node that was most recently added to the tree (from either branch).
|
|
// This guarantees all branch pedals have written their output buses before the merger
|
|
// reads them, regardless of which branch the caller added pedals to last.
|
|
let mergerPredecessor: any Synthesizer = section.sharedTail.node
|
|
try engine.add(merger, position: .after(mergerPredecessor))
|
|
|
|
routingNodes.append(merger)
|
|
lastNode = merger
|
|
outputBus = postBus
|
|
}
|
|
|
|
// MARK: - Teardown
|
|
|
|
/// Removes all pedals, routing nodes, and branch chains from the engine and releases
|
|
/// all allocated buses.
|
|
///
|
|
/// Removal order follows the remove-before-release invariant:
|
|
///
|
|
/// 1. Remove main-chain pedals from the engine.
|
|
/// 2. Remove all routing nodes (splitters, mergers) — these write branch buses that
|
|
/// the next step releases, so they must be dequeued first.
|
|
/// 3. `BranchChain.teardown()` for each branch — removes branch pedals and releases
|
|
/// branch buses (safe because the splitter/merger writers are already dequeued).
|
|
/// 4. Release board-owned 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.
|
|
///
|
|
/// After calling this method the `PedalBoard` should not be reused.
|
|
public func teardown() {
|
|
// Step 1: Remove main-chain pedals.
|
|
for pedal: Pedal in pedals {
|
|
engine.remove(pedal)
|
|
}
|
|
pedals.removeAll()
|
|
|
|
// Step 2: Remove routing nodes (splitters and mergers) BEFORE releasing the branch
|
|
// buses they write/read. BranchChain.teardown() releases those buses in step 3,
|
|
// so the writers must be dequeued first.
|
|
for node: any Synthesizer in routingNodes {
|
|
engine.remove(node)
|
|
}
|
|
routingNodes.removeAll()
|
|
|
|
// Step 3: Remove branch pedals and release branch buses.
|
|
for chain: BranchChain in branchChains {
|
|
chain.teardown()
|
|
}
|
|
branchChains.removeAll()
|
|
|
|
lastNode = nil
|
|
|
|
// Step 4: Release board-owned buses (head bus and main-chain inter-node buses).
|
|
for bus: AudioBus in allocatedBuses {
|
|
engine.busAllocator.releaseAudioBus(bus)
|
|
}
|
|
allocatedBuses.removeAll()
|
|
}
|
|
}
|