Files
ShoeGaze/Sources/LyrebirdShoeGaze/Routing/BranchChain.swift
T
2026-06-21 12:25:18 -07:00

155 lines
6.1 KiB
Swift

// BranchChain.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A linear sub-chain of pedals within one branch of a parallel section.
///
/// `BranchChain` mirrors ``PedalBoard/add(_:)`` logic but writes into branch-local buses
/// rather than the board's main bus path. Each call to ``add(_:)`` allocates a new output
/// bus, configures the pedal's sample rate and bus indices, and inserts the pedal into the
/// engine immediately after the current shared tail node.
///
/// ## Evaluation order
///
/// Both branches in a ``ParallelSection`` share a single `sharedTail` pointer so that all
/// branch pedals appear in a flat linear sequence in the engine's node tree. The tree layout is:
///
/// ```
/// Splitter → [branchA pedals in order] → [branchB pedals in order] → Merger
/// ```
///
/// Despite being "parallel" in signal-flow terms (each branch reads from an independent
/// splitter output bus), correctness requires that all pedals that write their respective
/// output buses evaluate before the ``Merger`` reads those buses. The flat linear layout
/// guarantees this regardless of which branch pedals are added first.
///
/// A `BranchChain` is created by ``PedalBoard/split()`` and is accessed via
/// ``ParallelSection/branchA`` and ``ParallelSection/branchB``. Call ``PedalBoard/merge(_:)``
/// to combine the two branches back into the main chain after adding pedals.
@MainActor
public final class BranchChain {
// MARK: - State
private let engine: SynthesisEngine
/// All pedals in this branch in insertion (signal-flow) order.
public private(set) var pedals: [Pedal] = []
/// Index of the bus that the last pedal in this branch writes to. Before any pedal is
/// added this is the branch's input bus (the output of the splitter for this branch).
public private(set) var tailBusIndex: Int
/// Shared tail node pointer. Both branches in a ``ParallelSection`` share the same
/// `SharedTail` wrapper so all pedals are inserted in a flat linear order.
private let sharedTail: SharedTail
/// All buses allocated by this branch (for release on teardown).
private var allocatedBuses: [AudioBus] = []
/// Sample rate injected from the board, used to configure each added pedal.
private let sampleRate: Double
// MARK: - Init
/// Creates a branch chain seeded to a particular starting bus and shared tail reference.
///
/// This initialiser is called internally by ``PedalBoard/split()``. Callers never
/// construct a `BranchChain` directly.
///
/// - Parameters:
/// - engine: The `SynthesisEngine` that will own the branch's pedal nodes.
/// - inputBus: The bus index from which the first pedal in the branch reads its input.
/// - sampleRate: The engine sample rate; injected into each added pedal.
/// - sharedTail: Shared mutable reference to the current tree tail node. Both branches
/// of the same `ParallelSection` share this wrapper so insertions from either branch
/// form a flat linear chain rather than sibling trees both rooted at the splitter.
init(
engine: SynthesisEngine,
inputBus: AudioBus,
sampleRate: Double,
sharedTail: SharedTail
) {
self.engine = engine
self.tailBusIndex = inputBus.index
self.sampleRate = sampleRate
self.sharedTail = sharedTail
self.allocatedBuses.append(inputBus)
}
// MARK: - Adding pedals
/// Appends a pedal to the end of this branch and adds it to the engine.
///
/// The pedal's `inputBus` is set to the current branch tail bus; a new mono bus is
/// allocated for its `outputBus`. After this call, ``tailBusIndex`` advances to the
/// new output bus.
///
/// The pedal is inserted after the shared tail node (which may be the splitter, or a
/// pedal from either branch), so all branch pedals appear in the tree in the order they
/// were added across both branches combined.
///
/// - Parameter pedal: The pedal to append to this branch.
/// - Throws:
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available.
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
public func add(_ pedal: Pedal) throws {
let pedalOutputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
allocatedBuses.append(pedalOutputBus)
pedal.inputBus = tailBusIndex
pedal.outputBus = pedalOutputBus.index
pedal.sampleRate = sampleRate
try engine.add(pedal, position: .after(sharedTail.node))
pedals.append(pedal)
sharedTail.node = pedal
tailBusIndex = pedalOutputBus.index
}
// MARK: - Teardown
/// Removes all pedals from the engine and releases all allocated buses.
///
/// Called internally by ``PedalBoard/teardown()`` when the board is torn down.
/// After calling this method the `BranchChain` should not be reused.
func teardown() {
for pedal: Pedal in pedals {
engine.remove(pedal)
}
pedals.removeAll()
for bus: AudioBus in allocatedBuses {
engine.busAllocator.releaseAudioBus(bus)
}
allocatedBuses.removeAll()
}
}
// MARK: - SharedTail
/// A mutable reference wrapper for the current tree-tail node shared between branch chains.
///
/// Both ``BranchChain`` instances in a ``ParallelSection`` hold the same `SharedTail` so
/// that insertions from either branch always go after the most recently inserted node — forming
/// a flat linear chain in the node tree. Isolation is provided by `@MainActor`.
@MainActor
final class SharedTail {
/// The current tree-tail node. Updated by each `BranchChain.add(_:)` call.
var node: any Synthesizer
/// Creates a `SharedTail` seeded to the given node (typically the ``Splitter``).
///
/// - Parameter node: The initial tail — the node after which the first branch pedal will
/// be inserted.
init(node: any Synthesizer) {
self.node = node
}
}