// 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.. 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() } }