Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/SynthesizerProtocol.md
T

9.9 KiB

Synthesizer Protocol

@Metadata { @PageKind(article) }

The composable unit of instrument or effect in Lyrebird.

Protocol Definition

Synthesizer is four requirements, split along the thread boundary — build / release / free are the language side, evaluate is the RT side:

Requirement Isolation Contract
Synthesizer/build() @MainActor Configure the generator DAG. Called once, when the synth is added. Allocate every generator here — never during evaluate.
Synthesizer/evaluate(graph:count:) nonisolated Evaluate one block segment. The RT render thread's only entry point into a Synthesizer; must not hop actors. Called once per segment — more than once per block when a scheduled event splits it. Default is a no-op; SynthesizerBase provides the real one.
Synthesizer/release(engine:) @MainActor Begin a graceful release (typically post gate = 0). Default throws SynthesizerError/noGate — override it in any synthesizer with a gate input.
Synthesizer/free(engine:) @MainActor Immediate removal. Posts a remove event at the current sample time; the synth stops evaluating once the RT thread applies it.

The isolation split is the load-bearing part: see ARCHITECTURE.md §9.1. Language-side requirements must never be called from the RT audio thread.

SynthesizerBase declares release(engine:) and free(engine:) as open members mirroring the protocol defaults, so a subclass override dispatches correctly when a caller holds an any Synthesizer — which is how Group reaches its children. Subclass SynthesizerBase and override; do not rely on the protocol extension default to pick up your implementation.

Synthesizer Lifecycle

Override release(engine:) in any synthesizer that has an envelope gate:

final class GatedNote: SynthesizerBase {
    @LiveParam var gate: Double = 1.0

    override func build() { /* gate drives EnvelopeGen … */ }

    override func release(engine: SynthesisEngine) throws {
        gate = 0.0   // atomic write; envelope begins release phase
    }
}

Call free(engine:) for an immediate hard kill:

let note: MySynth = MySynth()
try engine.add(note)

note.free(engine: engine)   // removed on next block boundary

Group provides a cascade implementation of both: group.release(engine:) calls release on all children (freeing those that throw .noGate), then self-frees when the group empties. group.free(engine:) tears down all children immediately. See the Node Tree article for full semantics.

SynthesizerBase

Most Synthesizer implementations should subclass SynthesizerBase rather than conforming to Synthesizer directly.

// Example — your synthesizer, defined by subclassing SynthesizerBase
class SineTone: SynthesizerBase {
    override func build() {
        let osc = OscSin.Audio(freq: 440.0, phase: 0.0)
        output(bus: 0, source: osc * 0.5)
    }
}
  • Override build() and call output(bus:source:) or addOutputGenerator(_:) with root generators.
  • evaluate(graph:count:) is final — the engine drives it automatically.
  • Do not override evaluate in subclasses; override build instead.

Tip: To inspect a specific instance's output and inner state on the RT thread — or to set a breakpoint on one voice out of a pool — override SynthesizerBase/debugTap(graph:count:outputs:). See doc:Debugging.

Parameters

Declare live parameters as @LiveParam (or @UIParam for SwiftUI binding) properties on your SynthesizerBase subclass. Wire the projected value ($name) directly into your generator inputs:

final class SineTone: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var amp:  Double = 0.5

    override func build() {
        let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
        output(bus: 0, source: osc * $amp)
    }
}

// Update from the main thread. Both routes write the same atomic.
let note: SineTone = SineTone()
note.freq = 880.0                                  // typed direct write
try? note.updateParameter("freq", value: 880.0)    // by-name (e.g. OSC handler)

@LiveParam / @UIParam properties are auto-registered via Mirror reflection at the end of build(). The property name (with the leading _ of property-wrapper backing storage stripped) becomes the parameter key.

The RT audio thread picks up the new value at the start of the next (sub-)block — never mid-block.

updateParameter throws ParameterUpdateError.keyNotFound if no live parameter exists for the supplied key.

Or drive a @LiveParam from a LyrebirdRoutine / LyrebirdTask body — timed, sequential control code on a background thread. The synth is @MainActor, so capture the projected node ($freq, a Sendable ParameterNode) on the main actor, then use ctx.set / ctx.ramp:

final class SineTone: SynthesizerBase {
    @LiveParam var freq: Double = 440.0

    override func build() {
        output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
    }
}

let note: SineTone = SineTone()
let freq: ParameterNode = note.$freq          // captured on the main actor

