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

1381 lines
72 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Writing Generators
A step-by-step guide to implementing correct, RT-safe generators in Lyrebird.
Every built-in generator in `Sources/Lyrebird/Generators/` follows the patterns here.
---
## 1. Protocol Choice — `AudioGenerator` vs `ControlGenerator`
| Criterion | Use `AudioGenerator` | Use `ControlGenerator` |
|-----------|---------------------|------------------------|
| Output resolution | One value per sample | One value per control sub-block (`controlBlockSize` samples); framework assembles to full audio-rate output |
| Typical use | Oscillators, filters, noise, delay | LFOs, parameter smoothing, envelope targets |
| `rate` property | `.audio` | `.control` |
| `_computeSamples` | **You implement** the full per-sample loop | **Must override** in all production generators — the default allocates on every call and is not RT-safe; see §2 |
Both conform to `Generator`, which conforms to `ValidGeneratorInput`. Either can be wired as an input to any other generator.
### When to implement both Audio and Control variants
| Generator role | Pattern | Reason |
|---|---|---|
| Signal **source** (oscillator, noise, bus reader) | Audio + Control | Block-rate variant saves CPU for LFO use; phase/state has meaningful block-rate semantics |
| Signal **processor** (filter, delay, effect) | Audio only | Operates sample-by-sample on a signal — "block-rate filter" is undefined; its *parameters* already accept any rate via `ValidGeneratorInput` |
| Structural wrapper (Pan2, GeneratorArray, bus I/O) | Depends | Bus I/O has a genuine audio/control bus distinction; structural wrappers rarely need both |
**The key test:** does computing one value per block instead of one per sample make physical sense for this generator's role?
- `OscSin.Control` — yes. Phase advances at block rate; useful as an LFO.
- `WhiteNoise.Control` — yes. One random value per block, smoothed by the ramp.
- A hypothetical `FirstOrderSection.Control` — **no**. The filter IS the sample-by-sample processor. Its cutoff frequency *input* can be a `ControlGenerator`, but the filter itself must run at audio rate.
### ControlGenerator output feeds AudioGenerator input transparently
`ControlGenerator._computeSamples` is called once per control sub-block (`controlBlockSize` samples). Each call produces a linear ramp from `previousOutputValue` to the new sub-block target. The `ControlGenerator.calculatedSamples` protocol extension assembles all sub-block calls into the full audio-rate output using `_subBlockBuffer`, then caches the result. Any `AudioGenerator` that calls `calculatedSamples` on a `ControlGenerator` input receives a smoothly interpolated full block — no special handling needed.
At `SynthesisEngine`'s default `controlBlockSize` of 64, a 512-sample block executes `_computeSamples` 8 times. At `controlBlockSize = blockSize`, the old behaviour is preserved (one call, one ramp).
```swift
// WhiteNoise.Control produces one random value per control sub-block,
// smoothed into piecewise ramps that fill the full audio-rate block.
// FirstOrderSection receives that block sample-by-sample — no adaptation needed.
let noise = WhiteNoise.Control()
let filter = FirstOrderSection(input: OscSin.Audio(freq: 440.0),
a0: noise * 0.05 + 0.1, a1: 0.0, b1: 0.9)
```
### The enum namespace pattern for paired generators
Built-in generators that have both rates use `enum Namespace { class _Base; final class Audio; final class Control }`:
```swift
public enum OscSin {
public class _Base { /* shared fields + init */ }
public final class Audio: _Base, AudioGenerator { /* per-sample loop */ }
public final class Control: _Base, ControlGenerator { /* block-rate ramp */ }
}
```
Follow this structure for any new generator pair. `_Base` holds all shared stored properties (`_freqInput`, `_phase`, `_result`, `_subBlockBuffer`, etc.) and the shared init. Both rate variants subclass `_Base` and implement their own `_computeSamples` and `floatValue`. Placing `_subBlockBuffer` in `_Base` adds no overhead to `Audio` instances — `GeneratorBase._subBlockBuffer` initialises to `[[]]` (no inner allocation). Only `Control` conformers that call `_setupSubBlockBuffer()` in their designated `init` allocate the 512-sample assembly buffer.
After the closing `}` of the enum, add a `GeneratorEnum` conformance extension so the pair is discoverable at compile time and in DocC:
```swift
extension OscSin: GeneratorEnum {
public typealias AudioType = OscSin.Audio
public typealias ControlType = OscSin.Control
}
```
This is a two-line requirement for every new generator namespace enum — zero runtime cost.
```swift
// Audio-rate oscillator — inherit GeneratorBase for _segmentSerial, _cachedResult, _subBlockBuffer
final class MyOsc: GeneratorBase, AudioGenerator {
// No manual _segmentSerial / _cachedResult needed — provided by GeneratorBase
// ...
}
// Control-rate LFO (block-rate target per sub-block, assembled to audio rate by the framework)
final class MyLFO: GeneratorBase, ControlGenerator {
var previousOutputValue: Double = 0.0
// _subBlockBuffer inherited from GeneratorBase (single-channel). Multi-channel generators
// must resize _subBlockBuffer to match channel count in init.
// ...
}
```
> **Important:** The default `ControlGenerator._computeSamples` allocates on every call and is not RT-safe for production use. All built-in control generators override it with a pre-allocated buffer. See §2.
---
## 2. Buffer Pre-allocation
`GeneratorBase` owns `_result` and pre-allocates it in its designated initializer
(`init(channels: Int = 1)`). Mono generators inherit a single zero-filled channel of
`lyrebirdDefaultResultBufferSize` (512) samples — **no `_result` declaration or assignment
needed in the subclass**. Open `_computeSamples` with `_checkCount(count)`, the inherited
helper that traps if the engine is somehow misconfigured.
```swift
final class MyGen: GeneratorBase, AudioGenerator {
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// ... fill _result[0][0..<count] ...
return _result
}
}
```
`floatValue` is provided by the `AudioGenerator` protocol extension — no override needed
unless you want different scalar semantics (e.g. `ConstantGeneratorInput` returns its stored
value directly).
`SynthesisEngine.init` enforces `blockSize ≤ lyrebirdDefaultResultBufferSize` via its own
`precondition`, so the guard in `_checkCount` is only ever reached during misconfiguration
or tests.
**Multi-channel generators** pass `channels: N` to `super.init` and **must override
`outputChannelCount`**:
```swift
public override var outputChannelCount: Int { 4 } // or a fixed `let _channels`
init(...) {
// ... set subclass stored properties ...
super.init(channels: 4)
}
```
For dynamic channel counts (e.g. `BinaryOpGenerator`, `GeneratorArray`), compute the count
in `init` and pass it to `super.init(channels: outChannels)`. The base allocates `_result`
with the requested row count in one shot. The buffer factory `makeResultBuffer(channels: N)`
(in `ResultBuffer.swift`) is available if a subclass needs a separately-owned buffer.
`Generator.outputChannelCount` is read by `BinaryOpGenerator` (the `+ - * /` operator backbone)
to decide how to broadcast across operand pairs:
| lhs × rhs | Output | Behaviour |
|-----------|--------|-----------|
| `1 × N`, `N × 1` | N-row | Mono operand broadcasts to every channel. |
| `N × N` | N-row | Element-wise. |
| `N × M` (both > 1, N ≠ M) | — | `precondition` traps at `init`. |
`GeneratorBase` provides a default `outputChannelCount` of `1`. If your generator's `_result`
has more than one row and you don't override, `pan2 * 0.5` (and similar arithmetic on your
generator) will silently drop channels 1..N-1.
```swift
// Multi-channel BinaryOpGenerator just works once outputChannelCount is overridden:
let pan = Pan2(input: osc, pan: -0.3)
output(bus: 0, source: pan * 0.5) // both channels × 0.5
output(bus: 0, source: dry + pan) // mono dry broadcasts to stereo
output(bus: 0, source: dry2ch * 0.7 + wet2ch * 0.3) // element-wise stereo mix
```
> **Note** — the `mul:` and `add:` parameters on every Generator (`OscSin.Audio(..., mul: x)`,
> etc.) follow the same broadcast policy as `BinaryOpGenerator`: mono `mul`/`add` broadcasts
> to every output channel; matched-channel-count `mul`/`add` applies per-channel; mismatched
> multi-row inputs trap via `precondition` at the apply site.
**`ControlGenerator` pre-allocation** — the default `ControlGenerator._computeSamples` allocates on every call and must not be used in production. Override it and write the interpolated ramp into the inherited `_result`. `ControlGenerator` conformers also must call `_setupSubBlockBuffer()` from `init` to allocate `_subBlockBuffer`, and must provide their own `floatValue` returning the block target (the `AudioGenerator` default impl does not apply).
```swift
final class MyLFO: GeneratorBase, ControlGenerator {
var previousOutputValue: Double = 0.0
private let rateInput: any ValidGeneratorInput
init(rate: any ValidGeneratorInput = 1.0) {
self.rateInput = rate
super.init()
_setupSubBlockBuffer()
}
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let target = floatValue(graph: graph) // your computed block target
let prev = previousOutputValue
let step = (target - prev) / Double(count)
for i in 0..<count {
_result[0][i] = prev + step * Double(i + 1)
}
previousOutputValue = target
return _result
}
func floatValue(graph: SynthGraph) -> Double {
// Compute and return the block target (block-rate value only, no loop)
rateInput.floatValue(graph: graph)
}
}
```
`_computeSamples` and `floatValue` have different roles here: `floatValue` computes the block-rate target; `_computeSamples` builds the interpolated audio-rate ramp. Do not call `calculatedSamples` from `floatValue` on a `ControlGenerator` — the ramp is the output of `_computeSamples`, not an input to it.
---
## 3. State Variables
Declare all DSP state as stored properties and initialize them fully in `init`. No lazy initialization on the RT thread.
```swift
final class MyFilter: GeneratorBase, AudioGenerator {
// Inputs (already-resolved values stored here — see § 3.1)
private let freqInput: any ValidGeneratorInput
private let qInput: any ValidGeneratorInput
private let freqIsGenerator: Bool
private let qIsGenerator: Bool
// DSP state — fully initialized at construction
private var x1: Double = 0.0 // previous input sample
private var y1: Double = 0.0 // previous output sample
init(freq: any ValidGeneratorInput, q: any ValidGeneratorInput) {
// Resolve every `any ValidGeneratorInput` slot before storing —
// see § 3.1.
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
let resolvedQ: any ValidGeneratorInput = q._resolvedInput()
freqInput = resolvedFreq
qInput = resolvedQ
freqIsGenerator = resolvedFreq is any Generator
qIsGenerator = resolvedQ is any Generator
super.init() // mono _result allocated by GeneratorBase
}
}
```
### 3.1 Resolving `any ValidGeneratorInput` slots at init
Every Generator `init` parameter typed `any ValidGeneratorInput` MUST be passed through `_resolvedInput()` before it is stored or type-classified via `is any Generator`. The resolution step is non-RT (runs in `init`), zero RT overhead, and idempotent for non-provider inputs.
`_resolvedInput()` is a protocol requirement on `ValidGeneratorInput` with a default implementation returning `self`. Scalars (`Double`, `Int`), `Generator` instances, and `Closure` pass through unchanged. Only `GeneratorInputProvider` overrides — its impl calls the stored `make` closure to produce a fresh `any ValidGeneratorInput`. The provider's own `calculatedSamples` / `floatValue` / `intValue` / `needsInterpolation` / `sampleBlock` accessor implementations are `preconditionFailure` traps — they are unreachable in correct code, and fire if a provider survives to the render path without being resolved. Missing resolution = guaranteed crash at the first audio block, not silent wrong audio.
**Canonical pattern — resolve at the TOP of every Generator `init`:**
```swift
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
q: any ValidGeneratorInput = 0.707,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
let resolvedQ: any ValidGeneratorInput = q._resolvedInput()
_input = resolvedInput
_freq = resolvedFreq
_q = resolvedQ
_inputIsGenerator = resolvedInput is any Generator
_freqIsGenerator = resolvedFreq is any Generator
_qIsGenerator = resolvedQ is any Generator
_mulAdd = MulAddSpec(mul: mul, add: add) // mul / add resolved INSIDE MulAddSpec — do NOT pre-resolve
super.init()
}
```
**Helper-boundary policy — do NOT pre-resolve params that flow through a helper that already resolves.** The following helper init paths resolve their slots internally; passing already-resolved values is idempotent but wasteful and obscures intent. Pass the raw caller-supplied value through:
| Helper | Slots it resolves |
|---|---|
| `MulAddSpec(mul:add:)` | `mul` / `add` |
| `OscillatorBase.init(freq:phase:mul:add:)` | `freq` (plus mul/add via MulAddSpec) |
| `LFNoiseBase.init(freq:initialRngState:mul:add:)` | `freq` (plus mul/add via NoiseBase → MulAddSpec) |
| `NoiseBase.init(initialRngState:mul:add:)` | `mul` / `add` via MulAddSpec |
| `DynamicsBase.init(in:threshold:ratio:attack:release:kneeWidth:)` | all 6 slots |
A Generator inheriting `OscillatorBase` and exposing no additional `any ValidGeneratorInput` slots needs no resolution in its own designated init — `super.init` handles it. A Generator inheriting `OscillatorBase` and adding (say) a `dutyCycle: any ValidGeneratorInput` slot resolves only `dutyCycle` itself; `freq` / `mul` / `add` route through `super.init`.
**Classify on the resolved value, not the raw param.** `is any Generator` run against the unresolved param would mis-classify a `GeneratorInputProvider` (which conforms to `ValidGeneratorInput` but is not a `Generator`) as a non-generator scalar, AND the stored value would still be the unresolved provider — guaranteed render-path trap. Always classify against the `let resolvedX:` local.
**Why this design.** The contract lets `GeneratorInputProvider` be a transparent input source — callers pass a provider anywhere `any ValidGeneratorInput` is accepted, with no `.make()` call at the call site. The provider unwraps once at Generator init time (non-RT) and the Generator stores a normal `ValidGeneratorInput` from then on. RT-path code is unchanged; this is an init-time-only contract.
Full end-to-end pipeline (Process factory → Synthesizer → Generator) lives in `Sources/Lyrebird/Lyrebird.docc/GeneratorInputProvider.md`.
---
## 4. Reading Inputs
Choose the consumption pattern that matches the input's update rate.
### Pattern 1 — Scalar (block-rate)
```swift
let freq = freqInput.floatValue(graph: graph)
```
Use when the parameter changes at most once per block and audio-rate accuracy is not required. Appropriate for filter cutoff, LFO rate, and similar slowly-varying parameters.
### Pattern 2 — Block-interpolated ramp
```swift
let freqBlock = freqInput.sampleBlock(graph: graph, count: count,
previousValue: previousFreq)
```
Use when the source is a `ControlGenerator` (e.g. `ParameterNode` from `@LiveParam`, `UIParamNode` from `@UIParam`, an LFO). `sampleBlock` is a single-channel convenience wrapper over `calculatedSamples`. The `previousValue` parameter is part of the protocol signature but is **ignored by every conforming type** in the current implementation — `Generator`, `Double`, `Int`, and `Closure` all discard it. For `ControlGenerator` inputs, the interpolated ramp is produced internally by `ControlGenerator._computeSamples`, which tracks `previousOutputValue` across blocks automatically. The result is a smooth ramp within the block that prevents clicks on parameter changes.
### Pattern 3 — Audio-rate block (per-sample accuracy)
```swift
let modSamples = modInput.calculatedSamples(graph: graph, count: count)[0]
```
Use when the input is an audio-rate generator and per-sample accuracy matters — FM synthesis, audio-rate AM, waveshaping. Reading via `calculatedSamples` evaluates the upstream generator at audio rate and returns the full block.
> **Caution:** `Double`, `Int`, and `Closure` `ValidGeneratorInput` conformances allocate on every `calculatedSamples` call. Use Pattern 1 (`floatValue`) for literal constants and closure inputs even when the consuming generator uses audio-rate reads for generator inputs. Use `ConstantGeneratorInput` when you need a Generator-typed constant that is RT-safe at audio rate.
> **Sub-block caution (ControlGenerators only):** When a `ControlGenerator` runs in sub-block mode (`controlBlockSize < blockSize`), its `_computeSamples` is called N times per audio block with `count = controlBlockSize`. Any `AudioGenerator` input consumed via Pattern 3 (`calculatedSamples`) inside `_computeSamples` receives `count = subCount`, advancing its state by only `subCount` samples per call. This causes phase divergence from full-block consumers of the same generator. For modulation inputs (freq, rate) inside a `ControlGenerator._computeSamples`, use Pattern 1 (`floatValue`) or a `ControlGenerator` source.
### Choosing the right pattern — the `inputIsGenerator` idiom
The all-in-one approach: classify each input **once at init time** using `is any Generator`, then branch in `_computeSamples` without any runtime type checks on the RT thread.
```swift
final class MyOsc: GeneratorBase, AudioGenerator {
private let freqInput: any ValidGeneratorInput
/// Classified once at init — no runtime `is` check on the RT thread.
private let freqIsGenerator: Bool
private var phase: Double = 0.0
private var _result: [[Double]]
init(freq: any ValidGeneratorInput = 440.0) {
self.freqInput = freq
self.freqIsGenerator = freq is any Generator
_result = [[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)]
}
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count, "...")
let sampleRate = Double(graph.engine.sampleRate)
// Evaluate unconditionally so the upstream generator always advances its state.
let freqSamples: [Double]?
let scalarFreqInc: Double
if freqIsGenerator {
freqSamples = freqInput.calculatedSamples(graph: graph, count: count).first
scalarFreqInc = 0
} else {
freqSamples = nil
scalarFreqInc = freqInput.floatValue(graph: graph) / sampleRate
}
for i in 0..<count {
let phaseInc: Double
if let fs = freqSamples {
phaseInc = (i < fs.count ? fs[i] : 0) / sampleRate
} else {
phaseInc = scalarFreqInc
}
_result[0][i] = someFunction(phase)
phase += phaseInc
if phase >= 1.0 { phase -= 1.0 }
}
return _result
}
func floatValue(graph: SynthGraph) -> Double {
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0
}
}
```
Key points:
- `freqIsGenerator` is stored at init, not checked per block.
- The `calculatedSamples` / `floatValue` call is **outside the inner loop** — only the index lookup happens per sample.
- When `freqIsGenerator` is false (literal `Double`/`Int`, `String`, or `Closure`), the scalar path calls `floatValue` once — zero extra allocation. `ConstantGeneratorInput` conforms to `Generator` and therefore takes the audio-rate `calculatedSamples` path; its buffer is pre-allocated so the path is RT-safe.
- String parameter key inputs are classified as non-generator (`String` does not conform to `Generator`), so they always use the block-rate scalar path. This is correct: parameter updates are control-rate by design.
### FM synthesis example
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
class FMSynth: SynthesizerBase {
override func build() {
let modulatorFreq: Double = 440.0
let carrierFreq: Double = 440.0
let modDepth: Double = 200.0 // modulation index ≈ 0.45
let modulator = OscSin.Audio(freq: modulatorFreq)
let carrier = OscSin.Audio(freq: modulator * modDepth + carrierFreq)
output(bus: 0, source: Pan2(input: carrier * 0.3))
}
}
```
`OscSin.Audio` detects that `freq` is a `BinaryOpGenerator` (a `Generator`) at init time, sets `_freqIsGenerator = true`, and reads a fresh per-sample frequency value on every block. The modulator's state advances exactly once per block via the fan-out cache — even if `carrier` and `output` both call `calculatedSamples` on it.
---
## 5. Fan-out Caching — Implement the Gateway
The `Generator` protocol extension provides `calculatedSamples` as a segment-serial caching gateway around your `_computeSamples`. You must **implement `_computeSamples`**, not `calculatedSamples`. Never override `calculatedSamples`.
```swift
// CORRECT — implement _computeSamples
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { ... }
// WRONG — overriding the caching gateway breaks fan-out safety
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { ... }
```
`AudioGenerator.floatValue` must route through the cache to prime it for control-rate callers:
```swift
// AudioGenerator — route through the full-block cache
func floatValue(graph: SynthGraph) -> Double {
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0
}
```
Using `count: graph.engine.blockSize` (not `count: 1`) is essential. If `floatValue` primes the cache with a 1-sample result, a subsequent `calculatedSamples(count: blockSize)` call in the same segment finds `cachedChannel.count (1) < count (blockSize)` and takes a cache miss, triggering a second `_computeSamples` call and double state-advance. Using the full block size ensures the cached result satisfies any downstream count request within the segment.
This ensures that whether a downstream generator calls `floatValue` or `calculatedSamples`, they both receive the same evaluation for the current segment.
> **`ControlGenerator` is different.** For `ControlGenerator`, `floatValue` must return the block-rate scalar target **directly** — it must not call `calculatedSamples`. The ramp is the *output* of `_computeSamples`, not an input to `floatValue`. See the `MyLFO` skeleton in §2 and `ParameterNode.swift` for the canonical pattern.
**Inherited stored properties** — by inheriting from `GeneratorBase`, conforming classes get `_segmentSerial`, `_cachedResult`, and `_subBlockBuffer` for free:
```swift
open class GeneratorBase {
public var _segmentSerial: UInt64 = 0 // cache key — init at 0
public var _cachedResult: [[Double]] = [[]] // cached block output
public var _subBlockBuffer: [[Double]] // assembly buffer for ControlGenerator sub-blocking
}
```
`_segmentSerial` starts at `0`; `SynthesisEngine.segmentSerial` starts at `1`, so the first call always misses the cache and calls `_computeSamples`. The `_cachedResult = []` step in the gateway releases the previous block's backing storage before computing, preventing a Swift CoW copy on the write into `_result[0]`.
---
## 6. Forbidden Operations on the RT Thread
The following must never appear inside `_computeSamples`:
| Forbidden | Why |
|-----------|-----|
| `Array(...)` or `[T](repeating:count:)` | Heap allocation |
| `Dictionary(...)` | Heap allocation |
| `String(...)` or string interpolation | Heap allocation |
| `class` instantiation (`SomeClass(...)`) | Heap allocation |
| `DispatchSemaphore.wait()` | Blocking |
| `os_unfair_lock_lock` / `NSLock.lock()` | Can block |
| `print(...)` / `NSLog(...)` | Heap allocation + I/O |
| `assertionFailure(...)` / `fatalError(...)` with a message | String construction + Swift runtime lock in debug builds |
| `try` with throwing operations | Can trigger allocation |
| Growing any collection (`.append`, `.reserveCapacity`) | Heap allocation |
| `vDSP_biquad_CreateSetupD` / `vDSP_biquad_DestroySetupD` | Heap allocation / deallocation |
| `vDSP_create_fftsetup` / `vDSP_destroy_fftsetup` | Heap allocation / deallocation |
| `vDSP_DFT_zop_CreateSetup` / `vDSP_DFT_DestroySetup` | Heap allocation / deallocation |
| Any Accelerate `*CreateSetup*` / `*DestroySetup*` call | Heap allocation / deallocation — use §12 off-thread pattern |
All mutable state must be pre-allocated in `init`. If you need to communicate results to the main thread (e.g. envelope completion), use `Synchronization.Atomic` — see §7.
### No force unwraps, no magic numbers
These apply in all generator code, not just on the RT thread.
**Force unwraps** — never use `!` on optionals or `try!`. The most common generator-specific hotspot is `UnsafeBufferPointer.baseAddress` inside Accelerate calls. Always use `guard let`:
```swift
// WRONG — baseAddress can theoretically be nil for empty slices
vDSP_vsmulD(src.baseAddress!, 1, &g, dst.baseAddress!, 1, n)
// RIGHT
src.withUnsafeBufferPointer { sb in
guard let s = sb.baseAddress else { return }
dst.withUnsafeMutableBufferPointer { db in
guard let d = db.baseAddress else { return }
vDSP_vsmulD(s, 1, &g, d, 1, n)
}
}
```
**Magic numbers** — bind every non-trivial literal to a named `let`. Exemptions: `0`, `1`, `-1`, and `2` in unambiguous arithmetic context.
```swift
// WRONG
let delay = [Double](repeating: 0, count: 2 * (numBiquads + 1))
let w = 1.0 / sqrt(2.0)
// RIGHT
let biquadDelayStateCount = 2 * (numBiquads + 1)
let delay = [Double](repeating: 0, count: biquadDelayStateCount)
let ambi1WScale = 1.0 / sqrt(2.0)
```
---
## 7. The `needsFree` Pattern
When a generator needs to signal completion to the non-RT context (e.g. an envelope that has finished playing), use `Synchronization.Atomic<Bool>`:
```swift
import Synchronization
final class MyEnv: AudioGenerator {
// ...
private let _needsFree: Atomic<Bool> = Atomic(false)
/// RT thread writes true when the envelope reaches its end.
/// Main thread reads this after each block to decide whether to free the node.
var needsFree: Bool { _needsFree.load(ordering: .acquiring) }
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
// ...
if doneCondition {
_needsFree.store(true, ordering: .releasing)
}
return _result
}
}
```
The RT thread stores with `.releasing`; the main thread loads with `.acquiring`. No lock, no allocation. See `EnvelopeGen.swift` for the full implementation (`_Base` holds `_needsFree`; both `EnvelopeGen.Audio` and `EnvelopeGen.Control` inherit it).
---
## 8. Denormal Hygiene
Any generator that maintains **feedback state** (IIR filter coefficients, ring-buffer write head, running accumulator) must apply `denormalsToZero()` to each feedback value after it is written. This prevents subnormal floating-point values from accumulating in signal tails, which causes 100× CPU spikes on both ARM64 and x86-64.
The thread-level `enableFlushToZero()` in `CoreAudioDriver.render()` is the primary defence, but `denormalsToZero()` on individual state variables is required as the surgical, self-documenting guard.
```swift
// After updating IIR state in _computeSamples:
y1 = a0 * x + a1 * x1 + b1 * y1
y1 = denormalsToZero(y1) // guard against subnormal accumulation
x1 = x // feedforward — no denormal risk
```
**Rule of thumb:** apply `denormalsToZero` to values that participate in a feedback loop (output fed back as input). Feedforward paths (input samples) do not need it.
```
State variable type | Apply denormalsToZero?
-------------------------------------------|------------------------
IIR feedback (y[n-1]) | YES
Delay buffer — feedback path (e.g. DelayLineFeedback) | YES (on write)
Delay buffer — feedforward only (e.g. DelayLine) | NO (input samples, no accumulation)
Phase accumulator | NO (wraps, doesn't accumulate error)
Input sample (x[n-1]) | NO (feedforward)
Envelope level | Consider if it can approach 0 asymptotically
```
See `DenormalUtils.swift` and `DenormalHandlingTests.swift` for the full reference.
---
## 9. Complete Skeleton
```swift
import LyrebirdSynth
import Synchronization
/// A template for a new AudioGenerator.
final class MyGenerator: GeneratorBase, AudioGenerator {
// MARK: Inputs
private let freqInput: any ValidGeneratorInput
private let freqIsGenerator: Bool // classified at init; never re-checked on RT thread
// MARK: DSP state
private var phase: Double = 0.0
// _result inherited from GeneratorBase (mono, lyrebirdDefaultResultBufferSize, zero-filled)
// MARK: Init
init(freq: any ValidGeneratorInput = 440.0) {
self.freqInput = freq
self.freqIsGenerator = freq is any Generator
super.init()
}
// MARK: Computation
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let sampleRate = Double(graph.engine.sampleRate)
let freqSamples: [Double]?
let scalarPhaseInc: Double
if freqIsGenerator {
freqSamples = freqInput.calculatedSamples(graph: graph, count: count).first
scalarPhaseInc = 0
} else {
freqSamples = nil
scalarPhaseInc = freqInput.floatValue(graph: graph) / sampleRate
}
let fullCycle: Double = 1.0
for i in 0..<count {
_result[0][i] = someFunction(phase)
let phaseInc: Double
if let fs = freqSamples { phaseInc = (i < fs.count ? fs[i] : 0) / sampleRate }
else { phaseInc = scalarPhaseInc }
phase += phaseInc
if phase >= fullCycle { phase -= fullCycle }
}
return _result
}
// floatValue inherited from AudioGenerator protocol extension
}
```
---
## 10. Testing Checklist
Write tests for every new generator using Swift Testing (`@Test`, `#expect`, `@Suite`).
> The `makeTestEngine`, `makeSynthGraph`, and `advanceBlock` helpers are defined in `Tests/LyrebirdTests/TestHelpers.swift`. Test files must use `@testable import LyrebirdSynth` and belong to the `LyrebirdTests` target to access them.
### Required tests
```swift
@Suite("MyGenerator")
struct MyGeneratorTests {
// 1. Rate matches protocol
@Test func rateIsAudio() {
#expect(MyGenerator().rate == .audio)
}
// 2. Output count matches request
@Test func outputCountMatchesRequest() throws {
let engine = makeTestEngine(blockSize: 64)
try engine.start()
let graph = makeSynthGraph(engine: engine)
let gen = MyGenerator(freq: 440.0)
let out = gen.calculatedSamples(graph: graph, count: 64)
#expect(out[0].count == 64)
engine.stop()
}
// 3. Precondition fires for over-count (use withKnownIssue or process-level test)
// Note: preconditions are fatal; test by verifying the guard exists in code review.
// 4. Fan-out — single evaluation within one segment
@Test func fanOutSingleEvaluation() throws {
let engine = makeTestEngine(blockSize: 8)
try engine.start()
let graph = makeSynthGraph(engine: engine)
let gen = MyGenerator(freq: 440.0)
let out1 = gen.calculatedSamples(graph: graph, count: 8)
let out2 = gen.calculatedSamples(graph: graph, count: 8)
// Same block, same serial — second call must return the cached result
#expect(out1[0] == out2[0])
engine.stop()
}
// 5. State advances exactly once per block (not twice)
@Test func stateAdvancesOncePerBlock() throws {
let engine = makeTestEngine(blockSize: 8)
try engine.start()
var graph = makeSynthGraph(engine: engine)
let gen = MyGenerator(freq: 440.0)
_ = gen.calculatedSamples(graph: graph, count: 8)
_ = gen.calculatedSamples(graph: graph, count: 8) // cache hit — no second advance
advanceBlock(engine)
graph = makeSynthGraph(engine: engine)
let block2 = gen.calculatedSamples(graph: graph, count: 8)
// Compare block2 against expected state after exactly one block of advance
// (assertion depends on generator specifics)
_ = block2
engine.stop()
}
// 6. Integration — runs inside a Synthesizer on the engine
@Test func integrationWithEngine() throws {
// Use a test Synthesizer that wires MyGenerator to an Out and runs a few blocks.
}
}
```
### Optional but recommended
- **Denormal test** — if the generator has feedback state, confirm output stays finite after 10 000 blocks of silence input (see `DenormalHandlingTests.swift`).
- **`floatValue` consistency** — `floatValue` routes through `calculatedSamples(count: blockSize)` and returns the first sample; confirm it returns the same value as `calculatedSamples(count: blockSize)[0][0]` on the same graph.
- **Parameter modulation** — wire a `ParameterNode` (from `@LiveParam`) to a frequency input and confirm the output changes after the value is mutated on the main thread.
---
## Pattern 4 — Multi-output generators
A generator can return more than one channel by pre-allocating `_result` with N inner
arrays and filling all of them in `_computeSamples`. `Out` writes each channel to a
consecutive bus automatically.
**Pre-allocation for two channels:**
```swift
private var _result: [[Double]] = [
[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize),
[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)
]
```
**Buffer precondition** — check only one channel (all are the same size):
```swift
precondition(count <= _result[0].count,
"MyGenerator: count (\(count)) exceeds pre-allocated buffer size")
```
**`_computeSamples` fills both channels and returns the full 2D result:**
```swift
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
precondition(count <= _result[0].count, "...")
for i in 0..<count {
_result[0][i] = leftSample(i)
_result[1][i] = rightSample(i)
}
return _result
}
```
**Usage in a Synthesizer:**
```swift
output(bus: 0, source: MyTwoChannelGenerator(input: osc))
// Out writes channel 0 → bus 0, channel 1 → bus 1
```
See `Sources/Lyrebird/Generators/Pan2.swift` for the canonical example.
---
## Pattern 5 — Multi-channel expansion with GeneratorArray
`GeneratorArray` wraps N independent generators and produces an N-channel
`[[Double]]`. Use it with `expand()` to create parallel signal paths in
`build()`:
```swift
override func build() {
// Two oscillators at different frequencies → stereo output
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
}
```
**Element-wise operators** produce a new `GeneratorArray`:
```swift
let quietOscs = oscs * 0.5 // each channel × 0.5
let stereo = oscs + otherOscs // element-wise (counts must match)
let panned = 0.3 * oscs // scalar op GeneratorArray
```
**Multi-channel bus reads** use `input(bus:channels:)`, mirroring `output(bus:source:)`:
```swift
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5) // read two buses, apply gain, write stereo
```
`GeneratorArray` conforms to `Generator` and participates in the fan-out cache,
so the same array instance can be safely shared between multiple consumers.
`output(bus: 0, source:)` handles multi-channel sources directly — channel 0 goes
to bus 0, channel 1 to bus 1, and so on. No separate stereo helper is needed.
---
## Pattern 6 — Extracting a channel from a multi-output generator
All `AudioGenerator` and `ControlGenerator` instances support a `[n]` subscript and a
`.channel(n)` method that return a single-channel `ChannelSelect.Audio` (or `.Control`).
Use this to decouple multi-output generators inline, without bus routing.
```swift
// Numeric subscript — works on any generator
let left = Pan2(input: src, pan: -0.3)[0]
let right = Pan2(input: src, pan: -0.3)[1]
// Named aliases on specific generators (sugar over [n])
let pan = Pan2(input: src)
output(bus: 0, source: pan.left + pan.right) // mono fold-down, Pan2 evaluates once
// FreqTracker inline — no downstream synth required
let tracker = FreqTracker(in: mic)
output(bus: 0, source: OscSin.Audio(freq: tracker.freq) * tracker.confidence)
// MCE decoupling
let oscs = expand([440.0, 880.0, 1320.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs[0] + oscs[1]) // mix first two channels only
```
**Fan-out:** `pan.left` and `pan.right` share the same `Pan2` instance. The segment-serial
cache ensures `Pan2._computeSamples` fires once per segment — both selectors see
sample-consistent data.
**Out-of-range `n`:** returns silence, never crashes. Channel count is a build-time property.
Named aliases: `Pan2` (`.left`, `.right`), `Pan4` (`.frontLeft`, `.frontRight`,
`.rearRight`, `.rearLeft`), `FreqTracker` (`.freq`, `.confidence`).
See `docs/stdlib/multichannel.md` — "Inline Channel Selection" section.
---
## 11. `ParameterNode` as a Signal-Graph Node
`ParameterNode` is a `ControlGenerator` that lives on the signal graph and is typically
created via the `@LiveParam` property wrapper. It is wired directly into generator `init`
calls via the projected value (`$name`):
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: Double = 440.0
override func build() {
let osc = OscSin.Audio(freq: $freq) // $freq: ParameterNode — ControlGenerator
output(bus: 0, source: osc * 0.2)
}
}
```
Because `ParameterNode` is an `AudioGenerator`, downstream generators that inspect
`freq is any Generator` (e.g. `OscSin`) take the audio-rate modulation path — calling
`calculatedSamples` for a full per-sample linear ramp from the previous value to the new
target. This is smoother than the string-key path (which calls `floatValue` for a
block-constant value).
### Key properties of `ParameterNode`
| Property | Value |
|----------|-------|
| Conforms to | `AudioGenerator`, `ValidGeneratorInput` |
| Cross-thread channel | `Atomic<UInt64>` bit-cast from `Double` (Double) |
| Main-thread write | `node.value = 880.0` — releasing atomic store |
| RT-thread read | acquiring load at start of each `_computeSamples` block |
| Interpolation | Linear ramp from `_previousValue` to target over the block |
| Fan-out | Segment-serial cache — safe to wire into multiple consumers |
| RT allocation | None — `_result` pre-allocated in `init` |
### Do not add `@LiveParam` semantics to generators you author
If you are writing a custom generator, do not reach for `ParameterNode` as an internal
field — accept `any ValidGeneratorInput` for inputs and let the caller decide whether to
pass a literal, a `ParameterNode`, or another generator:
```swift
// Good: caller wires whatever they want
final class MyFilter: AudioGenerator {
private let cutoff: any ValidGeneratorInput
init(cutoff: any ValidGeneratorInput) { self.cutoff = cutoff }
}
// Caller:
let filter = MyFilter(cutoff: $myParam) // @LiveParam
```
`@LiveParam` and `ParameterNode` are for the `SynthesizerBase` subclass layer —
the public API through which callers mutate a running synthesizer's parameters.
---
## 12. Accelerate / vDSP Optimizations
Use scalar loops first. Only reach for Accelerate after profiling identifies a hot path. A 512-sample block processed at 44100 Hz leaves ~11.6 ms per block — scalar Swift is fast enough for most generators. vDSP and vForce pay off for:
- Batch arithmetic on every sample in a block (scale, mix, clear)
- Batch trig on every sample (cos/sin for spectral synthesis, panning)
- Cascaded biquad filter banks at high orders (4+ sections)
- Matrix multiplies (Ambisonic decoding)
### Tier 1 — Batch arithmetic and vForce (always RT-safe)
These functions operate on pre-allocated buffers and do not allocate. They are safe to call inside `_computeSamples`.
| Function | Use |
|----------|-----|
| `vDSP_vclrD` / `vDSP_vclr` | Zero a buffer in-place |
| `vDSP_vsmulD` / `vDSP_vsmul` | Multiply buffer by scalar |
| `vDSP_vaddD` / `vDSP_vadd` | Element-wise add two buffers |
| `vDSP_vdpsp` | Convert `Double` buffer to `Float` in-place |
| `vvcosf`, `vvsinf` | Batch cosine / sine (Float) |
| `vvsqrtf`, `vvatan2f` | Batch sqrt / atan2 (Float) |
| `memmove` | Shift buffer content (overlap-add, ring-buffer slide) |
**Required boilerplate:** get a base address before entering the call. Never force-unwrap; always use `guard let`:
```swift
_result[0].withUnsafeMutableBufferPointer { buf in
guard let base = buf.baseAddress else { return }
var gain = panGain
vDSP_vsmulD(srcBase, 1, &gain, base, 1, vDSP_Length(count))
}
```
All buffers must be pre-allocated in `init` — never create `[Double](repeating:count:)` inside `_computeSamples`.
### Tier 2 — Matrix multiply with pre-allocated scratch (RT-safe with care)
`vDSP_mmulD` / `vDSP_mmul` themselves do not allocate, but they need a scratch matrix to pack input channels into the expected layout. Pre-allocate the scratch in `init`:
```swift
// init
private var _matrixScratch: [Double] // rows × count, pre-allocated
init(speakers: Int) {
_matrixScratch = [Double](repeating: 0, count: 4 * lyrebirdDefaultResultBufferSize)
// ...
}
// _computeSamples — fill scratch, then call vDSP_mmulD
_matrixScratch.withUnsafeMutableBufferPointer { scratch in
guard let ms = scratch.baseAddress else { return }
// pack channels into row-major scratch...
vDSP_mmulD(decodeMatrix, 1, ms, 1, outputBase, 1,
vDSP_Length(speakers), vDSP_Length(count), 4)
}
```
Never declare `var scratch = [Double](...)` inside `_computeSamples` — that allocates on the RT thread.
### Tier 3 — Setup-required vDSP operations (setup must be created off-RT)
Some Accelerate functions require an opaque setup object that is created by a separate "Create" call:
| Setup-creating call | Used by |
|--------------------|---------|
| `vDSP_biquad_CreateSetupD` | `vDSP_biquadD` cascade |
| `vDSP_create_fftsetup` | `vDSP_fft_zrip` |
| `vDSP_DFT_zop_CreateSetup` | DFT |
**All Create calls allocate. Never call them on the RT thread.**
Use the SPSCQueue + background Thread pattern:
1. **`init`** — create the initial setup on the main thread; start a background `Thread` that owns creation and teardown.
2. **RT thread** — enqueues a coefficient packet (a fixed-size value type, no allocation) on a `SPSCQueue` when parameters change; dequeues a ready setup from a response queue and swaps it in atomically.
3. **Background thread** — dequeues coefficient packets, calls `Create`, enqueues the new setup on the response queue, drains the kill queue by calling `Destroy`.
```swift
// Approximate structure (see ButterworthLowPass.swift for full implementation)
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket> // RT → bg: "rebuild with these"
private let _vdspRespQueue: SPSCQueue<OpaquePointer> // bg → RT: "here is the new setup"
private let _vdspKillQueue: SPSCQueue<OpaquePointer> // RT → bg: "destroy the old one"
private var _vdspSetup: OpaquePointer? = nil // RT-owned current setup
// RT thread (_computeSamples) on parameter change:
if !_vdspCoeffQueue.enqueue(newPacket) {
// Queue full — reset sentinels so next block retries instead of silently dropping
prevFreq = -1.0; prevSampleRate = -1.0
}
// Swap in any new setup the background thread prepared:
if let newSetup = _vdspRespQueue.dequeue() {
if let old = _vdspSetup {
if !_vdspKillQueue.enqueue(old) {
// Kill queue full — last-resort same-thread destroy.
// Unreachable under normal operation (capacity 32, bg drains every 1ms).
vDSP_biquad_DestroySetupD(old)
}
}
_vdspSetup = newSetup
}
// Background thread loop:
while let packet = _vdspCoeffQueue.dequeue() {
if let setup = vDSP_biquad_CreateSetupD(ptr, numSections) {
if !_vdspRespQueue.enqueue(setup) {
vDSP_biquad_DestroySetupD(setup) // response queue full, discard
}
}
while let old = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(old) }
}
```
Key invariants:
- Only the background thread calls `Create` / `Destroy`.
- `BiquadCoeffPacket` is a fixed-size value type (tuple of Doubles) — zero ARC, zero allocation when enqueued.
- Kill-queue capacity (32) must greatly exceed the maximum pending setups per second. At 512-sample blocks and 44100 Hz, one setup per block ≈ 86/s — capacity 32 means the background thread must drain within ~370 ms, well within its 1ms poll rate.
### What not to do
```swift
// WRONG — allocates on RT thread
let setup = vDSP_biquad_CreateSetupD(coeffPtr, numSections)
// WRONG — scratch allocated on every block
let scratch = [Double](repeating: 0, count: count * 4)
vDSP_mmulD(...)
// WRONG — force-unwrap on baseAddress
vDSP_vsmulD(buf.baseAddress!, 1, &gain, out.baseAddress!, 1, ...)
```
Add these to the forbidden list in §6 alongside heap allocation and locking.
---
## 13. Shared RT-Safe Helper Functions
Three module-level free functions and one method exist to eliminate repeated boilerplate. **Always use them** — do not re-inline the patterns they replace.
> **Out-of-tree extension packages:** these helpers are exposed as `@_spi(LyrebirdExtensions) public`. Add `@_spi(LyrebirdExtensions) import LyrebirdSynth` to any generator implementation file outside the core module. Full surface and stability policy: [extension-sdk.md](extension-sdk.md).
### `_resolvedInput()` — init-time resolution of `any ValidGeneratorInput`
Protocol requirement on `ValidGeneratorInput`. Default impl returns `self`; `GeneratorInputProvider` overrides to call its `make` closure and return a fresh `any ValidGeneratorInput`. Every Generator `init` that takes `any ValidGeneratorInput` parameters MUST call `_resolvedInput()` on each slot before storing or running `is any Generator` classification.
Full pattern + rationale: § 3.1 above. One-line rule: top-of-init `let resolvedX: any ValidGeneratorInput = x._resolvedInput()` before any storage.
**Helper-boundary skip-list.** Do NOT pre-resolve params that flow into one of these — the helper resolves internally, and pre-resolving is wasteful (idempotent but redundant):
| Helper | Slots it resolves internally |
|---|---|
| `MulAddSpec(mul:add:)` | `mul` / `add` |
| `OscillatorBase.init(freq:phase:mul:add:)` | `freq` + mul / add |
| `LFNoiseBase.init(freq:initialRngState:mul:add:)` | `freq` + mul / add |
| `NoiseBase.init(initialRngState:mul:add:)` | `mul` / `add` via MulAddSpec |
| `DynamicsBase.init(in:threshold:ratio:attack:release:kneeWidth:)` | all 6 dynamics slots |
Skipping resolution on a slot that does NOT flow through one of these = guaranteed crash at first audio block when a `GeneratorInputProvider` is passed to that slot (provider's accessor methods are `preconditionFailure` traps).
### `MulAddSpec.applyIfNeeded`
Every generator that exposes `mul`/`add` parameters stores a `MulAddSpec`. Apply it at the end of `_computeSamples` with a single call — do not write the `if !isIdentity` guard yourself:
```swift
// WRONG — boilerplate the helper was added to eliminate
if !_mulAdd.isIdentity { _mulAdd.apply(to: &_result, graph: graph, count: count) }
// RIGHT
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
```
`applyIfNeeded` is `@inline(__always)` — the guard is not a function call overhead, it compiles identically to the inline pattern.
### `fillRampedResult`
`ControlGenerator` implementations that own a `_rampTarget` property use this function to replace the ramp-fill + mulAdd + `previousOutputValue` update block:
```swift
// WRONG — 12+ lines of boilerplate
let rampStart = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
let countFloat = Double(count)
let step = (target - rampStart) / countFloat
for i in 0..<count {
_result[0][i] = rampStart + step * Double(i + 1)
}
if !_mulAdd.isIdentity {
_mulAdd.apply(to: &_result, graph: graph, count: count)
previousOutputValue = _result[0][count - 1]
} else {
previousOutputValue = target
}
return _result
// RIGHT — caller handles the count == 0 early-exit; helper does everything else
let rampStart = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
previousOutputValue = fillRampedResult(
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
return _result
```
`fillRampedResult` is `@inline(__always)` and allocates nothing. It returns the new `previousOutputValue` (either `target` on the identity path, or `_result[0][count - 1]` after mulAdd).
**When NOT to use it:** generators whose ramp has semantics that differ from the standard pattern — e.g. `Compressor.Control` (ramp multiplied into the input signal), `EnvelopeGen.Control` (no mulAdd, sets `previousOutputValue` before the ramp), or `ChannelSelect.Control` (no `_rampTarget`, no mulAdd). Use the helper only when your control path matches the standard flow exactly.
**`MathGenerators.Control` exception to `applyIfNeeded`:** The 21 `MathGenerators.Control` classes (Add, Mul, Sub, etc.) apply `_mulAdd` to the scalar `_rampTarget` *before* ramping — not to the output buffer after. They intentionally do not call `applyIfNeeded` on the buffer. This is architecturally correct: the mulAdd is baked into the ramp target so it participates in smoothing. Review agents must not flag this pattern as an `applyIfNeeded` violation.
### `fillScalarRampedResult`
The `Math.Control` family (Abs, Ceil, Clip, Cos, Exp, Fold, LinExp, Log, Pow, Sin, Sqrt, Tanh, Wrap, Ring1–4, etc. — 28 generators) has a different ramp shape than `fillRampedResult`: the caller pre-folds `mul`/`add` into the scalar `target` (the documented `MathGenerators.Control` exception above), so the helper must NOT re-apply `MulAddSpec.apply` after the ramp. Use `fillScalarRampedResult` for this pattern:
```swift
// WRONG — inline ramp loop (28-site duplication)
guard count > 0 else { return _result }
let rampStart = previousOutputValue; previousOutputValue = target
let step = (target - rampStart) / Double(count)
for i in 0..<count { _result[0][i] = rampStart + step * Double(i + 1) }
// RIGHT
fillScalarRampedResult(into: &_result, previousOutputValue: &previousOutputValue, target: target, count: count)
```
The helper updates `previousOutputValue` to `target` and returns void. `@inline(__always)`, allocates nothing, traps if `count > result[0].count`. Use whenever the standard `Math.Control` shape applies — scalar op + scalar mul/add fold + ramp.
### `xorshift64Next`
All noise generators share one xorshift64 PRNG. Use the free function instead of inlining the three bit-twist lines:
```swift
// WRONG — inline xorshift
rngState ^= rngState << 13
rngState ^= rngState >> 7
rngState ^= rngState << 17
let bipolarRangeScale: Double = 2.0
let sample = Double(rngState) / Double(UInt64.max) * bipolarRangeScale - 1.0
// RIGHT
let sample = xorshift64Next(&rngState)
```
Also use it in `_Base.init` to seed the initial value from the mixed state:
```swift
var state = initialRngState
self.currentValue = xorshift64Next(&state)
self.rngState = state
```
`xorshift64Next` is `@inline(__always)` and takes a direct `inout UInt64` — zero overhead.
### `lastGeneratorSampleOrFloat`
Many block-rate generators (dynamics, delay-time inputs, `ControlGenerator.Control` paths) need the most recent value of a `ValidGeneratorInput` at the *end* of the current block:
- If the input is a generator → read `_result[0][count - 1]` from its `calculatedSamples`.
- If the input is a scalar / `ParameterNode` / closure → read `floatValue(graph:)`.
The choice was repeated verbatim in 28 dynamics + delay sites before being extracted. Use the helper instead of inlining:
```swift
// WRONG — inline branching
let v: Double
if _xIsGenerator {
if let buf = input.calculatedSamples(graph: graph, count: count).first, count > 0 {
v = buf[count - 1]
} else {
v = input.floatValue(graph: graph)
}
} else {
v = input.floatValue(graph: graph)
}
// RIGHT
let v = lastGeneratorSampleOrFloat(input, isGenerator: _xIsGenerator, graph: graph, count: count)
```
`isGenerator` must be classified at `init` (`self._xIsGenerator = input is any Generator`) — never call `is` on the RT thread. The helper is `@inline(__always)`. Use it whenever a generator-or-scalar input needs to be sampled once per (sub-)block at block-rate granularity.
### `_checkCount` (on `GeneratorBase`)
Every `_computeSamples` opens with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Equivalent to the long-form `precondition(...)` that used to be repeated at the top of every generator. Use this everywhere instead of the inline form; replace generator-specific messages only if you need extra debug context (rare).
```swift
// WRONG — boilerplate
precondition(count <= _result[0].count,
"count \(count) exceeds pre-allocated buffer (\(_result[0].count)). "
+ "Ensure SynthesisEngine blockSize <= lyrebirdDefaultResultBufferSize.")
// RIGHT
_checkCount(count)
```
### `makeResultBuffer` / `makeSampleBuffer` (in `ResultBuffer.swift`)
Factory helpers for output / scratch buffers sized to `lyrebirdDefaultResultBufferSize`. `GeneratorBase` calls `makeResultBuffer(channels:)` internally; you rarely need them directly. Use them when you own a *separate* scratch buffer (e.g. zero-fallback rows, sidechain buffers) instead of inlining `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)`.
```swift
// WRONG
_zeroFallback = [Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)
// RIGHT
_zeroFallback = makeSampleBuffer()
```
### Summary table
| Helper | Location | Use when |
|--------|----------|----------|
| `_checkCount(_:)` | `GeneratorBase.swift` | Every `_computeSamples` — first line, traps on oversize block |
| `_calculatedSamplesBlockRate(graph:count:)` | `Generator.swift` | Body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (§15) — IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers |
| `OscillatorBase` (base class) | `Generators/Oscillators/OscillatorBase.swift` | Phase-accumulator oscillators (LF / band-limited saw / square / triangle / dutycycle / Impulse). Inherit instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Table-lookup oscillators (`OscSin`, `OscTable`) excluded — they store `_phase` in table-index units to avoid a per-sample multiply. |
| `NoiseBase` (base class) | `Generators/Noise/NoiseBase.swift` | xorshift64 noise generators. Inherit instead of declaring `rngState` / `_mulAdd` inline. Distribution-parameterised subclasses add their own params, forward `super.init(initialRngState:mul:add:)`. Crackle (no PRNG) and LF noise variants excluded. |
| `runRBJBiquadBlock(...)` | `Generators/Filters/RBJBiquadHelpers.swift` | `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Pass coefficient formula as closure; helper owns the shared input-pull / generator-vs-scalar branch / `processBlock` / `applyIfNeeded` tail. |
| `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` | `Generators/Filters/FilterHelpers.swift` | Two-pole resonator inner loop `y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`. Scalar variant for block-constant coefficients; interpolated variant for per-sample coefficient sweeps from `start` to `end`. State (`y1` / `y2`) passed as `inout`; denormal flush at the end of the helper. Used by `RingingFilter` + `ResonatingFilter` — pass the coefficient-computation function from the call site. |
| `sampleOrFallback(_:scalar:at:)` | `Generators/Filters/FilterHelpers.swift` | Per-sample coefficient lookup with zero-fallback past block end (`i < $0.count ? $0[i] : 0`). Replaces the verbose `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag` / `Decay` family uses a different end-clamp + `lagCoeff` wrapping convention — helper does not apply there. |
| `onePoleLowPassStep(state:x:b1:comp:)` | `Generators/Filters/FilterHelpers.swift` | One-pole low-pass smoother step `y = b1·state + comp·x` with `comp = 1 − b1` precomputed by caller. Mutates `state` `inout`; returns `y`. Used by `Lag.Audio`, `Lag2.Audio` (cascade two), `LagUpDown.Audio` / `Lag2UpDown.Audio` (after asymmetric coefficient selection). |
| `leakyIntegratorStep(state:x:b1:)` | `Generators/Filters/FilterHelpers.swift` | Leaky integrator step `y = x + b1·state` (SC `Decay` / `Decay2` convention — input not attenuated by `1 − b1`). Mutates `state` `inout`; returns `y`. Used by `Decay.Audio`, `Decay2.Audio` (cascade two for attack/decay difference). |
| `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` | `Generators/Dynamics/DynamicsHelpers.swift` | Asymmetric attack/release smoother step. `direction: .rising` selects attack-coeff when `target > state` (envelope-follower convention); `.falling` selects attack-coeff when `target < state` (compressor / expander gain-target convention). `comp = 1 − coeff` precomputed by caller for both pairs. Mutates `state` `inout`. Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`). |
| `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` | `GeneratorCore/HotLoopHelpers.swift` | `i < n ? p[i] : 0`. Per-sample input fetch with zero-pad past block end. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside `withUnsafeBufferPointer` hot loops. Across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` for out-of-tree generators. |
| `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` | `GeneratorCore/InputResolutionHelpers.swift` | Block-rate input resolution. Returns `(samples: [Double]?, scalar: Double)` — `samples != nil` means the input was a `Generator`, otherwise scalar via `floatValue(graph:)`. Replaces the 8-line `if _xxxIsGenerator { ... } else { ... }` boilerplate at the top of `_computeSamples` paths that pull multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. |
| `applySpatialDistanceFiltering(...)` | `Generators/Panning/SpatialDistanceHelpers.swift` | Shared per-sample distance-shaping + delay-line + lowpass + 4-corner equal-power pan pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Caller pre-computes `(panX, panY)` and the Chebyshev distance metric `posD` from its coordinate frame; the helper handles steps 3-11 of the pipeline (amplitude attenuation `1/posD`, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass with denormal flush, then calls `writeEqualPowerSquarePanSample`). Mutates `delayLine` / `writePos` / `readPos` / `lpZ1` / `lastCutoff` / `lastLPCoeff` `inout`. `@inline(__always) internal`. |
| `plateReverbInputDiffusion(...)` | `Generators/Reverb/PlateReverbHelpers.swift` | 4-stage cascaded `plateAllpassStep` — the Dattorro input diffusion network on a single sample. Each stage uses its own circular buffer, position, size, and coefficient. All state mutated `inout`. Consumed by `PlateReverb.Audio._computeSamples`. `@inline(__always) internal`. |
| `plateReverbTankHalf(...)` | `Generators/Reverb/PlateReverbHelpers.swift` | One half of the Dattorro figure-of-eight tank: modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write. Used twice per sample in `PlateReverb.Audio._computeSamples` (left + right halves). All state mutated `inout`; opposite-half feedback is read by the caller as `dl2Buf[dl2Pos]` (oldest sample) before invoking this helper. `@inline(__always) internal`. |
| `gverbReadEarlyTaps(...)` | `Generators/Reverb/GVerbHelpers.swift` | Reads four pre-FDN early-reflection taps from `tapBuf` with branchless wrap + per-tap gains; returns the four samples as `(u0, u1, u2, u3)`. Consumed by `GVerb.Audio._computeSamples`. `@inline(__always) internal`. |
| `gverbFDNDamperCascade(...)` | `Generators/Reverb/GVerbHelpers.swift` | Applies four one-pole LP damper steps `y = x*(1-damp) + prev*damp` to the four raw FDN delay-line reads. Mutates `fdnDampState[0..3]` `inout` with denormal flush; returns `(d0, d1, d2, d3)`. Caller pre-computes `fdnPassThrough = 1 - dampingVal`. `@inline(__always) internal`. |
| `makeSampleBuffer(_:)` / `makeResultBuffer(channels:)` | `ResultBuffer.swift` | Separately-owned scratch buffer or non-`GeneratorBase`-managed `_result` |
| `_mulAdd.applyIfNeeded(to:graph:count:)` | `MulAdd.swift` | Any generator with a `MulAddSpec` — audio or control rate |
| `fillRampedResult(into:from:to:mulAdd:graph:count:)` | `MulAdd.swift` | `ControlGenerator` with `_rampTarget` + `_mulAdd` following the standard ramp pattern |
| `fillScalarRampedResult(into:previousOutputValue:target:count:)` | `MulAdd.swift` | `Math.Control` ramp pattern (28 generators) — caller pre-folds `mul`/`add` into the scalar `target`; helper writes ramp without re-applying mulAdd |
| `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | `MulAdd.swift` | Block-rate read of a generator-or-scalar input — reads last sample of generator block, falls back to `floatValue` |
| `xorshift64Next(_:)` | `WhiteNoise.swift` | Any generator that needs an xorshift64 PRNG sample |
| `lyrebirdSeedXorshift64(from:mixConstant:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for Audio/Control pairs that must decorrelate via a per-variant `mixConstant` |
| `lyrebirdSeedXorshift64(from:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for stand-alone single-state owners (e.g. `DemandTemporalTendency`, `DemandTemporalBrownian`) — convenience for the two-arg form with `mixConstant: 0` |
| `_registerAutoFreeIfNeeded(_:)` | `Envelopes/DoneActionWatchable.swift` (extension) | Last line of every `DoneActionWatchable` generator's designated `init` (after `super.init`). If `doneAction == .freeNode`, self-registers with the currently-building `SynthesizerBase` so the synth auto-frees on completion. No-op outside `Synthesizer.build()`. |
---
## 14. Implementing a `DemandGenerator` Value Source
`DemandGenerator` is **not** a `Generator` — it is a pull-based value source owned by exactly one `Demand.Audio` or `Demand.Control` puller. Implement it when you need a new sequencing or randomisation source (e.g. a walk, a weighted random, a geometric series).
```swift
public protocol DemandGenerator: AnyObject {
func nextValue() -> Double? // nil = exhausted
func reset()
var isExhausted: Bool { get }
}
```
### Rules
- **No `_result` buffer, no `_segmentSerial`.** Not a `Generator`; never called by `calculatedSamples`.
- **`AnyObject`-constrained** — avoids Swift 6 `Sendable` issues with protocol existentials.
- **`nonisolated(unsafe) let _demand`** — the puller (`Demand.Audio`/`Demand.Control`) stores the source as `nonisolated(unsafe) let` because it is owned by exactly one instance on the RT thread.
- **`reset()` must restore `nextValue()` to the first value.** Whether or not PRNG state is restored is a design decision — `DemandRandom` intentionally does not restore its PRNG seed on `reset()` to avoid repeating random sequences.
- **`repeats: -1` = infinite** by convention (matches `DemandSequence`/`DemandRandom`).
### Minimal skeleton
```swift
public final class DWalk: DemandGenerator {
private let _values: [Double]
private let _repeats: Int
private var _index: Int = 0
private var _cycleCount: Int = 0
public init(values: [Double], repeats: Int = -1) {
_values = values
_repeats = repeats
}
public var isExhausted: Bool {
_repeats >= 0 && _cycleCount >= _repeats
}
public func nextValue() -> Double? {
guard !isExhausted, !_values.isEmpty else { return nil }
let v = _values[_index]
// advance _index with walk logic...
_index = (_index + 1) % _values.count
if _index == 0 { _cycleCount += 1 }
return v
}
public func reset() {
_index = 0
_cycleCount = 0
}
}
```
### Tests to write
- `returnsExpectedSequence` — verify ordering/selection logic
- `exhaustsAfterNRepeats` — drain with `while let v = seq.nextValue()`, check count
- `isExhaustedImmediately` when `repeats: 0`
- `resetRestartsSequence` — exhaust, reset, verify first value again
- `infiniteNeverExhausts` — run 1000 calls with `repeats: -1`, check `!isExhausted`
Reference implementations: `Sources/Lyrebird/Generators/Demand/DemandSequence.swift`, `DemandRandom.swift`.
---
## 15. Control Rate and `controlBlockSize`
`SynthesisEngine` processes its audio callback buffer in control sub-blocks. The sub-block size is determined at engine creation and is visible to every generator as `graph.engine.controlBlockSize`.
### How sub-blocks work
For each audio callback segment of `count` samples, `AudioGenerator.calculatedSamples` traverses the signal graph once and fills the full `count`-sample output. `ControlGenerator.calculatedSamples` calls `_computeSamples` in `controlBlockSize`-sample chunks (the sub-block loop), assembles results into `_subBlockBuffer`, caches the full block, and returns it. `AudioGenerator` consumers see no difference — they always receive a full interpolated block.
The sub-block loop is in the `ControlGenerator` protocol extension (`Generator.swift`). Never replicate it in `_computeSamples`.
### Configuring `controlBlockSize`
Pass `controlBlockSize:` to `SynthesisEngine.init`. If omitted, the engine uses `driver.suggestedControlBlockSize`, which defaults to `lyrebirdDefaultControlBlockSize` (64). The value must be a positive power of two that divides `blockSize` evenly.
```swift
// Explicit: 32-sample control blocks (16 sub-blocks in a 512-sample callback)
let engine = SynthesisEngine(blockSize: 512, controlBlockSize: 32, ...)
// Default (driver suggestion): lyrebirdDefaultControlBlockSize = 64
let engine = SynthesisEngine(blockSize: 512, ...)
```
### NRT and sample-accurate control
`NRTDriver.suggestedControlBlockSize` returns `lyrebirdSampleAccurateControlBlockSize` (1). At `controlBlockSize = 1`, every `ControlGenerator` advances its state machine once per sample — maximum envelope and modulation resolution at zero measurable CPU overhead (offline rendering has no RT budget). Use this for high-fidelity renders where envelope inflection points must land on exact sample boundaries.
```swift
let driver = NRTDriver(outputURL: url, duration: 4.0)
// controlBlockSize defaults to 1 via NRTDriver.suggestedControlBlockSize
let engine = SynthesisEngine(blockSize: 512, driver: driver, ...)
```
### Available constants
| Constant | Value | Use |
|----------|-------|-----|
| `lyrebirdDefaultControlBlockSize` | 64 | Default for RT drivers; good CPU/resolution tradeoff |
| `lyrebirdSampleAccurateControlBlockSize` | 1 | NRT default; one control tick per sample |
### `_subBlockBuffer` in paired generators
For paired generators using the `_Base` pattern (`Audio: _Base` + `Control: _Base`), declare `_subBlockBuffer` in `_Base`:
```swift
public class _Base {
var _result: [[Double]]
public var _subBlockBuffer: [[Double]] = [[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)]
// ...
}
```
This means `Audio` instances carry the property unused (4 KB), but all 21 MathGenerator `_Base` classes and every other paired generator follow this rule — new paired generators inherit the property automatically without a separate declaration in `Control`.
For standalone `ControlGenerator` conformers (no `_Base` superclass), declare `_subBlockBuffer` directly on the class (see §2 skeleton).
## 16. `RootRegistering` — auto-register side-effect roots
Generators that exist for their I/O side effect rather than for a usable downstream output — bus writers, recorders, disk I/O, trigger emitters — should conform to `RootRegistering` (`Sources/Lyrebird/GeneratorCore/RootRegistering.swift`). Constructed inside `SynthesizerBase.build()` they self-register as synth roots; the caller may discard the return value with `let _ = ...`.
Mechanism: the protocol's default extension method `_registerAsRootIfBuilding()` reads the `SynthesizerBase._currentlyBuildingRef` task-local — set by `rebuildGraph()` around the `build()` call — and calls `addOutputGenerator(self)` on the active synth. Outside `build()` (helper called from `LyrebirdTask`, async context, etc.) the task-local is nil and the call is a silent no-op; callers must register explicitly via `addOutputGenerator(_:)`.
### Conformance recipe
```swift
public final class MyDiskWriter: GeneratorBase, AudioGenerator, RootRegistering {
public init(/* … */) {
super.init(channels: 1)
_registerAsRootIfBuilding() // last line of designated init
}
// _computeSamples writes file, fills _result with passthrough or zeros
}
```
Call order in inits that also conform to `DoneActionWatchable`:
```swift
super.init(/* … */)
_registerAutoFreeIfNeeded(doneAction)
_registerAsRootIfBuilding()
```
Both helpers read the same task-local; order doesn't matter functionally but match the pattern across the codebase.
### Existing conformers
`Out.Audio`, `Out.Control`, `RecordBuffer.Audio`, `RecordBuffer.Control`, `DiskOut.Audio`, `SendTrigger.Audio`, `SendTrigger.Control`. Each keeps its existing passthrough output for inline insertion / monitoring use cases.
### Do not double-register
A `RootRegistering` generator that auto-registers AND is also passed to `addOutputGenerator(_:)` appears twice in `outputGenerators`. The second evaluation is short-circuited by the `_segmentSerial` fan-out cache (`_computeSamples` runs exactly once per segment), so the side effect fires only once — but the duplicate entry is wasteful. Either let auto-registration handle it, or construct outside `build()` and register manually — never both.
### When NOT to conform
`RootRegistering` is for generators whose primary purpose is a side effect. Pure signal producers (oscillators, filters, envelopes, math operators) MUST NOT conform — they are not roots; they are inputs to roots.
---
- `docs/protocols/generator.md` — protocol reference, type aliases, operator overloading
- `docs/protocols/synthesizer.md` — how to wire generators into a Synthesizer, `@LiveParam` usage
- `Sources/Lyrebird/Math/DenormalUtils.swift` — `enableFlushToZero`, `denormalsToZero`
- `Sources/Lyrebird/Generators/OscSin.swift` — canonical Audio+Control paired generator example (`_Base` pattern)
- `Sources/Lyrebird/Generators/Pan2.swift` — canonical multi-output generator example
- `Sources/Lyrebird/GeneratorCore/GeneratorArray.swift` — multi-channel expansion type
- `Sources/Lyrebird/Generators/EnvelopeGen.swift` — `needsFree` Atomic pattern; `_Base` shared between `EnvelopeGen.Audio` and `EnvelopeGen.Control`
- `Sources/Lyrebird/Parameters/ParameterNode.swift` — `ParameterNode` implementation
- `Sources/Lyrebird/Parameters/LiveParam.swift` — `@LiveParam` property wrapper
- `Sources/Lyrebird/Generators/Filters/FirstOrderSection.swift` — denormal hygiene on IIR state
- `Sources/Lyrebird/Generators/Filters/ButterworthLowPass.swift` — Tier 3 vDSP: SPSCQueue+background Thread setup delivery pattern
- `Sources/Lyrebird/Generators/Pan2.swift` / `AmbiEncoder1.swift` — Tier 1 vDSP: `vDSP_vsmulD` batch scale
- `Sources/Lyrebird/Generators/AmbiDecoder1.swift` — Tier 2 vDSP: `vDSP_mmulD` with pre-allocated scratch
- `Sources/Lyrebird/Generators/Demand/DemandSequence.swift` / `DemandRandom.swift` — canonical `DemandGenerator` examples
- `Sources/Lyrebird/Generators/Demand/Demand.swift` — `Demand.Audio`/`Demand.Control` puller pattern; `nonisolated(unsafe)` ownership, `didTrigger` per-block gate