1.0 release

This commit is contained in:
2026-06-21 12:25:18 -07:00
parent b7973cba9a
commit 6f55615d7b
81 changed files with 10968 additions and 0 deletions
@@ -0,0 +1,154 @@
// 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
}
}
@@ -0,0 +1,328 @@
// 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
/// 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
) throws {
self.engine = engine
// 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)
let createdBoardB: PedalBoard = try PedalBoard(engine: engine)
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.
let master: BoardOutputMaster = BoardOutputMaster(boardOutputBusIndex: 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)
}
}
@@ -0,0 +1,87 @@
// Merger.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sums two branch buses to a single output bus with independent per-branch levels.
///
/// Intended as the downstream companion to ``Splitter`` when combining two parallel
/// signal paths back into a single chain. Each branch contributes its signal scaled
/// by its level parameter; the two scaled signals are summed into `outputBus`.
///
/// ## Signal graph
///
/// ```
/// inputBusA → In.Audio × levelA ──┐
/// + → outputBus
/// inputBusB → In.Audio × levelB ──┘
/// ```
///
/// ## Parameters
///
/// - `levelA`: Gain applied to branch A before summing. `1.0` = unity gain, `0.0` = muted.
/// - `levelB`: Gain applied to branch B before summing. `1.0` = unity gain, `0.0` = muted.
///
/// > Note: With both defaults at `1.0`, two branches carrying the same signal sum to
/// > approximately 2× amplitude. In normal use the ``Splitter`` routes independent bus
/// > paths to each branch, so they carry different signals and this doubling does not
/// > occur. For an empty (pass-through) branch with `levelA = levelB = 1.0`, lower
/// > one of the levels or attenuate in the signal chain to avoid the additive boost.
///
/// - Parameters:
/// - inputBusA: Audio bus index from which branch A's signal is read.
/// - inputBusB: Audio bus index from which branch B's signal is read.
/// - outputBus: Audio bus index to which the summed output is written.
public final class Merger: SynthesizerBase {
// MARK: - Parameters
/// Level for branch A. `1.0` = unity gain, `0.0` = muted.
@UIParam public var levelA: Double = 1.0
/// Level for branch B. `1.0` = unity gain, `0.0` = muted.
@UIParam public var levelB: Double = 1.0
// MARK: - Routing
/// Audio bus index from which branch A's signal is read.
public internal(set) var inputBusA: Int
/// Audio bus index from which branch B's signal is read.
public internal(set) var inputBusB: Int
/// Audio bus index to which the summed output is written.
public internal(set) var outputBus: Int
// MARK: - Init
/// Creates a merger that sums two branch buses into one output bus.
///
/// - Parameters:
/// - inputBusA: Audio bus index from which branch A's signal is read.
/// - inputBusB: Audio bus index from which branch B's signal is read.
/// - outputBus: Audio bus index to which the summed output is written.
public init(
inputBusA: Int,
inputBusB: Int,
outputBus: Int
) {
self.inputBusA = inputBusA
self.inputBusB = inputBusB
self.outputBus = outputBus
super.init()
}
// MARK: - Build
/// Builds the signal graph: (inputBusA × levelA) + (inputBusB × levelB) → outputBus.
public override func build() {
let sigA: In.Audio = input(bus: inputBusA)
let sigB: In.Audio = input(bus: inputBusB)
output(bus: outputBus, source: (sigA * $levelA) + (sigB * $levelB))
}
}
@@ -0,0 +1,79 @@
// ParallelSection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A parallel signal-routing section inside a ``PedalBoard``.
///
/// A `ParallelSection` is created by ``PedalBoard/split()`` and holds the two independent
/// branch sub-chains plus the ``Splitter`` node that feeds them. After adding pedals to each
/// branch, pass the section to ``PedalBoard/merge(_:)`` to combine the branches back into
/// the main board chain.
///
/// ## Typical usage
///
/// ```swift
/// let section = try board.split()
/// try section.branchA.add(DelayPedal())
/// try section.branchB.add(FuzzPedal())
/// try board.merge(section)
/// // Further board.add(_:) calls chain after the merger.
/// ```
///
/// ## Evaluation order
///
/// Both branches share a single `SharedTail` tracking pointer so all pedals from both
/// branches are inserted in a flat linear sequence in the node tree. Signal-flow parallelism
/// is expressed via independent buses, not via tree structure:
///
/// ```
/// … → Splitter → [branchA pedals] → [branchB pedals] → Merger → …
/// ```
///
/// The merger is inserted after the `SharedTail` — i.e. after the last pedal added across
/// either branch — so all branch pedals have written their output buses before the merger reads
/// them. This guarantees correctness regardless of the order in which the caller adds pedals to
/// the two branches.
@MainActor
public final class ParallelSection {
// MARK: - Nodes and chains
/// The splitter that routes the pre-section signal into the two branches.
public let splitter: Splitter
/// Sub-chain A of this parallel section.
public let branchA: BranchChain
/// Sub-chain B of this parallel section.
public let branchB: BranchChain
/// Shared tail pointer updated by both branch chains. Used by ``PedalBoard/merge(_:)``
/// to determine the node after which the merger should be inserted.
internal let sharedTail: SharedTail
// MARK: - Init
/// Creates a parallel section. Called internally by ``PedalBoard/split()``.
///
/// - Parameters:
/// - splitter: The ``Splitter`` node that fans out into the two branches.
/// - branchA: The first branch sub-chain, fed by the splitter's A output bus.
/// - branchB: The second branch sub-chain, fed by the splitter's B output bus.
/// - sharedTail: The shared tail tracking pointer used by both branch chains.
init(
splitter: Splitter,
branchA: BranchChain,
branchB: BranchChain,
sharedTail: SharedTail
) {
self.splitter = splitter
self.branchA = branchA
self.branchB = branchB
self.sharedTail = sharedTail
}
}
@@ -0,0 +1,27 @@
// SplitMode.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Routing mode for a ``Splitter``.
///
/// Controls which of the two output branches carries signal:
///
/// - `.a`: Only branch A passes; branch B is muted.
/// - `.b`: Only branch B passes; branch A is muted.
/// - `.both`: Both branches carry the full input signal (parallel operation).
///
/// Transitions between modes are click-free because the ``Splitter`` applies
/// a lag to each branch enable value.
public enum SplitMode: String, Codable, CaseIterable {
/// Branch A active, branch B muted.
case a
/// Branch B active, branch A muted.
case b
/// Both branches active (parallel routing).
case both
}
@@ -0,0 +1,129 @@
// Splitter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Routes one input bus to two independent output buses with click-free per-branch enables.
///
/// Both branches read the same input signal. Each branch level is lagged through a
/// ``Lag.Control`` so enable/disable transitions are artefact-free (no abrupt cuts).
///
/// Use ``mode`` as a convenience setter to configure common routing patterns:
/// - `.a` → branch A on, branch B muted
/// - `.b` → branch B on, branch A muted
/// - `.both` → both branches active (full parallel routing)
///
/// ## Signal graph
///
/// ```
/// inputBus → In.Audio
/// ├── × Lag(branchAEnabled) → outputBusA
/// └── × Lag(branchBEnabled) → outputBusB
/// ```
///
/// ## Parameters
///
/// - `branchAEnabled`: Branch A level. `1.0` = passing, `0.0` = muted.
/// - `branchBEnabled`: Branch B level. `1.0` = passing, `0.0` = muted.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the input signal from.
/// - outputBusA: Audio bus index to write branch A's output to.
/// - outputBusB: Audio bus index to write branch B's output to.
public final class Splitter: SynthesizerBase {
// MARK: - Parameters
/// Branch A level. `1.0` = passing, `0.0` = muted. Transitions are click-free.
@UIParam public var branchAEnabled: Double = 1.0
/// Branch B level. `1.0` = passing, `0.0` = muted. Transitions are click-free.
@UIParam public var branchBEnabled: Double = 1.0
// MARK: - Routing
/// Audio bus index from which the input signal is read.
public internal(set) var inputBus: Int
/// Audio bus index to which branch A's output is written.
public internal(set) var outputBusA: Int
/// Audio bus index to which branch B's output is written.
public internal(set) var outputBusB: Int
// MARK: - Constants
/// Lag time in seconds for branch enable transitions.
/// Prevents audible clicks when toggling a branch on or off.
private let switchLagTime: Double = 0.02
/// Threshold above which an enable value is treated as "on" for ``mode`` getter.
private let enableThreshold: Double = 0.5
// MARK: - Init
/// Creates a splitter that routes one input bus to two branch buses.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the input signal from.
/// - outputBusA: Audio bus index to write branch A's output to.
/// - outputBusB: Audio bus index to write branch B's output to.
public init(
inputBus: Int,
outputBusA: Int,
outputBusB: Int
) {
self.inputBus = inputBus
self.outputBusA = outputBusA
self.outputBusB = outputBusB
super.init()
}
// MARK: - Mode convenience
/// Routing mode derived from the current branch enable values.
///
/// - Getting: Returns `.both` if both enables are ≥ 0.5; `.a` if only branch A
/// is ≥ 0.5; `.b` if only branch B is ≥ 0.5. Returns `.a` if both are below 0.5
/// (neither branch active — `.a` is the least-surprising fallback).
/// - Setting: Updates `branchAEnabled` and `branchBEnabled` to match the chosen mode.
/// `.a` → (1, 0); `.b` → (0, 1); `.both` → (1, 1). Transitions are click-free.
public var mode: SplitMode {
get {
let aOn: Bool = branchAEnabled >= enableThreshold
let bOn: Bool = branchBEnabled >= enableThreshold
if aOn && bOn { return .both }
if aOn { return .a }
if bOn { return .b }
return .a
}
set {
switch newValue {
case .a:
branchAEnabled = 1.0
branchBEnabled = 0.0
case .b:
branchAEnabled = 0.0
branchBEnabled = 1.0
case .both:
branchAEnabled = 1.0
branchBEnabled = 1.0
}
}
}
// MARK: - Build
/// Builds the signal graph: input → lagged per-branch gain → two output buses.
public override func build() {
let inSig: In.Audio = input(bus: inputBus)
let gainA: Lag.Control = Lag.Control(input: $branchAEnabled, time: switchLagTime)
let gainB: Lag.Control = Lag.Control(input: $branchBEnabled, time: switchLagTime)
output(bus: outputBusA, source: inSig * gainA)
output(bus: outputBusB, source: inSig * gainB)
}
}