// 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` 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 = Atomic(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.., source: any ValidGeneratorInput) { for bus: Range.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` 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? }