// PedalBoard.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation 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.. AudioBus { guard let rightTail: AudioBus = outputBusRight else { throw ShoeGazeError.stereoWidthExceeded } return rightTail } // MARK: - Stereo width helpers /// Allocates a mono inter-node bus and tracks it for release on teardown. private func allocateInterNodeBus() throws -> AudioBus { let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) allocatedBuses.append(bus) return bus } /// Inserts a node into the engine maintaining evaluation order, then records it as `lastNode`. /// /// Inserts `.after(lastNode)` when a previous node exists, else `.after` the caller-supplied /// predecessor or `headInputNode`, else a plain add as a last resort. private func insertNode(_ node: any Synthesizer, after predecessor: (any Synthesizer)?) throws { if let previous: any Synthesizer = lastNode { try engine.add(node, position: .after(previous)) } else if let pred: any Synthesizer = predecessor ?? headInputNode { try engine.add(node, position: .after(pred)) } else { try engine.add(node) } lastNode = node } /// Advances the chain tail to the given bus pair and width. private func advanceTail(left: AudioBus, right: AudioBus?, width: Int) { self.outputBus = left self.outputBusRight = right self.width = width } /// Collapses a stereo (width-2) tail back to mono by summing the two tails (×0.5 each) /// through a ``Merger``. No-op when the chain is already mono. /// /// - Throws: /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the merger add. public func mergeToMono() throws { guard width == 2, let rightTail: AudioBus = outputBusRight else { return } let monoBus: AudioBus = try allocateInterNodeBus() let merger: Merger = Merger( inputBusA: outputBus.index, inputBusB: rightTail.index, outputBus: monoBus.index ) // Sum with equal half-gains so two correlated channels do not double in level. merger.levelA = 0.5 merger.levelB = 0.5 try insertNode(merger, after: nil) routingNodes.append(merger) advanceTail(left: monoBus, right: nil, width: 1) orderedSegments.append(.mergeToMono) } // MARK: - Stereo split /// Fans the current mono tail into two independently authored branch chains that become the /// stereo output pair, plus a clean dry tap for the `bypass` route. /// /// Add pedals via `section.left.add(_:)` / `section.right.add(_:)`, then call /// `collectStereo(_:)` to wire the route collector and advance the board to width 2. /// Set `section.route` to choose the output mode (`stereo` / `leftOnly` / `rightOnly` / /// `bypass`) at any time. /// /// - Returns: A ``StereoSplitSection`` with two empty branch chains. /// - Throws: /// - `ShoeGazeError.stereoWidthExceeded` if the board is already stereo. /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the splitter add. public func splitStereo() throws -> StereoSplitSection { guard width == 1 else { throw ShoeGazeError.stereoWidthExceeded } let preBus: AudioBus = outputBus // Branch input buses are owned (and released) by each BranchChain, not by the board, // mirroring `split()`. The dry tap is board-owned. let leftInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let rightInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let dryTapBus: AudioBus = try allocateInterNodeBus() let splitter: StereoSplitter = StereoSplitter( inputBus: preBus.index, outputBusLeft: leftInBus.index, outputBusRight: rightInBus.index, dryTapBus: dryTapBus.index ) // Both branches share one tail pointer so their pedals form a flat linear sequence, // guaranteeing all branch pedals evaluate before the collector regardless of add order. // Construct and track the branch chains (which take ownership of `leftInBus`/`rightInBus`) // BEFORE the throwing engine insert below, so those buses are always released on teardown // even if the splitter add fails. let tail: SharedTail = SharedTail(node: splitter) let leftChain: BranchChain = BranchChain( engine: engine, inputBus: leftInBus, sampleRate: engine.sampleRate, sharedTail: tail ) let rightChain: BranchChain = BranchChain( engine: engine, inputBus: rightInBus, sampleRate: engine.sampleRate, sharedTail: tail ) branchChains.append(leftChain) branchChains.append(rightChain) try insertNode(splitter, after: nil) routingNodes.append(splitter) let section: StereoSplitSection = StereoSplitSection( splitter: splitter, left: leftChain, right: rightChain, sharedTail: tail, dryTapBus: dryTapBus ) stereoSplitSections.append(section) orderedSegments.append(.stereoSplit(section)) return section } /// Splits the current **stereo** tail into two independently authored branch chains — left /// channel into one, right channel into the other — so the channels can be processed /// separately, then recombined to stereo by ``collectStereo(_:)``. /// /// The stereo counterpart of ``splitStereo()``: it requires a width-2 tail and uses a /// ``StereoUnzipSplitter`` (which reads both channels) instead of a mono-duplicating /// ``StereoSplitter``. Everything downstream (branch chains, route collector, route control) /// is identical, so it returns the same ``StereoSplitSection`` type. /// /// Route semantics for the reused ``StereoRouteCollector`` differ from a mono split, because /// each lane here carries one *original* channel rather than a duplicated mono signal: /// `.stereo` = L lane → left, R lane → right; `.leftOnly` / `.rightOnly` = center the chosen /// lane (so you hear only that original channel, processed, in both speakers); `.bypass` = /// the centered mono sum (`0.5·L + 0.5·R`) of the pre-unzip signal in both speakers. /// /// - Returns: A ``StereoSplitSection`` with two empty branch chains; call `collectStereo(_:)` /// after adding branch pedals. /// - Throws: /// - `ShoeGazeError.cannotUnzipMonoChain` if the tail is mono (width 1). /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the splitter add. public func unzipStereo() throws -> StereoSplitSection { guard width == 2, let rightTail: AudioBus = outputBusRight else { throw ShoeGazeError.cannotUnzipMonoChain } let preLeft: AudioBus = outputBus let preRight: AudioBus = rightTail // Branch input buses are branch-owned (mirroring `splitStereo`); the dry tap is board-owned. let leftInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let rightInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) let dryTapBus: AudioBus = try allocateInterNodeBus() let splitter: StereoUnzipSplitter = StereoUnzipSplitter( inputLeft: preLeft.index, inputRight: preRight.index, outputBusLeft: leftInBus.index, outputBusRight: rightInBus.index, dryTapBus: dryTapBus.index ) let tail: SharedTail = SharedTail(node: splitter) let leftChain: BranchChain = BranchChain( engine: engine, inputBus: leftInBus, sampleRate: engine.sampleRate, sharedTail: tail ) let rightChain: BranchChain = BranchChain( engine: engine, inputBus: rightInBus, sampleRate: engine.sampleRate, sharedTail: tail ) branchChains.append(leftChain) branchChains.append(rightChain) try insertNode(splitter, after: nil) routingNodes.append(splitter) let section: StereoSplitSection = StereoSplitSection( splitter: splitter, left: leftChain, right: rightChain, sharedTail: tail, dryTapBus: dryTapBus ) stereoUnzipSections.append(section) orderedSegments.append(.stereoUnzip(section)) return section } /// Inserts the route collector for a stereo split section and advances the board to width 2. /// /// The collector reads both branch tails and the dry tap, and writes the board's new left and /// right tail buses. It is inserted after the section's shared tail (the last pedal added /// across either branch), so all branch pedals have written their buses before it reads them. /// Branches with no pedals pass their split signal straight through. /// /// - Parameter section: A section returned by `splitStereo()`. /// - Throws: /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the collector add. public func collectStereo(_ section: StereoSplitSection) throws { let outLeft: AudioBus = try allocateInterNodeBus() let outRight: AudioBus = try allocateInterNodeBus() let collector: StereoRouteCollector = StereoRouteCollector( inputBusLeft: section.left.tailBusIndex, inputBusRight: section.right.tailBusIndex, dryTapBus: section.dryTapBus.index, outputBusLeft: outLeft.index, outputBusRight: outRight.index ) // Insert after the shared tail — the most recently added node across both branches. try engine.add(collector, position: .after(section.sharedTail.node)) routingNodes.append(collector) lastNode = collector section.bind(collector: collector) advanceTail(left: outLeft, right: outRight, width: 2) } // 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) let section: ParallelSection = ParallelSection( splitter: splitter, branchA: chainA, branchB: chainB, sharedTail: tail ) orderedSegments.append(.parallel(section)) return section } /// 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 orderedSegments.removeAll() stereoSplitSections.removeAll() stereoUnzipSections.removeAll() // 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() } }