Files
ShoeGaze/Sources/LyrebirdShoeGaze/PedalBoard.swift
T
josh 947dfe427a Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal:

- Beat-quantized transport: record start and loop close both snap to the
  next beat via a LyrebirdRoutine waiting on the shared clock; loop length
  is an exact whole-beat span. Falls back to immediate/unquantized when no
  clock is present.
- Loop-length read-outs (frames/seconds/beats), transport state, and a
  sample-clock-derived play-head position for the UI timeline.
- Overdub undo (pre-dub snapshot + restore), reverse playback (live rate
  flip), and feedback-decay overdub (overdub preLevel via a Feedback knob).
- Inject the shared LyrebirdClock + SynthesisEngine into Pedal via
  PedalBoard/ChainRouter so tempo-aware pedals can reach them.
- New double-width LooperTimelineView (state badge, length read-out,
  sweeping play-head) wired into PedalView via Pedal.widthUnits.

Concurrency hardening from RT-safety review: a transportGeneration counter
drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop()
cannot recall once enqueued; the undo restore is deferred past the RT
overdub gate-close; transport routines use non-blocking stop().

Note: this commit also snapshots pre-existing uncommitted work-in-progress
already in the tree (MIDI control refactor, Tuner, Tempo, preset changes),
which is interleaved with the looper changes through shared files and could
not be split into a separately-building commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:22:20 -07:00

