// ChainRouter.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import LyrebirdUI /// Routes one shared input to two independent `PedalBoard` chains, then merges their /// outputs through a single `BoardOutputMaster` to stereo hardware output. /// /// ## Topology /// /// ``` /// inputSource → routerInputBus → Splitter → boardA.headBus → boardA chain ─┐ /// → boardB.headBus → boardB chain ─┤ /// Merger → routerMixBus → BoardOutputMaster → hw 0/1 /// ``` /// /// The ``mode`` property (delegating to ``splitter``) selects which chain is audible: /// - `.a` — only board A passes through; board B is muted. /// - `.b` — only board B passes through; board A is muted. /// - `.both` — both boards are summed at the merger (full parallel operation). /// /// ## Typical usage /// /// ```swift /// let router: ChainRouter = try shoeGaze.makeChainRouter() /// try router.addToA(OverdrivePedal()) /// try router.addToB(DelayPedal()) /// try router.finalize() /// router.mode = .both /// try engine.start() /// ``` /// /// Add pedals via ``addToA(_:)`` and ``addToB(_:)`` rather than calling `boardA.add` or /// `boardB.add` directly. These methods update an internal `lastInsertedNode` pointer so /// ``finalize()`` can always place the merger after the true last node in the evaluation /// tree, regardless of the order in which boards are populated. /// /// Do **not** add the router's boards to `ShoeGaze.boards` via `addBoard()` — /// this router owns their lifecycle. Call ``teardown()`` (or `ShoeGaze.teardown()`) /// to clean up. /// /// ## Evaluation order /// /// 1. `source` evaluates first and writes `routerInputBus`. /// 2. `splitter` evaluates immediately after `source`, reads `routerInputBus`, /// and writes `boardA.headBus` and `boardB.headBus`. /// 3. Each board's pedals evaluate in the order they were added via ``addToA(_:)`` / /// ``addToB(_:)``. Because `lastInsertedNode` is updated after every add, /// pedals from either board are always chained after the previously inserted node. /// 4. After ``finalize()``, the `merger` is inserted after `lastInsertedNode` /// (the overall last node across both boards, or the splitter when both are empty). /// 5. The `BoardOutputMaster` is inserted immediately after the merger. @MainActor public final class ChainRouter { // MARK: - Public boards /// The first pedalboard chain. /// /// Add pedals via ``addToA(_:)`` (preferred) to keep ``finalize()`` ordering correct. /// This property is public for read-only inspection and UI binding only. public let boardA: PedalBoard /// The second pedalboard chain. /// /// Add pedals via ``addToB(_:)`` (preferred) to keep ``finalize()`` ordering correct. /// This property is public for read-only inspection and UI binding only. public let boardB: PedalBoard // MARK: - Routing nodes /// The splitter that distributes the shared input to both board head buses. public let splitter: Splitter /// The merger that combines both board output buses. /// `nil` until ``finalize()`` is called. public private(set) var merger: Merger? // MARK: - Mode convenience /// Routing mode. Delegates to ``splitter``. /// /// - `.a` → board A audible, board B muted. /// - `.b` → board B audible, board A muted. /// - `.both` → both boards summed at the merger. /// /// Transitions are click-free (the splitter lags branch enables over 20 ms). public var mode: SplitMode { get { splitter.mode } set { splitter.mode = newValue } } // MARK: - Master stage /// The live master-gain `UIParamNode` for the router's output stage. `nil` until /// ``finalize()`` is called. Bind a master-volume knob here. public internal(set) var masterGainNode: UIParamNode? // MARK: - Private private let engine: SynthesisEngine /// Shared tempo clock, forwarded to both sub-boards so tempo-aware pedals quantize to beats. private let clock: LyrebirdClock? /// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`). private let source: any Synthesizer /// The bus that the input source writes to, shared by both board head buses via the splitter. private let routerInputBus: AudioBus /// The bus that the merger writes to, read by the `BoardOutputMaster`. /// Allocated during ``finalize()``. private var routerMixBus: AudioBus? /// The output master synth. `nil` until ``finalize()`` is called. private var outputMaster: BoardOutputMaster? /// The board whose first pedal was added earliest (i.e. the board that received its first /// `addToA` / `addToB` call first). Because each board's first pedal inserts /// `.after(splitter)` and subsequent boards push the earlier board further down the /// evaluation list, the first-populated board's tail node is always the last node /// evaluated across both boards — regardless of populate order. ``finalize()`` uses /// `firstPopulatedBoard.tailNode` to place the merger after the full tree. /// /// `nil` until the first `addToA` or `addToB` call. private var firstPopulatedBoard: PedalBoard? /// Guard that prevents pedals being added after the merger has been inserted. private var finalized: Bool = false // MARK: - Init /// Creates a chain router backed by `engine` with the given input source policy. /// /// Allocates `routerInputBus`, adds the input source to the engine, creates `boardA` /// and `boardB` (each with their own `headBus`), creates the `Splitter` and adds it /// after the source, then sets both boards' `headInputNode` to the splitter so the /// first pedal on each board chains after the splitter automatically. /// /// Call ``finalize()`` after all pedals have been added to both boards via /// ``addToA(_:)`` and ``addToB(_:)``. /// /// - Parameters: /// - engine: The `SynthesisEngine` that will own all nodes. /// - inputSource: How the shared input bus is fed. Defaults to `.testLoop`. /// - Throws: /// - `ShoeGazeError.liveInputRequiresInputChannels` when `.liveInput` is used /// but `engine.numInputChannels == 0`. /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects any node insertion. public init( engine: SynthesisEngine, inputSource: InputSource = .testLoop, clock: LyrebirdClock? = nil ) throws { self.engine = engine self.clock = clock // Step 1 — allocate the shared input bus. let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) self.routerInputBus = inputBus // Step 2 — add the input source that writes the shared input bus. let addedSource: any Synthesizer switch inputSource { case .testLoop: let loop: TestLoopSource = TestLoopSource(targetBus: inputBus.index) try engine.add(loop) addedSource = loop case .liveInput(let channel): let hardwareInputBusIndex: Int do { hardwareInputBusIndex = try liveInputBusIndex(channel: channel, engine: engine) } catch { engine.busAllocator.releaseAudioBus(inputBus) throw error } let passThrough: HardwareInputPassThrough = HardwareInputPassThrough( inputBusIndex: hardwareInputBusIndex, outputBusIndex: inputBus.index ) try engine.add(passThrough) addedSource = passThrough } self.source = addedSource // Step 3 — create both boards (each allocates its own head bus). let createdBoardA: PedalBoard = try PedalBoard(engine: engine, clock: clock) let createdBoardB: PedalBoard = try PedalBoard(engine: engine, clock: clock) self.boardA = createdBoardA self.boardB = createdBoardB // Step 4 — create the splitter and insert it after the source. let builtSplitter: Splitter = Splitter( inputBus: inputBus.index, outputBusA: createdBoardA.headBus.index, outputBusB: createdBoardB.headBus.index ) try engine.add(builtSplitter, position: .after(addedSource)) self.splitter = builtSplitter // Step 5 — point each board's headInputNode at the splitter so the first // pedal on each board is inserted `.after(splitter)` automatically. createdBoardA.headInputNode = builtSplitter createdBoardB.headInputNode = builtSplitter } // MARK: - Pedal add helpers /// Appends a pedal to board A and, on the first call across either board, records /// board A as the first-populated board so ``finalize()`` can correctly place the /// merger after the full evaluation tree. /// /// - Parameter pedal: The pedal to append to board A's signal chain. /// - Throws: /// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called. /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the add. public func addToA(_ pedal: Pedal) throws { guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized } try boardA.add(pedal) // Record the first board to receive a pedal. The first-populated board's first // pedal inserts `.after(splitter)`; subsequent boards push it further down the // tree, making the first-populated board's tail always the last evaluated node. if firstPopulatedBoard == nil { firstPopulatedBoard = boardA } } /// Appends a pedal to board B and, on the first call across either board, records /// board B as the first-populated board so ``finalize()`` can correctly place the /// merger after the full evaluation tree. /// /// - Parameter pedal: The pedal to append to board B's signal chain. /// - Throws: /// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called. /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. /// - `EngineAddError` if the engine rejects the add. public func addToB(_ pedal: Pedal) throws { guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized } try boardB.add(pedal) // See addToA — only the first call across either board sets firstPopulatedBoard. if firstPopulatedBoard == nil { firstPopulatedBoard = boardB } } // MARK: - Finalize /// Completes the router by inserting the merger and output master into the engine. /// /// The merger is inserted after ``lastInsertedNode`` — the most recently added pedal /// across either board (via ``addToA(_:)`` / ``addToB(_:)``), or the splitter when /// neither board has any pedals. This placement is correct regardless of whether /// board A or board B was populated first. The `BoardOutputMaster` is inserted /// immediately after the merger and writes stereo hardware output buses 0 and 1. /// /// After `finalize()` returns, calls to ``addToA(_:)`` / ``addToB(_:)`` throw /// `ShoeGazeError.routerAlreadyFinalized`. /// /// - Throws: /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the mix bus. /// - `EngineAddError` if the engine rejects the merger or master node. public func finalize() throws { // Finalize step 1 — allocate the mix bus and create the merger. let mixBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) self.routerMixBus = mixBus let builtMerger: Merger = Merger( inputBusA: boardA.outputBus.index, inputBusB: boardB.outputBus.index, outputBus: mixBus.index ) // Insert the merger after the true last node in the evaluation tree. // // Both boards set headInputNode = splitter, so each board's first pedal inserts // `.after(splitter)`. The second board to add its first pedal pushes the first // board's chain further down the list. Therefore the board whose first pedal was // added FIRST always has its tail node last in the tree — `firstPopulatedBoard` // captures this. Fall back to the splitter when neither board has any pedals. let mergerPredecessor: any Synthesizer = firstPopulatedBoard?.tailNode ?? splitter try engine.add(builtMerger, position: .after(mergerPredecessor)) self.merger = builtMerger // Finalize step 2 — create the output master and insert it after the merger. The router's // full-bypass params are never driven (it isn't a board-bar board), so its dry source is // the mix bus itself — the bypass crossfade is a permanent no-op here. let master: BoardOutputMaster = BoardOutputMaster( boardOutputBusIndex: mixBus.index, dryInputBusIndex: mixBus.index ) try engine.add(master, position: .after(builtMerger)) self.outputMaster = master self.masterGainNode = master.gainNode finalized = true } // MARK: - Teardown /// Removes all router-owned nodes from the engine and releases the router buses. /// /// Calls `boardA.teardown()` and `boardB.teardown()` to remove pedals and release /// board buses. The router's own nodes (master, merger, splitter, source) are /// removed first so no node writes to a bus after it has been released. /// /// - 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. public func teardown() { // Remove master and merger (writers of routerMixBus) before releasing it. if let master: BoardOutputMaster = outputMaster { engine.remove(master) } if let builtMerger: Merger = merger { engine.remove(builtMerger) } // Remove splitter and source before boards release their head buses. engine.remove(splitter) engine.remove(source) // Remove all pedals from both boards and release board buses. boardA.teardown() boardB.teardown() // Release the router-owned buses. if let mixBus: AudioBus = routerMixBus { engine.busAllocator.releaseAudioBus(mixBus) } engine.busAllocator.releaseAudioBus(routerInputBus) } }