# Writing Generators @Metadata { @PageKind(article) } A step-by-step guide to implementing correct, RT-safe generators in Lyrebird. > Before you write a whole type: for one-off custom sample-accurate DSP — especially a > **single-sample feedback loop** (one-pole, waveguide, comb/allpass) — reach for > ``SampleLoop`` first. It gives you an RT-safe, allocation-free per-sample body with typed > feedback state and channel inference, no new `Generator` declaration. Promote to a full > generator (this guide) when you want parameters, Quick Help, reuse, and raw-pointer speed. ## 1. Protocol Choice — AudioGenerator vs ControlGenerator | Criterion | Use `AudioGenerator` | Use `ControlGenerator` | |-----------|---------------------|------------------------| | Output resolution | One value per sample | One value per block | | 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 — the default allocates every call | ```swift // Audio-rate oscillator — inherit GeneratorBase for _segmentSerial, _cachedResult, _subBlockBuffer final class MyOsc: GeneratorBase, AudioGenerator { // No manual _segmentSerial / _cachedResult needed // ... } // Control-rate LFO — call _setupSubBlockBuffer() in init final class MyLFO: GeneratorBase, ControlGenerator { var previousOutputValue: Double = 0.0 init() { super.init() _setupSubBlockBuffer() // allocates sub-block assembly buffer; never call on RT thread } // ... } ``` > **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. ## 1b. Enum Namespace Pattern for Paired Generators When implementing both Audio and Control variants, group them under a caseless enum namespace and add a ``GeneratorEnum`` conformance extension: ```swift public enum MyOsc { public class _Base { // shared stored properties and init } public final class Audio: _Base, AudioGenerator { // per-sample loop } public final class Control: _Base, ControlGenerator { // block-rate ramp } } extension MyOsc: GeneratorEnum { public typealias AudioType = MyOsc.Audio public typealias ControlType = MyOsc.Control } ``` The ``GeneratorEnum`` extension is a two-line requirement with zero runtime cost. It makes the pair visible to DocC, autocomplete, and generic constraints. Every built-in paired generator follows this pattern. ## 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.. [[Double]] { _checkCount(count) let target = floatValue(graph: graph) let prev = previousOutputValue let step = (target - prev) / Double(count) for i in 0.. Double { // Return the block-rate target directly — do NOT call calculatedSamples here. rateInput.floatValue(graph: graph) } } ``` `_computeSamples` and `floatValue` have different roles: `floatValue` computes the block-rate target; `_computeSamples` builds the interpolated audio-rate ramp. ## 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 { private let freqInput: any ValidGeneratorInput private let qInput: any ValidGeneratorInput private var x1: Double = 0.0 // previous input sample private var y1: Double = 0.0 // previous output sample // _result inherited from GeneratorBase — no declaration needed for mono generators. init(freq: any ValidGeneratorInput, q: any ValidGeneratorInput) { freqInput = freq qInput = q super.init() } } ``` ## 4. Reading Inputs ### Pattern 1 — Scalar (block-rate) ```swift let freq = freqInput.floatValue(graph: graph) ``` Use when the parameter changes at most once per block. 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). The interpolated ramp is produced internally by `ControlGenerator._computeSamples`, which tracks `previousOutputValue` automatically. ### 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. > **Caution:** `Double`, `Int`, and `Closure` allocate on every `calculatedSamples` call. > Use Pattern 1 (`floatValue`) for literal constants, even when other inputs use audio-rate reads. > Use ``ConstantGeneratorInput`` when you need a Generator-typed constant that is RT-safe at > audio rate. ### The inputIsGenerator Idiom 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 private let freqIsGenerator: Bool // classified once at init private var phase: Double = 0.0 init(freq: any ValidGeneratorInput = 440.0) { // Resolve every `any ValidGeneratorInput` slot before // storing or classifying via `is any Generator`. See // `docs/protocols/writing-generators.md` § 3.1. let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() freqInput = resolvedFreq freqIsGenerator = resolvedFreq is any Generator super.init() } func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) let sampleRate = Double(graph.engine.sampleRate) 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..= 1.0 { phase -= 1.0 } } return _result } // floatValue inherited from AudioGenerator protocol extension. } ``` ### FM Synthesis Example ```swift // Example — your synthesizer, defined by subclassing SynthesizerBase class FMSynth: SynthesizerBase { override func build() { let modDepth: Double = 200.0 let modulator = OscSin.Audio(freq: 440.0) let carrier = OscSin.Audio(freq: modulator * modDepth + 440.0) output(bus: 0, source: Pan2(input: carrier * 0.3)) } } ``` ``OscSin`` 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. ## 5. Fan-Out Caching — Implement the Gateway Correctly 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 using the full block size: ```swift func floatValue(graph: SynthGraph) -> Double { calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0 } ``` Using `count: graph.engine.blockSize` (not `count: 1`) ensures a subsequent `calculatedSamples` call in the same segment is a cache hit — the cached result satisfies any downstream count request. > **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`. **Inherited stored properties** — inherit from `GeneratorBase` to receive `_segmentSerial`, `_cachedResult`, and `_subBlockBuffer` automatically. No manual declarations needed. ## 6. Forbidden Operations on the RT Thread | Forbidden | Why | |-----------|-----| | `[T](repeating:count:)` or `Array(...)` | 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 | | `try` with throwing operations | Can trigger allocation | | `.append`, `.reserveCapacity` | Heap allocation | ## 7. The needsFree Pattern When a generator needs to signal completion to the non-RT context, use `Synchronization.Atomic`: ```swift import Synchronization final class MyEnv: AudioGenerator { private let _needsFree: Atomic = Atomic(false) var needsFree: Bool { _needsFree.load(ordering: .acquiring) } func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { // … if doneCondition { _needsFree.store(true, ordering: .releasing) } return _result } } // Poll from main thread after each block: if myEnv.needsFree { engine.remove(synth) } ``` ## 8. Denormal Hygiene Apply `denormalsToZero()` to **feedback state** (IIR filter output history, delay feedback) after each update. Subnormal values cause ×100 CPU spikes on both ARM64 and x86-64. ```swift y1 = a0 * x + a1 * x1 + b1 * y1 y1 = denormalsToZero(y1) // feedback — guard against subnormal accumulation x1 = x // feedforward — no denormal risk ``` | State variable | Apply denormalsToZero? | |---|---| | IIR feedback (y[n-1]) | YES | | Delay buffer (feedback path) | YES | | Delay buffer (feedforward only) | NO | | Phase accumulator | NO | | Input sample (x[n-1]) | NO | ## 9. Complete Skeleton ```swift import LyrebirdSynth import Synchronization final class MyGenerator: GeneratorBase, AudioGenerator { // MARK: Inputs private let freqInput: any ValidGeneratorInput private let freqIsGenerator: Bool // MARK: DSP state private var phase: Double = 0.0 // _result inherited from GeneratorBase (mono, lyrebirdDefaultResultBufferSize, zero-filled) init(freq: any ValidGeneratorInput = 440.0) { // Resolve every `any ValidGeneratorInput` slot before // storing or classifying via `is any Generator`. See // `docs/protocols/writing-generators.md` § 3.1. let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() freqInput = resolvedFreq freqIsGenerator = resolvedFreq is any Generator super.init() } 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..= fullCycle { phase -= fullCycle } } return _result } // floatValue inherited from AudioGenerator protocol extension. } ``` ## 10. Testing Checklist Write tests using Swift Testing (`@Test`, `#expect`, `@Suite`). The `makeTestEngine`, `makeSynthGraph`, and `advanceBlock` helpers are in `Tests/LyrebirdTests/TestHelpers.swift`. ### Required tests ```swift @Suite("MyGenerator") struct MyGeneratorTests { @Test func rateIsAudio() { #expect(MyGenerator().rate == .audio) } @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() } @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) #expect(out1[0] == out2[0]) // same segment → cached result engine.stop() } } ``` ### Optional but recommended - **Denormal test** — if the generator has feedback state, confirm output stays finite after 10 000 blocks of silence input. - **`floatValue` consistency** — `floatValue` routes through `calculatedSamples(count: blockSize)` and returns the first sample; confirm it matches `calculatedSamples(count: blockSize)[0][0]` on the same graph. - **Parameter modulation** — wire a `ParameterNode` (from `@LiveParam`) to a frequency input and confirm output changes after the value is mutated on the main thread. ## Multi-Output Generators (Pattern 4) A generator returns more than one channel by passing `channels: N` to `super.init` and overriding `outputChannelCount`. `GeneratorBase` allocates an N-row `_result` in one shot — no subclass declaration or post-super reassignment: ```swift public override var outputChannelCount: Int { 2 } public init(...) { // ... set subclass stored properties ... super.init(channels: 2) } public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { _checkCount(count) for i in 0.. for the full multi-channel expansion guide. ## Debugging a New Generator When a generator's `_computeSamples` produces the wrong numbers, you need to step its compute loop for one instance and watch its state. Tag the instance with ``GeneratorBase/debugTag`` and set an LLDB conditional breakpoint on `_computeSamples`, or read its post-block output from a Synthesizer's debug tap. See for the full workflow.