LyrebirdTask.run(engine: engine) { ctx in
    ctx.add(note)
    ctx.set(freq, to: 660)                     // step
    try ctx.ramp(freq, to: 220, beats: 2)      // timed glide
}

ctx.set / ctx.ramp take a ParameterNode only — @UIParam's UIParamNode is @Observable and main-thread-only. See doc:RoutineTask § Live parameters.

For the full decision matrix (when to use @LiveParam vs direct generator wiring vs SendTrigger vs envelope/buffer swap), see doc:ParameterInputs.

Convenience Helpers (SynthesizerBase)

These are all called from inside build():

let signal: OscSin.Audio = OscSin.Audio(freq: 440.0)
let lfo: OscSin.Control = OscSin.Control(freq: 2.0)

// Audio output
output(bus: 0, source: signal)               // one bus
output(buses: 0..<2, source: signal)         // same source to multiple buses (fan-out cached)

// Control output
controlOutput(bus: 5, source: lfo)

// Audio input (returns In.Audio generator)
let sig: In.Audio = input(bus: 2)

// Control input (returns In.Control generator, interpolated)
let ctrl: In.Control = controlInput(bus: 10)

// Multi-channel audio input (returns GeneratorArray)
let stereo: GeneratorArray = input(bus: 2, channels: 2)

Adding to the Engine

let note1: MySynth = MySynth()
let note2: MySynth = MySynth()  // independent instance — own phase, own envelope
try engine.add(note1)
try engine.add(note2)

engine.add(_:) posts an .add event to the pending queue. Before enqueueing, the engine:

  1. Calls rebuildGraph() (clears, then calls build()) on SynthesizerBase instances on the main thread.
  2. Pre-allocates the linked-list PreparedNode on the main thread.

The RT audio thread in applyEvent only wires pointer references — no allocation on the RT thread.

Removing from the Engine

let note1: MySynth = MySynth()
let note2: MySynth = MySynth()
try engine.add(note1)
try engine.add(note2)

let someTime: SampleTime = engine.currentTime + engine.seconds(2.0)

engine.remove(note1)
engine.remove(note2, at: someTime)  // sample-accurate removal

Removed instances are handed to freeQueue for ARC deallocation on a background drain thread — never on the RT audio thread.

Auto-Free

Any DoneActionWatchable generator (EnvelopeGen/Audio / EnvelopeGen/Control, Line/Control, ExponentialLine/Control, PlayBuffer/Audio / PlayBuffer/Control, RecordBuffer/Audio / RecordBuffer/Control, DiskIn/Audio, SpectralPlayBuffer) constructed inside SynthesizerBase/build() with doneAction: .freeNode self-registers with the synth's auto-free watcher — no explicit call needed:

final class PluckedNote: SynthesizerBase {
    override func build() {
        let myEnv: Envelope = Envelope(
            levels: [0, 1, 0],
            durations: [0.01, 0.3],
            curves: [.sine, .exponential]
        )
        let someSignal: OscSin.Audio = OscSin.Audio(freq: 440.0)
        let env: EnvelopeGen.Control = EnvelopeGen.Control(
            envelope: myEnv,
            timeScale: 8.0,
            doneAction: .freeNode      // self-registers
        )
        output(bus: 0, source: someSignal * env)
    }
}

When the envelope completes, it sets needsFree = true (an Atomic<Bool> releasing store on the RT thread); a background utility-queue watcher polls the flag and calls engine.remove(synth) on the main thread.

For probes constructed outside build(), or for custom DoneActionWatchable conformers, register explicitly:

let myProbe: EnvelopeGen.Control = EnvelopeGen.Control(
    envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [.sine, .exponential]),
    doneAction: .freeNode
)
autoFreeOnDone(myProbe)

Polling needsFree manually is still supported but rarely needed.

Do not call engine.remove from within the RT callback.

Thread-Safety Model

  • parameterTable.inputs is populated by _autoRegisterLiveParams() at the end of rebuildGraph() (main thread, before add) and read during evaluate() (RT thread, after add). No concurrent access.
  • updateParameter issues a releasing atomic store on the projected ParameterNode / UIParamNode; the RT thread picks up the new value via an acquiring atomic load at the start of the next (sub-)block — no queue, no dictionary mutation on the RT thread.
  • Double-add is an error, not undefined behaviour: adding the same instance while it is still active in the tree throws EngineAddError/doubleAdd(engine:); adding an instance already bound to a different engine throws EngineAddError/boundToOtherEngine(current:prior:). Both are backed by a single-shot atomic CAS. To re-add an instance, engine.remove(synth) and allow at least one processBlock to complete first.