18 KiB
Synthesizer Protocol
The composable unit of instrument or effect in Lyrebird. Any type conforming to Synthesizer can be added to the signal graph tree.
Current Implementation State
Complete. The protocol, node tree, Group, and SynthesizerBase are fully implemented and tested (152 tests passing).
Protocol Definition
public protocol Synthesizer: AnyObject {
/// Configure the internal generator DAG. Called once on the scheduling thread.
func build()
/// Evaluate one segment of the signal graph. Called on the RT audio thread.
/// Default: no-op; SynthesizerBase provides the real one.
func evaluate(graph: SynthGraph, count: Int)
/// Begin a graceful release (e.g. set gate → 0).
/// Default throws `SynthesizerError.noGate`. Override in synthesizers with EnvelopeGen.
func release(engine: SynthesisEngine) throws
/// Immediately remove this node from the signal graph.
/// Default posts an engine remove event. Group overrides with full cascade teardown.
func free(engine: SynthesisEngine)
}
Default evaluate and free are provided by a protocol extension. Default release throws SynthesizerError.noGate — override it in synthesizers that have a gate input.
SynthesizerBase re-declares release(engine:) and free(engine:) as open members mirroring
those defaults. This is deliberate and load-bearing: a protocol-extension default binds
statically at the conformance, so without the class members a subclass's implementation would
be unreachable through an any Synthesizer — including Group.release's cascade to its
children, which would then see .noGate and hard-free every gated child. Subclass
SynthesizerBase and override. See ARCHITECTURE.md §9.1.
Synthesizer Lifecycle
release(engine:) — graceful shutdown
Signal the synthesizer to begin releasing (set gate → 0, trigger doneAction envelope, etc.). Synthesizers that don't support release throw SynthesizerError.noGate.
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 — no try, no string
}
}
let note = GatedNote()
try engine.add(note)
// Later — begin release:
try? note.release(engine: engine)
For string-key gate parameters:
override func release(engine: SynthesisEngine) throws {
try updateParameter("gate", value: 0.0)
}
free(engine:) — immediate removal
Removes the node from the signal graph at the current sample time, without waiting for an envelope to complete.
note.free(engine: engine)
SynthesizerError
public enum SynthesizerError: Error {
case noGate // thrown by default release(engine:) when no gate is supported
}
Catch .noGate to distinguish synthesizers that don't support release from ones that throw real errors:
do {
try synth.release(engine: engine)
} catch SynthesizerError.noGate {
synth.free(engine: engine) // no gate — free immediately
}
Group lifecycle cascade
Group provides cascade implementations of both lifecycle methods. See docs/protocols/node-tree.md — "Group Lifecycle" section.
SynthesizerBase
Most Synthesizer implementations should subclass SynthesizerBase rather than conforming to Synthesizer directly.
// Example — your synthesizer, defined by subclassing SynthesizerBase
final 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)
}
}
- Override
build()and calladdOutputGenerator(_:)with each root generator (typicallyOut.AudioorOut.Control). evaluate(graph:count:)isfinal— the engine drives it automatically.- Do not override
evaluatein subclasses; overridebuildinstead.
ClosureSynthesizer — a graph without a subclass
When all you want is to hear a generator graph — a scratchpad line, a demo, a
one-off voice, a test — ClosureSynthesizer supplies the graph from a closure
instead of a build() override:
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
The closure runs inside build() — once, on the main thread, at add time. Each
instance is its own graph, so construct the generators inside the closure
rather than handing it instances shared with another synthesizer (the same
graph-copy-per-instance rule as any SynthesizerBase). A multi-channel source
fans out across consecutive buses from bus, exactly like output(bus:source:).
There are no @LiveParam slots — reach for a named subclass once a voice needs
live-controllable parameters.
Debugging: per-instance debug tap
Canonical reference: the DocC article
<doc:Debugging>(Sources/Lyrebird/Lyrebird.docc/Debugging.md) covers this plus inspecting inner nodes and stepping a generator's compute loop. The summary below is a quick pointer.
evaluate(graph:count:) is final, so you cannot hook it directly. Instead override
debugTap(graph:count:outputs:) — an open no-op the engine calls once per scheduling
segment, after every output generator has run, but only when debugTapEnabled is set on
that instance. The tap's invocation is compiled out of release builds (the call site is
#if DEBUG); the method and flag still exist so an override compiles unconditionally, but
the hook never fires in release.
This is the canonical place to set a breakpoint on one specific voice.
final class FMTone: SynthesizerBase {
@LiveParam var carrierFreq: Double = 440.0
override func build() {
let mod: any Generator = OscSin.Audio(freq: 220.0) * 660.0
output(bus: 0, source: OscSin.Audio(freq: $carrierFreq + mod) * 0.18)
}
override func debugTap(
graph: SynthGraph,
count: Int,
outputs: [any Generator]
) {
// 👈 Breakpoint here. The RT thread halts with self, outputs, and graph
// in scope. In the debugger:
// po self.carrierFreq
// po outputs.first?._cachedResult // Out's samples this block
// po outputs.first?._result[0].prefix(8) // first 8 samples
let block: Int = count
_ = block
}
}
Enable it per instance — flip only the voice you want to inspect:
let voice: FMTone = FMTone()
#if DEBUG
voice.debugTapEnabled = true // main thread, before add — only this voice taps
#endif
try engine.add(voice)
In a poly pool, gate the flag so a single note breaks:
for note: Int in chord {
let v: FMTone = FMTone()
v.debugTapEnabled = (note == 60) // break only middle C
try engine.add(v)
}
What you get when it halts
| In scope | Holds |
|---|---|
self |
Every let / @LiveParam on the voice. |
outputs |
This instance's registered output-generator tree. Each generator's _cachedResult / _result = samples just computed for this block. |
graph.engine |
Sample rate, block size, bus pool — read a bus mid-render. |
count |
Samples in this scheduling segment (≤ 512; the engine splits a block at scheduled-event boundaries, so the tap can fire several times per audio block). |
Rules
- Runs on the RT render thread. A breakpoint is fine (it halts the thread and you look).
Any code in the override obeys the RT rules — no allocation, locks,
print, orString. - Fires per scheduling segment — hundreds of hits/sec while audio runs. Use a conditional
breakpoint (
count == 512) or an override-local frame counter to break every Nth. - Want continuous inspection without halting? Snapshot into a pre-allocated ring in the tap
and drain it on the main thread instead — see
NodeTreeMirrorfor the pattern.
Adding to the Engine
let note1 = SineTone()
let note2 = SineTone() // 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:
- Calls
rebuildGraph()(clears then callsbuild()) onSynthesizerBaseinstances, orbuild()on plainSynthesizerconformers — on the main thread. - Pre-allocates the linked-list
PreparedNode— on the main thread.
The RT audio thread in applyEvent only wires pointer references into Group.addToTail — no allocation occurs on the RT thread.
Removing from the Engine
engine.remove(note1)
engine.remove(note2, at: someTime) // sample-accurate removal
Removed instances are handed off to freeQueue for ARC deallocation on the background drain thread — never on the RT audio thread.
Node Tree
SynthesisEngine
└── rootGroup (Group)
├── Group (optional nesting)
│ ├── Synthesizer ← evaluated first
│ └── Synthesizer
└── Synthesizer ← evaluated last
Groupis itself aSynthesizer— groups can be nested arbitrarily.- Children are evaluated in insertion order (tail-append by default).
- Evaluation order controls bus routing: if A writes to bus 2 and B reads from bus 2, A must precede B in the tree.
Group.addToTail/addToHead/removeareinternal— useengine.add(_:)andengine.remove(_:)from user code.
@LiveParam and @UIParam — Live Parameters
@LiveParam (in Lyrebird) and @UIParam (in LyrebirdUI) are the only live-parameter
mechanisms. Both auto-register at build() time via Mirror reflection — no
declareParameter call is required.
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: osc * $amp)
}
}
let tone = SineTone()
try engine.add(tone)
tone.freq = 880.0 // typed direct write
try? tone.updateParameter("freq", value: 880.0) // by-name (e.g. from OSC)
How it works
| Thread | Operation |
|---|---|
| Main thread | tone.freq = 880.0 → releasing Atomic<UInt64> store |
| RT thread | _computeSamples → acquiring load → linear ramp from previous to new target |
The projected value $freq is a ParameterNode — a ControlGenerator. When wired into
OscSin.Audio(freq: $freq), OscSin detects it as a Generator and calls calculatedSamples,
producing a linearly-interpolated audio-rate buffer ramping to the new value. The ramp is
sized to the engine's control block: one ramp per audio block when controlBlockSize == blockSize (default), or K ramps per audio block when controlBlockSize < blockSize.
Changing a @LiveParam from a Routine / Task
@LiveParam values can be driven from a LyrebirdRoutine / LyrebirdTask body — algorithmic,
sequential, timed control code that runs on a background thread. The ParameterNode's value
setter is a releasing atomic store, so a routine/task-body write is safe (a single control-side
producer alongside the RT thread's acquiring load) — the same store as the main-thread setter.
Two facts shape how you access the parameter:
- The synth is
@MainActor-isolated, sotone.freqandtone.$freqcan't be reached from the@Sendablebody (that's a main-actor access from a background thread). - The projected node
$freqis aParameterNode, which isSendable.
So capture the projected node on the main actor at setup, then drive it from the body with
ctx.set / ctx.ramp (see docs/tooling/routine-task.md § Live parameters):
let tone = SineTone() // @MainActor setup
let freq = tone.$freq // ParameterNode — Sendable, captured once
LyrebirdTask.run(engine: engine) { ctx in // @Sendable body — background thread
ctx.add(tone)
try ctx.wait(beats: 1)
ctx.set(freq, to: 660) // step
try ctx.ramp(freq, to: 220, beats: 2) // glide, blocks for the duration
ctx.remove(tone)
}
ctx.set / ctx.ramp take a ParameterNode only — @UIParam's UIParamNode is @Observable
and main-thread-only, so it is not a valid target from a background body; update @UIParam from the
main thread.
No-capture alternative: a synth driven mostly from routines can declare the node directly as
nonisolated let freq = ParameterNode(440)instead of@LiveParam— reachable from the body with no capture line (ctx.set(tone.freq, to: 660)), trading the plain-Doublevalue sugar and the$-projection.
Auto-registration via Mirror
SynthesizerBase.rebuildGraph() walks Mirror(reflecting: self) plus the superclass chain
at the end of build(), finding any @LiveParam / @UIParam properties (via the internal
LiveParameterWrapper protocol). The property name with the leading _ of property-wrapper
backing storage stripped becomes the parameter key.
Fan-out safety
ParameterNode has the standard segment-serial fan-out cache. Wiring $freq into multiple
downstream generators is safe — _computeSamples runs exactly once per segment regardless of
fan-out count.
updateParameter (by-name path)
updateParameter is the by-name route. Use it for external integrations that arrive as
String (OSC, MIDI, REPL, JSON presets):
try tone.updateParameter("freq", value: 880.0) // throws on unknown key
try? tone.updateParameter("freq", value: 880.0) // silent ignore for fire-and-forget
Throws ParameterUpdateError.keyNotFound(key) if no live parameter exists for key. The
write is the same atomic store as the typed setter — both are equivalent.
@UIParam
@UIParam is @LiveParam plus an @Observable value for SwiftUI binding. The projected
node (UIParamNode) delegates RT work to an internal ParameterNode, so audio-rate
delivery is identical. Use @UIParam whenever SwiftUI controls bind to the parameter — see
docs/ui/gui-system.md.
Runtime source-swap
Beyond scalar writes, any @LiveParam (or @UIParam) slot supports replacing the wired
generator at runtime without stopping the synthesizer.
// Assign an LFO as the source for freq — takes effect at the next audio block boundary:
tone.$freq.source = LFSawtooth.Control(freq: 0.5, mul: 100, add: 440)
// Revert to scalar (the last value written via `tone.freq = ...`):
tone.$freq.source = nil
// Soft crossfade over 4 blocks (~23 ms at 44.1 kHz / 256-sample block):
tone.$freq.setSource(newLFO, crossfadeBlocks: 4)
// Equivalent SynthesizerBase convenience helper:
tone.setSource(tone.$freq, to: newLFO)
The two public API surfaces are:
ParameterNode.source— get/set property on the projected value (synth.$freq). Reading returns the last value assigned on the main thread (eventually consistent with the audio thread within one block). The setter performs a hard swap (no crossfade).SynthesizerBase.setSource(_:to:crossfadeBlocks:)— convenience wrapper taking theParameterNodedirectly; useful in generic or programmatic contexts.
Crossfade semantics: crossfadeBlocks = 0 (default) = hard swap at the next block boundary.
A value > 0 linearly blends old and new source outputs over that many blocks. A mid-crossfade
swap kills the in-progress old source immediately and starts a fresh crossfade.
For the complete contract — threading rules, queue limits, and the known limitation on
updating a source generator's own parameters — see Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md
(the DocC-rendered material under "Live source-swap").
Subclass parameters
Subclasses can declare additional @LiveParam / @UIParam properties — both subclass and
inherited parameters are registered. Note: Swift forbids re-declaring @LiveParam var x in
a subclass when the parent already has one (would require override on a property-wrapper
backing store, which is unsupported), so subclass parameters must use distinct names.
Auto-Free
When EnvelopeGen.Audio or EnvelopeGen.Control signals completion with doneAction: .freeNode, it sets needsFree = true
(an Atomic<Bool> releasing store on the RT thread). The caller must read this flag from a
non-RT context (main thread or scheduling loop) after processBlock returns and post a .remove
event to the pending queue:
// After engine.processBlock — on main/scheduling thread:
if envelopeGen.needsFree {
engine.remove(synth)
}
Do not call engine.remove from within the RT callback — that would post to pendingQueue from
the RT thread, which violates the no-queue-posts-from-RT rule. The removed instance is routed
through freeQueue for off-RT deallocation.
Polyphonic Voice Pools
VoicePool<S: SynthesizerBase> manages N pre-allocated synthesizer instances as polyphonic voices. All logic is language-side — no RT changes.
Setup
let group = Group()
try engine.add(group)
let pool = try VoicePool(
voiceCount: 8,
group: group,
engine: engine,
stealStrategy: .oldest
) {
let s = MySynth()
s.gate = 0.0
return s
}
VoicePoolError.invalidVoiceCount is thrown when voiceCount < 1.
Note-on / note-off
let voice = pool.noteOn(note: 60) // allocates or steals; returns S
voice.freq = midiToHz(60)
voice.gate = 1.0
voice.gate = 0.0
pool.noteOff(note: 60) // marks voice free; pool does not gate it down
pool.allNotesOff() // marks all voices free
Steal strategies
| Case | Behavior |
|---|---|
.oldest |
Steals the voice playing longest (min trigger serial). Default. |
.roundRobin |
Cycles through voices in index order. |
.quietest |
Reads @LiveParam named "amplitude", "amp", or "gain" via Mirror; steals the lowest. Falls back to .oldest when no amp param found. |
.lowestAmplitude |
Alias for .quietest. |
All pool methods are main-thread only.
Legacy Reference
These files are in legacy/Lyrebird/LyrebirdSynth/Lyrebird/ — the legacy prototype. They are not in the current codebase; they are design references only.
LyrebirdNode.swift— Group, linked list, head/tailLyrebirdGraph.swift— build closure, parameter dict, graph copyAudioSampleGraphs.swift— example Synthesizer definitions