685 lines
31 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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..<numOutputChannels) are managed by the engine
/// and are never requested from the bus allocator here.
///
/// ## Thread safety
///
/// `PedalBoard` is `@MainActor`. All methods must be called from the main thread.
@MainActor
public final class PedalBoard {
// MARK: - State
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the
/// looper) can quantize to beats. `nil` for boards created without one.
private let clock: LyrebirdClock?
/// The bus that feeds the first pedal in the chain.
public let headBus: AudioBus
/// All pedals in order of insertion (signal-flow order) in the main chain (not branches).
public private(set) var pedals: [Pedal] = []
/// The bus that the last node in the chain writes to (left / mono tail).
/// Before any node is added, this is `headBus` (the board is a pass-through).
public private(set) var outputBus: AudioBus
/// The right-channel tail bus when the chain is stereo (``width`` == 2), else `nil`.
/// Set by a widener, a stereo-native pedal, an auto-stereoized pedal, or `collectStereo(_:)`;
/// cleared by `mergeToMono()`.
public private(set) var outputBusRight: AudioBus?
/// Current channel width of the chain tail: `1` = mono, `2` = stereo. Capped at 2.
public private(set) var width: Int = 1
/// All stereo split sections created via `splitStereo()` (for inspection / UI binding).
public private(set) var stereoSplitSections: [StereoSplitSection] = []
/// All stereo unzip sections created via ``unzipStereo()``. Same `StereoSplitSection` type as
/// ``stereoSplitSections``; tracked separately so a UI can distinguish the two region kinds.
public private(set) var stereoUnzipSections: [StereoSplitSection] = []
/// The node that writes the head bus (e.g. a `TestLoopSource` or input pass-through).
/// Set by `ShoeGaze` after adding the input source. When non-nil, the first `add(_:)`
/// call chains the first pedal after this node automatically (no `after:` arg needed).
public internal(set) var headInputNode: (any Synthesizer)?
/// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to
/// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from
/// a saved rig restores the saved id, so a board keeps its identity across edits and reorders.
public internal(set) var id: UUID = UUID()
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
public var label: String = "Board"
/// The live master-gain `UIParamNode` for this board's output stage. `nil` until
/// `ShoeGaze.finalizeBoard(_:)` connects the output master. Bind a master-volume knob here.
public internal(set) var masterGainNode: UIParamNode?
/// The live board-select gain `UIParamNode` (`1` = audible, `0` = silenced), driven by
/// `ShoeGaze.selectBoard(_:crossfadeSeconds:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var selectGainNode: UIParamNode?
/// The live crossfade-time `UIParamNode` (seconds) for board-select transitions.
/// `nil` until `finalizeBoard(_:)`.
public internal(set) var crossfadeTimeNode: UIParamNode?
/// The live per-board full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough).
/// `nil` until `finalizeBoard(_:)`. Driven by `ShoeGaze.setBoard(_:bypassed:)`.
public internal(set) var boardBypassNode: UIParamNode?
/// The live rig-wide full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough),
/// driven across every board by `ShoeGaze.setRigBypassed(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigBypassNode: UIParamNode?
/// The live rig-wide output-volume `UIParamNode` ([0, 1]), driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigVolumeNode: UIParamNode?
/// The live rig-wide output-mute `UIParamNode` (`0` = audible, `1` = silenced), driven across
/// every board by `ShoeGaze.setRigMuted(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigMuteNode: UIParamNode?
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
internal var outputMaster: BoardOutputMaster?
// MARK: - Private tracking
/// Tracks all allocated inter-node buses so they can be released on teardown.
private var allocatedBuses: [AudioBus] = []
/// The last node (pedal, splitter, or merger) inserted into the board. Used as the
/// `.after(_:)` predecessor for the next inserted node. Falls back to `headInputNode`
/// when no node has been added yet.
private var lastNode: (any Synthesizer)?
/// All splitter and merger nodes owned by the board (for removal on teardown).
private var routingNodes: [any Synthesizer] = []
/// All branch chains owned by the board (for teardown).
private var branchChains: [BranchChain] = []
/// Ordered signal-chain segments (pedals + split regions) in signal-flow order. Used to
/// capture full board topology for serialization and to drive signal-flow UIs. Maintained by
/// `add`/`split`/`splitStereo`. A segment's index here matches its index in
/// `captureState().segments` — the region index used by the lane-addressed edit API.
public private(set) var orderedSegments: [BoardSegment] = []
// MARK: - Init
/// Creates a pedalboard that allocates its head bus and prepares for pedal insertion.
///
/// - Parameters:
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
/// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for
/// beat-quantized transport. Optional; `nil` disables quantization for pedals on
/// this board.
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws {
self.engine = engine
self.clock = clock
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
self.headBus = head
self.outputBus = head
self.allocatedBuses.append(head)
}
// MARK: - Tail node
/// The last node inserted into the board (pedal, splitter, or merger), or `nil` if no
/// node has been added yet. Used by `ShoeGaze.finalizeBoard(_:)` to position the master
/// synth after the entire chain.
///
/// Falls back to `headInputNode` when no node has been inserted; `finalizeBoard` handles
/// the case where both are `nil` by using a plain `engine.add`.
public var tailNode: (any Synthesizer)? { lastNode ?? headInputNode }
// MARK: - Adding pedals
/// Appends a pedal to the end of the signal chain and adds it to the engine.
///
/// The pedal's `inputBus` is set to the current tail bus index; a new mono bus is
/// allocated for its `outputBus`. After this call, `outputBus` advances to the
/// newly allocated output bus.
///
/// Signal order is maintained by inserting each node `.after(_:)` the previous one
/// in the engine's node tree. For the first pedal in the chain, pass `after:` the
/// node that writes the head bus (e.g. the input source) so evaluation order is
/// preserved: source evaluates first, then the pedal, then subsequent pedals.
/// Subsequent calls do not need `after:` — the board tracks `lastNode` internally.
///
/// - Parameters:
/// - pedal: The `Pedal` instance to append.
/// - after: The `Synthesizer` that the first pedal should evaluate after. Only used
/// when this is the first node added to the board. Ignored for subsequent nodes
/// (the board chains them after the previous node automatically).
/// - Throws:
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for output.
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
// added to the engine.
switch pedal.channelKind {
case .mono:
if width == 1 {
// Mono region: one input, one output. Behaviour is identical to the original
// single-bus path.
let outLeft: AudioBus = try allocateInterNodeBus()
pedal.inputBus = outputBus.index
pedal.inputBusRight = nil
pedal.outputBus = outLeft.index
pedal.outputBusRight = nil
try insertNode(pedal, after: predecessor)
advanceTail(left: outLeft, right: nil, width: 1)
} else {
// Stereo region: auto-stereoize. The pedal runs `effect(_:)` per channel into
// two new buses — one logical pedal, two independent DSP graphs, shared knobs.
let rightTail: AudioBus = try requireRightTail()
let outLeft: AudioBus = try allocateInterNodeBus()
let outRight: AudioBus = try allocateInterNodeBus()
pedal.inputBus = outputBus.index
pedal.inputBusRight = rightTail.index
pedal.outputBus = outLeft.index
pedal.outputBusRight = outRight.index
try insertNode(pedal, after: predecessor)
advanceTail(left: outLeft, right: outRight, width: 2)
}
case .widener:
// 1 → 2. Only valid from a mono tail; width is capped at 2.
guard width == 1 else { throw ShoeGazeError.stereoWidthExceeded }
let outLeft: AudioBus = try allocateInterNodeBus()
let outRight: AudioBus = try allocateInterNodeBus()
pedal.inputBus = outputBus.index
pedal.inputBusRight = nil
pedal.outputBus = outLeft.index
pedal.outputBusRight = outRight.index
try insertNode(pedal, after: predecessor)
advanceTail(left: outLeft, right: outRight, width: 2)
case .stereoNative:
// 2 → 2 with cross-channel coupling. From a mono tail the input broadcasts to both
// channels (right input left nil); from a stereo tail it reads both tails.
let rightInput: Int? = (width == 2) ? try requireRightTail().index : nil
let outLeft: AudioBus = try allocateInterNodeBus()
let outRight: AudioBus = try allocateInterNodeBus()
pedal.inputBus = outputBus.index
pedal.inputBusRight = rightInput
pedal.outputBus = outLeft.index
pedal.outputBusRight = outRight.index
try insertNode(pedal, after: predecessor)
advanceTail(left: outLeft, right: outRight, width: 2)
}
pedals.append(pedal)
orderedSegments.append(.pedal(pedal))
}
/// Returns the right tail bus, enforcing the `width == 2 ⟺ outputBusRight != nil` invariant.
/// Throws rather than crashing if the invariant is ever violated by a coding error.
private func requireRightTail() throws -> 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()
}
}