Files
Lyrebird/docs/protocols/synthesizer.md
T
2026-06-01 18:27:40 -07:00

342 lines
12 KiB
Markdown

# 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
```swift
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.
---
## 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`.
```swift
final class GatedNote: SynthesizerBase {
@LiveParam var gate: LyrebirdFloat = 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:
```swift
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.
```swift
note.free(engine: engine)
```
### SynthesizerError
```swift
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:
```swift
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.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.5
override func build() {
let osc = OscSin.Audio(freq: $freq, phase: 0.0)
output(bus: 0, source: osc * $amp)
}
}
```
- Override `build()` and call `addOutputGenerator(_:)` with each root generator (typically `Out.Audio` or `Out.Control`).
- `evaluate(graph:count:)` is `final` — the engine drives it automatically.
- Do not override `evaluate` in subclasses; override `build` instead.
## Adding to the Engine
```swift
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:
1. Calls `rebuildGraph()` (clears then calls `build()`) on `SynthesizerBase` instances, or `build()` on plain `Synthesizer` conformers — 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 into `Group.addToTail` — no allocation occurs on the RT thread.
## Removing from the Engine
```swift
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
```
- `Group` is itself a `Synthesizer` — 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` / `remove` are `internal` — use `engine.add(_:)` and `engine.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.
```swift
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`.
### 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):
```swift
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.
```swift
// 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 the
`ParameterNode` directly; 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:
```swift
// 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
```swift
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
```swift
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/tail
- `LyrebirdGraph.swift` — build closure, parameter dict, graph copy
- `AudioSampleGraphs.swift` — example Synthesizer definitions