Files
Lyrebird/Sources/Lyrebird/Synthesizer/SynthesizerBase.swift
T
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

670 lines
33 KiB
Swift

// SynthesizerBase.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
/// SynthesizerBase — the concrete base class most Synthesizer implementations should subclass.
///
/// Subclass SynthesizerBase, override `build()`, and call `addOutputGenerator(_:)` (or one
/// of the `output(bus:source:)` helpers) to register root generators. The engine calls
/// `evaluate()` automatically — do not override it.
///
/// **Side-effect generators auto-register.** Generators conforming to ``RootRegistering`` —
/// ``Out/Audio``, ``Out/Control``, ``RecordBuffer/Audio``, ``RecordBuffer/Control``,
/// ``DiskOut/Audio``, ``SendTrigger/Audio``, ``SendTrigger/Control`` — added themselves
/// to `outputGenerators` when constructed inside ``build()``. No ``addOutputGenerator(_:)``
/// or ``output(bus:source:)`` call needed; the result may be discarded with `let _ = ...`.
/// Use ``addOutputGenerator(_:)`` explicitly only when constructing a `RootRegistering`
/// generator OUTSIDE ``build()`` (e.g. in a helper called from a `LyrebirdTask`).
///
/// ## Parameters
///
/// Declare live parameters with `@LiveParam` (or `@UIParam` for SwiftUI binding) and wire
/// the projected value (`$name`) directly into your generator inputs:
///
/// ```swift
/// class SineTone: SynthesizerBase {
/// @LiveParam var freq: Double = 440.0
/// @LiveParam var amp: Double = 0.5
///
/// override func build() {
/// let osc = OscSin.Audio(freq: $freq, phase: 0.0)
/// output(bus: 0, source: osc * $amp)
/// }
/// }
/// ```
///
/// `@LiveParam` / `@UIParam` properties are auto-registered via `Mirror` reflection at
/// `build()` time. The property name (with the leading `_` of property-wrapper backing
/// storage stripped) is used as the parameter key for by-name updates.
///
/// Update parameters from the main thread at any time:
/// ```swift
/// note.freq = 880.0 // typed direct write
/// try? note.updateParameter("freq", value: 880.0) // by-name (e.g. OSC handler)
/// ```
///
/// Both routes write the same atomic. The RT audio thread picks up the new value at the
/// start of the next (sub-)block — never mid-block.
///
/// ## Thread-safety model
///
/// `SynthesizerBase` maintains strict temporal separation between main-thread and RT-thread
/// access to shared state:
///
/// - `parameterTable.inputs` is populated by `_autoRegisterLiveParams()` at the end of
/// `rebuildGraph()`, which runs on the scheduling (main) thread inside
/// `SynthesisEngine.prepareAddEvent` — *before* the `.add` event is enqueued. The RT thread
/// cannot reach this Synthesizer until after that enqueue completes.
///
/// - `parameterTable.inputs` is read on the RT thread inside `evaluate()` only when
/// constructing the local `SynthGraph`. Parameter values themselves flow through the
/// projected `ControlGenerator` nodes, which use a lock-free `Atomic<UInt64>` for the
/// main→RT communication.
///
/// - `updateParameter(_:value:)` (and `LyrebirdMessageContext.set`) write atomically to the
/// projected node — no queue, no RT-side dispatch.
///
/// **Double-add precondition:** calling `engine.add(synth)` while the same instance is
/// already active in the tree is undefined behaviour — `rebuildGraph()` would mutate
/// `outputGenerators` on the main thread concurrently with `evaluate()` iterating it on
/// the RT thread. Always `engine.remove(synth)` and allow at least one `processBlock` to
/// pass before re-adding the same instance.
///
/// ## Actor isolation
///
/// The class is `@MainActor`-isolated so consumer subclasses building under Xcode 26's
/// `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default override `build()` / `init()` with
/// no concurrency annotations — their MainActor default matches the base. The single
/// RT-thread entry point, `evaluate(graph:count:)`, is `nonisolated final`; the only two
/// stored properties it reads on the RT thread — `parameterTable` and `outputGenerators` —
/// are `nonisolated(unsafe)`, safe by the engine's add-event happens-before barrier
/// (see `ARCHITECTURE.md` §9 and the per-property comments below). No new runtime
/// synchronisation is introduced.
@MainActor
open class SynthesizerBase: Synthesizer {
// MARK: - Generator DAG
/// The root generators evaluated each block segment. Populated by build() via
/// addOutputGenerator(_:). Cleared before each build() call so re-add is safe.
///
/// **RT-safety:** only accessed from `evaluate()` (RT thread) and `rebuildGraph()`
/// (main thread, before the Synthesizer enters the node tree). Concurrent access is
/// prevented by the scheduling barrier in `SynthesisEngine.prepareAddEvent`.
///
/// `nonisolated(unsafe)`: written in `build()`/`rebuildGraph()` on main; read on the RT
/// thread in `evaluate()`. Cross-thread access is ordered by the add-event happens-before
/// edge through the SPSC `pendingQueue` — the RT thread cannot reach this synth until
/// `build()` has fully returned on main. See `ARCHITECTURE.md` §9.
nonisolated(unsafe) private var outputGenerators: [any Generator] = []
// MARK: - Parameter storage (RT-read / build-write)
/// Reference to this Synthesizer's parameter inputs.
///
/// Written during `build()` (main thread, before add). Read during `evaluate()`
/// (RT thread, after add) and also when building `SynthGraph` for downstream generators.
/// See `ParameterTable` for the full thread-safety model.
///
/// `nonisolated(unsafe)`: the `let` reference is immutable; `.inputs` is populated on main
/// in `_autoRegisterLiveParams()` before the add event is enqueued, and read on the RT
/// thread in `evaluate()` after the add barrier. Same happens-before edge as
/// `outputGenerators`. See `ARCHITECTURE.md` §9.
nonisolated(unsafe) private let parameterTable: ParameterTable = ParameterTable()
// MARK: - Engine binding
/// Set-once atomic binding to the `SynthesisEngine` that owns this
/// synth.
///
/// Stored as the raw bit pattern of an `UnsafeMutableRawPointer` to
/// the bound engine — zero = unbound, non-zero = pointer to the engine.
/// Written via `_bind(to:)` under acquire-release CAS; cleared via
/// `_unbind(from:)` after the RT thread has released its reference.
///
/// **RT-safety.** The RT thread never reads this field — bound state
/// is checked only on the main thread during `engine.add(_:)` before
/// SPSC handoff. Zero RT cost.
///
/// **Identity, not retention.** The stored pointer is `passUnretained`,
/// so the binding does not extend the engine's lifetime. If the engine
/// deinits while still holding this synth in its node tree, the engine
/// teardown path drops the node first, then the binding's referent is
/// already destroyed — but at that point nobody is calling `_bind`
/// against the stale pointer, so the dangling bit pattern is harmless.
internal let _engineBinding: Atomic<UInt> = Atomic<UInt>(0)
/// Attempt to bind this synth to `engine`. Acquires the binding atomic
/// via compare-exchange (expected 0 → desired pointer-to-engine).
/// On contention, classifies and throws.
///
/// Called by `SynthesisEngine.add(_:)` on the main thread before the
/// add event is enqueued onto `pendingQueue`. Must run before any RT
/// thread access to this synth.
///
/// - Parameter engine: The engine claiming ownership.
/// - Throws:
/// - `EngineAddError.doubleAdd(engine:)` — already bound to the same
/// engine (callee forgot a `remove`-before-`add`).
/// - `EngineAddError.boundToOtherEngine(current:prior:)` — bound to a
/// different engine. `prior` resolved by walking the
/// `EngineLifecycleCoordinator` registry; nil-fallback never fires
/// in practice because the prior engine cannot have deinited while
/// still holding a pointer here (engines unbind on teardown).
/// Maximum CAS passes in `_bind` before surfacing a generic
/// `.boundToOtherEngine`. Two passes cover the common
/// stale-pointer-then-retry case (one clear + one retry); more
/// iterations imply real contention where the structured error is
/// more useful than spinning.
nonisolated private static let bindMaxPasses: Int = 2
nonisolated internal func _bind(to engine: SynthesisEngine) throws {
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
let target: UInt = UInt(bitPattern: rawPointer)
// CAS-loop with stale-pointer recovery:
// if the binding atomic holds a non-zero pointer whose owning
// engine has since deinited without calling `_unbind`, the raw
// bit pattern is dangling. A subsequent engine allocated at
// (or aliasing into) the same address would otherwise produce
// a false-positive `.doubleAdd` instead of binding correctly.
// Validate the original pointer against the live-engine registry
// before classifying; if no live engine matches, force-clear the
// stale binding and retry the CAS. Loop is bounded — at most one
// stale-clear pass per call, then either success or a real
// collision.
for _: Int in 0..<SynthesizerBase.bindMaxPasses {
let (exchanged, original): (Bool, UInt) = _engineBinding.compareExchange(
expected: 0,
desired: target,
ordering: .acquiringAndReleasing
)
if exchanged { return }
if original == target {
throw EngineAddError.doubleAdd(engine: engine.identifier)
}
// Walk the live-engine registry to map `original` back to a
// UUID. Match by raw pointer identity — cheap, linear in
// engine count. Multi-engine processes typically run ≤ 4
// engines.
let priorEngine: SynthesisEngine? = EngineLifecycleCoordinator.shared.engines.first { other in
let otherRaw: UnsafeMutableRawPointer = Unmanaged.passUnretained(other).toOpaque()
return UInt(bitPattern: otherRaw) == original
}
if priorEngine == nil {
// Stale pointer — clear and retry. Concurrent winner is
// possible (another thread CAS'd between our load and
// clear) but the next iteration's CAS handles it
// correctly (either success or a fresh real collision).
_ = _engineBinding.compareExchange(
expected: original,
desired: 0,
ordering: .releasing
)
continue
}
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: priorEngine?.identifier
)
}
// Two passes failed — unrealistic contention. Surface as a
// generic collision so the caller sees a structured error.
throw EngineAddError.boundToOtherEngine(
current: engine.identifier,
prior: nil
)
}
/// Release this synth's binding to `engine`. Idempotent — if the
/// binding is already cleared, or held by a different engine (which
/// would itself be a violation), the call is a no-op.
///
/// Called by `SynthesisEngine.remove(_:)` on the main thread *after*
/// the RT thread has released its reference via the freeQueue drain.
/// Calling earlier would let a stale main-thread re-add race with the
/// RT-side iteration.
///
/// - Parameter engine: The engine releasing ownership.
nonisolated internal func _unbind(from engine: SynthesisEngine) {
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
let target: UInt = UInt(bitPattern: rawPointer)
_ = _engineBinding.compareExchange(
expected: target,
desired: 0,
ordering: .releasing
)
}
// MARK: - Init
public init() {}
// MARK: - Build
/// Override in subclasses. Call `addOutputGenerator(_:)` (or the `output(bus:source:)`
/// helpers) to configure the signal DAG. `@LiveParam` / `@UIParam` properties are
/// auto-registered after `build()` returns — no `declareParameter` call is needed.
/// Do NOT allocate mutable state outside of `build()` — this method is the allocation
/// point.
open func build() {}
// MARK: - Lifecycle
/// Begin a graceful release (typically post `gate = 0.0` so an envelope enters its
/// release phase). The default throws ``SynthesizerError/noGate``.
///
/// Declared here — rather than relying on the `Synthesizer` protocol extension default —
/// so subclasses genuinely `override` it and the call dispatches through the class
/// vtable. A protocol-extension default is bound statically at `SynthesizerBase`'s
/// conformance, so a subclass method would be invisible to every caller holding an
/// `any Synthesizer` — including ``Group/release(engine:)``, which cascades to its
/// children through exactly that existential.
///
/// Language-side only — never call from the RT audio thread.
///
/// - Parameter engine: The engine this synthesizer is bound to.
/// - Throws: ``SynthesizerError/noGate`` unless overridden.
open func release(engine: SynthesisEngine) throws {
throw SynthesizerError.noGate
}
/// Immediately remove this synthesizer from the node tree.
///
/// Posts a remove event at the current sample time; the synthesizer stops evaluating once
/// the RT thread applies it. Declared here for the same dispatch reason as
/// ``release(engine:)``.
///
/// Language-side only — never call from the RT audio thread.
///
/// - Parameter engine: The engine to remove this synthesizer from.
open func free(engine: SynthesisEngine) {
engine.remove(self)
}
/// Register a generator as a root output. Called from within build().
/// Typically the argument is an Out or ControlOut generator.
///
/// `RootRegistering` conformers constructed inside ``build()`` self-register and
/// do not need this call. Use ``addOutputGenerator(_:)`` for non-`RootRegistering`
/// generators or for `RootRegistering` generators constructed outside ``build()``
/// (where the task-local pointer is `nil` and auto-registration is a no-op).
///
/// **Do not double-register.** Calling this with a `RootRegistering` generator
/// that already auto-registered places it in `outputGenerators` twice; the
/// second evaluation is short-circuited by the segment-serial fan-out cache but
/// the duplicate entry is wasteful.
/// `nonisolated`: invoked from nonisolated `RootRegistering` generator inits during
/// `build()` (on main, before the add barrier). Mutates `outputGenerators`
/// (`nonisolated(unsafe)`) — same happens-before justification.
public nonisolated final func addOutputGenerator(_ generator: any Generator) {
outputGenerators.append(generator)
}
// MARK: - Auto-free lifecycle probe
/// Optional lifecycle probe — typically an `EnvelopeGen.{Audio,Control}` or a
/// `doneAction`-supporting buffer/line generator — inspected by `SynthesisEngine`
/// to schedule the synth's own removal once the probe's `needsFree` flips to
/// `true`. Set automatically when a `DoneActionWatchable` generator with
/// `doneAction: .freeNode` is constructed inside ``build()``, or explicitly via
/// ``autoFreeOnDone(_:)``.
///
/// `nonisolated(unsafe)`: set inside `build()` on main (before the add barrier) and read
/// later by the engine's auto-free watcher on a utility-queue timer. Effectively immutable
/// after `build()` returns — same cross-thread justification as `outputGenerators`.
nonisolated(unsafe) internal var _autoFreeProbe: (any DoneActionWatchable)?
/// `@unchecked Sendable` wrapper around an unowned `SynthesizerBase` pointer.
/// Avoids forcing `SynthesizerBase` itself (and every user subclass) to conform
/// to `Sendable`, which `@TaskLocal` would otherwise require.
internal struct _BuildingRef: @unchecked Sendable {
let synth: SynthesizerBase
}
/// Task-local pointer to the `SynthesizerBase` whose `build()` is currently
/// executing. Set by ``rebuildGraph()`` around the `build()` call. Read via
/// ``_currentlyBuilding`` by ``DoneActionWatchable/_registerAutoFreeIfNeeded(_:)``
/// from inside concrete generator inits to self-register when
/// `doneAction == .freeNode`. `nil` outside any `build()` context, in which case
/// auto-registration is a no-op and the explicit ``autoFreeOnDone(_:)`` escape
/// hatch remains available.
/// Convenience unwrapping of the build-context task-local.
///
/// The backing `@TaskLocal` lives in the file-scope ``_SynthesizerBuildContext`` enum,
/// not here: `@TaskLocal` on a `@MainActor` class generates a main-actor-isolated
/// `$`-projected accessor even under `nonisolated`, which the nonisolated
/// generator-init read path cannot reach — so the storage is hoisted out of this
/// `@MainActor` class into a plain nonisolated namespace.
///
/// `nonisolated`: read from nonisolated generator inits during `build()`.
nonisolated internal static var _currentlyBuilding: SynthesizerBase? {
_SynthesizerBuildContext.currentRef?.synth
}
/// Opt this synthesizer into automatic removal when the given probe
/// reports `needsFree`.
///
/// Any `DoneActionWatchable` generator (`EnvelopeGen`, `Line`, `ExponentialLine`,
/// `PlayBuffer`, `RecordBuffer`, `DiskIn`, `SpectralPlayBuffer`) constructed
/// inside ``build()`` with `doneAction: .freeNode` self-registers — no explicit
/// call needed:
///
/// ```swift
/// public override func build() {
/// let env: EnvelopeGen.Control = EnvelopeGen.Control(
/// envelope: myEnv,
/// timeScale: 8.0,
/// doneAction: .freeNode // self-registers
/// )
/// output(bus: 0, source: someSignal * env)
/// }
/// ```
///
/// Call ``autoFreeOnDone(_:)`` explicitly only when the probe is constructed
/// outside ``build()``, or for custom `DoneActionWatchable` conformers.
///
/// When the synth is added to a `SynthesisEngine`, the engine registers the
/// probe in its auto-free watcher. The watcher polls `probe.needsFree` on a
/// shared utility-queue timer and calls `engine.remove(self)` on the main
/// thread once the flag flips. Synths removed manually before the flag fires
/// are quietly dropped from the watcher.
///
/// Calling this twice replaces the previous probe. Pass a generator that the
/// synth's own DAG already retains (the engine does not strengthen the
/// reference) — losing the probe to ARC turns the auto-free into a no-op.
/// `nonisolated`: callable from `DoneActionWatchable` generator inits during `build()`.
public nonisolated final func autoFreeOnDone(_ probe: any DoneActionWatchable) {
_autoFreeProbe = probe
}
// MARK: - Main-thread parameter update
/// Write a parameter value by name from the main thread.
///
/// The key is the property name of an `@LiveParam` / `@UIParam` declared on the
/// synthesizer subclass (with the leading `_` of property-wrapper backing storage
/// stripped — `@LiveParam var freq` is registered under `"freq"`). Auto-registration
/// runs after `build()` returns; the synth must have been added to an engine for the
/// table to be populated.
///
/// The write is a releasing atomic store on the projected node. The RT audio thread
/// picks up the new value at the start of the next (sub-)block — never mid-block.
/// Direct typed writes (e.g. `synth.freq = 880.0`) are equivalent to and preferred
/// over this by-name path; `updateParameter` exists primarily for external integrations
/// that receive the parameter name as a String (OSC, MIDI handlers, REPL, presets).
///
/// - Parameters:
/// - key: The property name of the `@LiveParam` / `@UIParam`.
/// - value: New parameter value.
/// - Throws: `ParameterUpdateError.keyNotFound` if no live parameter exists for `key`.
public final func updateParameter(_ key: String, value: Double) throws {
guard let entry: any LiveParameterValue = parameterTable.inputs[key] as? LiveParameterValue else {
throw ParameterUpdateError.keyNotFound(key)
}
entry._writeAtomicValue(value)
}
// MARK: - Evaluate (RT thread)
/// Drives all registered output generators for one block segment.
///
/// Builds a `SynthGraph` by reference to `parameterTable`, then evaluates each
/// registered output generator. Parameter updates (atomic writes from the main
/// thread) are picked up by the projected nodes themselves at the start of each
/// (sub-)block — no synchronization is required here.
///
/// Called by the engine — do not call directly.
///
/// `nonisolated`: the RT render thread's entry point. Reads only `parameterTable` and
/// `outputGenerators` (both `nonisolated(unsafe)`), safe by the add-event barrier.
public nonisolated final func evaluate(graph: SynthGraph, count: Int) {
let localGraph: SynthGraph = SynthGraph(
engine: graph.engine,
busOffset: graph.busOffset,
parameterTable: parameterTable,
scratchBuses: graph._scratchBuses
)
for generator: any Generator in outputGenerators {
_ = generator.calculatedSamples(graph: localGraph, count: count)
}
}
// MARK: - Bus / Input-Output convenience helpers
/// Create an `Out` generator for the given audio bus and register it as an output.
///
/// `bus` takes a plain `Int` index or an ``AudioBus`` allocation (channel count enforced
/// automatically). A ``ControlBus`` traps — this writes the audio-bus pool; use
/// ``controlOutput(bus:source:)`` for a control bus.
///
/// ```swift
/// output(bus: 0, source: sig) // plain Int bus
/// output(bus: myAudioBus, source: sig) // clamped to myAudioBus.channelCount
/// ```
public final func output(bus: any ValidBus, source: any ValidGeneratorInput) {
// Out.Audio conforms to RootRegistering and self-registers during init —
// no explicit addOutputGenerator() call is needed here. The discarded
// return value lets Swift see the side effect via auto-registration.
let _: Out.Audio = Out.Audio(bus: bus, source: source)
}
/// Create independent `Out` generators for each bus in the given range and register them.
///
/// Each bus gets its own `Out` instance — instances are not shared, so each write is
/// an independent accumulation into its respective bus. All instances reference the same
/// `source`; the fan-out cache ensures `source` is evaluated only once per block.
public final func output(buses: Range<Int>, source: any ValidGeneratorInput) {
for bus: Range<Int>.Element in buses {
// Self-registers via RootRegistering — see `output(bus:source:)` above.
let _: Out.Audio = Out.Audio(bus: bus, source: source)
}
}
/// Create a `ReplaceOut.Audio` generator for the given bus and register it as
/// an output. **Overwrites** the bus content (wipes any prior writes in the
/// current block).
///
/// `bus` takes a plain `Int` index or an ``AudioBus`` allocation (writing clamped to
/// `bus.channelCount` channels; multi-channel sources overwrite consecutive buses from
/// `bus.index`). A ``ControlBus`` traps — this writes the audio-bus pool.
///
/// ```swift
/// // In-place amp scale on a 4-channel bus.
/// replaceOutput(bus: outBus, source: In.Audio(bus: outBus) * smoothAmp)
/// ```
///
/// - Important: ReplaceOut wipes prior writes to its target bus in the
/// current block. Position the synth in the node tree after any additive
/// writers whose contribution must reach the input. See ``ReplaceOut``
/// for full semantics including ParallelGroup interaction.
public final func replaceOutput(bus: any ValidBus, source: any ValidGeneratorInput) {
// Self-registers via RootRegistering — same pattern as `output(bus:source:)`.
let _: ReplaceOut.Audio = ReplaceOut.Audio(bus: bus, source: source)
}
/// Create a `Out.Control` generator for the given control bus and register it as an output.
///
/// `bus` takes a plain `Int` index or a ``ControlBus`` allocation (channel count enforced
/// automatically). An ``AudioBus`` traps — this writes the control-bus pool; use
/// ``output(bus:source:)`` for an audio bus.
///
/// ```swift
/// controlOutput(bus: 10, source: lfo) // plain Int bus
/// controlOutput(bus: myCtrlBus, source: lfo) // clamped to myCtrlBus.channelCount
/// ```
public final func controlOutput(bus: any ValidBus, source: any ValidGeneratorInput) {
// Self-registers via RootRegistering — see `output(bus:source:)` above.
let _: Out.Control = Out.Control(bus: bus, source: source)
}
/// Create and return an `In.Audio` generator for the given audio bus.
///
/// `bus` takes a plain `Int` index (single bus) or an ``AudioBus`` (reads
/// `bus.channelCount` consecutive buses). A ``ControlBus`` traps — this reads the audio-bus
/// pool; use ``controlInput(bus:)`` for a control bus.
///
/// ```swift
/// input(bus: 2) // single-channel In.Audio
/// input(bus: myAudioBus) // multi-channel In.Audio matching allocation
/// ```
public final func input(bus: any ValidBus) -> In.Audio {
In.Audio(bus: bus)
}
/// Create and return an `In.Control` generator for the given control bus.
///
/// `bus` takes a plain `Int` index (single bus) or a ``ControlBus`` (reads
/// `bus.channelCount` consecutive buses). An ``AudioBus`` traps — this reads the control-bus
/// pool; use ``input(bus:)`` for an audio bus.
///
/// ```swift
/// controlInput(bus: 10) // single-channel In.Control
/// controlInput(bus: myCtrlBus) // multi-channel In.Control matching allocation
/// ```
public final func controlInput(bus: any ValidBus) -> In.Control {
In.Control(bus: bus)
}
/// Create a `GeneratorArray` that reads `channels` consecutive audio buses starting at `bus`.
///
/// Mirrors `output(bus:source:)` — use when you need separate generator instances per channel.
/// Each element reads one bus independently. For a single multi-output generator, prefer
/// `input(bus:)` with an ``AudioBus``.
///
/// ```swift
/// output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
/// ```
public final func input(bus: Int, channels: Int) -> GeneratorArray {
In.Audio.multi(bus: bus, channels: channels)
}
// MARK: - Runtime source-swap
/// Projected-value source-swap helper for `@LiveParam` parameters.
///
/// Equivalent to:
/// ```swift
/// synth.$freq.source = source
/// ```
/// but usable in generic or programmatic contexts where iterating over a
/// collection of `ParameterNode` references, or passing the node as an argument,
/// is more convenient than direct projected-value access.
///
/// ## Shape selection
///
/// Swift's `open class` constraint means `KeyPath<Self, ParameterNode>` cannot be
/// expressed generically with a `where Root == Self` constraint — the compiler cannot
/// satisfy both `Root: SynthesizerBase` and `Root == Self` simultaneously for an
/// open-class method dispatch. Shape (a) from the original plan (KeyPath) therefore
/// falls back to the direct `ParameterNode` argument shape, which is strictly safer:
/// the caller passes `synth.$freq` directly, eliminating all key-path machinery and
/// any possible dispatch edge cases.
///
/// Call site:
/// ```swift
/// synth.setSource(synth.$freq, to: lfo)
/// // equivalent to:
/// synth.$freq.setSource(lfo)
/// // equivalent to:
/// synth.$freq.source = lfo
/// ```
///
/// - Parameters:
/// - node: The `ParameterNode` projected value of a `@LiveParam` property
/// (`synth.$freq`, `synth.$amp`, etc.).
/// - source: Generator to wire in as the new source, or `nil` to revert
/// to the scalar ramp path.
/// - crossfadeBlocks: Number of audio blocks for crossfade. `0` = hard swap
/// (default). Larger values produce a smooth linear mix from the old
/// slot's output to the new one over N blocks.
///
/// ## Threading
///
/// **Main thread only.** Delegates to `ParameterNode.setSource(_:crossfadeBlocks:)`,
/// which enqueues a `SourcePacket` onto the per-parameter SPSC queue. The audio
/// thread drains the queue at the start of each block.
public final func setSource(
_ node: ParameterNode,
to source: (any Generator)?,
crossfadeBlocks: UInt16 = 0
) {
node.setSource(source, crossfadeBlocks: crossfadeBlocks)
}
// MARK: - Internal
/// Clears `outputGenerators`, calls `build()`, then re-runs `@LiveParam` / `@UIParam`
/// auto-registration. Called by the engine when this Synthesizer is added to the node
/// tree, ensuring a clean DAG even if the same instance is re-added.
///
/// **Value survival across re-add.** `parameterTable.inputs` is repopulated by
/// `_autoRegisterLiveParams()` on every call, but each `@LiveParam` / `@UIParam` property
/// wrapper holds its projected node (`ParameterNode` / `UIParamNode`) as a `let` —
/// the same instance is re-registered, so its atomic value and ramp state are preserved
/// across `engine.remove` + `engine.add` cycles.
///
/// - Precondition: the Synthesizer must NOT currently be active in the node tree.
/// Calling this while `evaluate()` may be running on the RT thread is a data race on
/// `outputGenerators`. Always `engine.remove(synth)` before re-adding.
internal func rebuildGraph() {
outputGenerators.removeAll()
_SynthesizerBuildContext.$currentRef.withValue(_BuildingRef(synth: self)) {
build()
}
_autoRegisterLiveParams()
}
/// Walks `Mirror(reflecting: self)` (plus the superclass chain) to discover any
/// `@LiveParam` / `@UIParam` properties and register their projected values in
/// `parameterTable.inputs`. The property name (Swift's property-wrapper backing storage
/// `_freq`, with the single leading underscore stripped to `freq`) is used as the
/// parameter key.
///
/// **Inheritance.** Walks the most-derived mirror plus every `superclassMirror` in the
/// chain so inherited `@LiveParam` / `@UIParam` properties are also registered. Note:
/// Swift forbids re-declaring `@LiveParam var x` in a subclass when the parent already
/// has one — same-name shadowing is therefore unreachable in practice and not a concern
/// for this walk.
///
/// Called from `rebuildGraph()` on the main thread, before the synth is added to the
/// node tree. Reflection cost is per-instance per-add and is negligible for typical synth
/// sizes; voice-pool scenarios that stress add/remove may consider caching the result.
private func _autoRegisterLiveParams() {
var mirrors: [Mirror] = []
var current: Mirror? = Mirror(reflecting: self)
while let m: Mirror = current {
mirrors.append(m)
current = m.superclassMirror
}
for m: Mirror in mirrors.reversed() {
for child: Mirror.Child in m.children {
guard let label: String = child.label else { continue }
let key: String = label.hasPrefix("_") ? String(label.dropFirst()) : label
if let wrapper: any LiveParameterWrapper = child.value as? LiveParameterWrapper {
parameterTable.inputs[key] = wrapper._projectedAsValidInput
}
}
}
}
}
// MARK: - Build-context task-local (nonisolated namespace)
/// File-scope holder for the `build()`-context task-local.
///
/// The task-local cannot live as a static on `SynthesizerBase` because that class is
/// `@MainActor`: `@TaskLocal` would synthesise a main-actor-isolated
/// `$`-projected accessor, which the **nonisolated** generator-init read path
/// (`RootRegistering` / `DoneActionWatchable` self-registration) cannot reach. Hoisting it
/// into this plain `enum` keeps both the `withValue` writer (on main, inside `rebuildGraph`)
/// and the cross-init readers nonisolated.
internal enum _SynthesizerBuildContext {
@TaskLocal static var currentRef: SynthesizerBase._BuildingRef?
}