# Generator Protocol The base unit of signal production in Lyrebird. ## Protocol Hierarchy ```swift protocol Generator: AnyObject { var rate: ProcessingRate { get } func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] func floatValue(graph: SynthGraph) -> Double } protocol AudioGenerator: Generator {} // rate == .audio protocol ControlGenerator: Generator {} // rate == .control enum ProcessingRate { case audio // sample rate (e.g. 44100 Hz) case control // block rate (e.g. 44100 / blockSize Hz) case spectral // integer multiple of control rate case demand // marks the DemandGenerator value-source tier; Demand.Audio/Control report .audio/.control } /// Marks a caseless namespace enum whose nested Audio and Control classes are a matched /// generator pair. Conforming types declare AudioType and ControlType so documentation, /// generic code, and tooling can discover the pair at compile time. protocol GeneratorEnum { associatedtype AudioType: AudioGenerator associatedtype ControlType: ControlGenerator } ``` ## Control-Rate Variants Paired generators use an `enum` namespace with nested `Audio` and `Control` classes (e.g. `OscSin.Audio`, `OscSin.Control`). The `Control` variant conforms to `ControlGenerator` instead of `AudioGenerator`. The `Control` variant runs once per block rather than once per sample, trading temporal resolution for CPU efficiency. ### When to create a Control variant Create a `Control` variant when **all** of the following are true: 1. **The generator produces an independent signal** — it has its own internal state (phase accumulator, PRNG, period counter) that advances over time without depending on an audio-rate input buffer. 2. **It is commonly used as a modulator (LFO), not audio content** — the output is wired to a parameter input of another generator rather than to an `Out` bus directly. 3. **Block-rate accuracy is sufficient** — oscillator frequencies below roughly `sampleRate / (blockSize × 4)` are indistinguishable from audio-rate in practice; noise and impulse generators are similarly well-served at block rate. Current generators that meet all three criteria: `OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`. ### When NOT to create a Control variant | Generator type | Reason | |---|---| | Filters (`RBJLowPass`, `ButterworthLowPass`, etc.) | Input-driven; filters already accept control-rate input via the interpolated ramp mechanism — no separate class needed | | Delay lines (`DelayLine`, `DelayLineFeedback`) | Require audio-rate state; a block-rate delay makes no acoustical sense | | Math generators (`BinaryOpGenerator`, `BipolarMappingGenerator`, `UnipolarMappingGenerator`, etc.) | Rate follows their inputs; they have no independent state to run at a different rate | | `EnvelopeGen.Audio` | Amplitude envelopes — per-sample shape accuracy is essential for click-free fade-outs and fast transients | ### How downstream consumers interact with Control-rate generators A `ControlGenerator`'s `_computeSamples` override produces a full `blockSize`-sample **interpolated ramp** from the previous block's output value to the current block's output value. This means any `AudioGenerator` that calls `calculatedSamples(count: blockSize)` on a `ControlGenerator` input receives a smooth audio-rate buffer — the filter or oscillator is unaware of the source rate. No special handling is required in the downstream generator. ### Naming convention (enum namespace pattern) Use an `enum` namespace with nested `_Base`, `Audio`, and `Control` classes. Both classes live in the same source file. Add a `GeneratorEnum` conformance extension at the bottom of the file to advertise the pair. ``` OscSin.Audio / OscSin.Control — OscSin.swift OscTable.Audio / OscTable.Control — OscTable.swift Impulse.Audio / Impulse.Control — Impulse.swift WhiteNoise.Audio / WhiteNoise.Control — WhiteNoise.swift LFStepNoise.Audio / LFStepNoise.Control — LFNoise.swift LFLineNoise.Audio / LFLineNoise.Control — LFNoise.swift EnvelopeGen.Audio / EnvelopeGen.Control — EnvelopeGen.swift PlayBuffer.Audio / PlayBuffer.Control — PlayBuffer.swift RecordBuffer.Audio / RecordBuffer.Control — RecordBuffer.swift In.Audio / In.Control — In.swift Out.Audio / Out.Control — Out.swift SendTrigger.Audio / SendTrigger.Control — SendTrigger.swift Demand.Audio / Demand.Control — Demand/Demand.swift ``` Every namespace enum adds a `GeneratorEnum` extension: ```swift extension OscSin: GeneratorEnum { public typealias AudioType = OscSin.Audio public typealias ControlType = OscSin.Control } ``` This lets generic code and DocC resolve the pair at compile time: ```swift func describe(_ type: G.Type) { print("Audio:", G.AudioType.self, "Control:", G.ControlType.self) } describe(OscSin.self) // Audio: OscSin.Audio Control: OscSin.Control ``` --- ## Type Aliases ```swift typealias ClosureBody = (SynthGraph, Int) -> Double // RT-safe closure signature ``` Samples are plain `Double` and counts plain `Int` — Lyrebird does not wrap them in aliases. ## ValidGeneratorInput Protocol Enables seamless mixing of constants, generators, and closures as generator inputs. All of the following are valid: ```swift let someGenerator: OscSin.Control = OscSin.Control(freq: 2.0, mul: 10.0, add: 440.0) let a: OscSin.Audio = OscSin.Audio(freq: 440.0) // Double literal let b: OscSin.Audio = OscSin.Audio(freq: 60) // Int literal let c: OscSin.Audio = OscSin.Audio(freq: someGenerator) // another Generator let d: OscSin.Audio = OscSin.Audio(freq: Closure { graph, i in Double(i) }) // closure ``` To drive an input from a live parameter, wire a `@LiveParam`'s projected value (`$freq`, a `ParameterNode`) into the generator. `String` is **not** a `ValidGeneratorInput` — the old string-parameter-key input was removed when `ParameterNode` / `UIParamNode` became `ControlGenerator`s. ```swift protocol ValidGeneratorInput { func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] func floatValue(graph: SynthGraph) -> Double func intValue(graph: SynthGraph) -> Int func needsInterpolation() -> Bool func sampleBlock(graph: SynthGraph, count: Int, previousValue: Double) -> [Double] } // Conforming types: Double, Int, any Generator, Closure, GeneratorInputProvider // Contract: calculatedSamples must always return a non-empty outer array (at least one channel). ``` ## Operator Overloading Math operators on Generator inputs create `BinaryOpGenerator` instances: ```swift let sig = OscSin.Audio(freq: 440) * 0.5 // BinaryOpGenerator (*) let mix = sig1 + sig2 // BinaryOpGenerator (+) ``` Operators: `*`, `+`, `-`, `/` ### Operator Precedence The overloads reuse Swift's standard operator symbols, so **standard Swift precedence applies**: | Operators | Precedence group | Associativity | |---|---|---| | `*`, `/` | `MultiplicationPrecedence` | left | | `+`, `-` | `AdditionPrecedence` | left | `*` and `/` bind before `+` and `-`; equal-precedence operators are left-to-right: ```swift osc * 0.5 + env // → (osc * 0.5) + env osc + env * 0.5 // → osc + (env * 0.5) osc - env - lfo // → (osc - env) - lfo (left-associative) (osc + env) * 0.5 // parentheses work normally ``` Note: `Double op Double` always resolves to the Swift stdlib — not a `BinaryOpGenerator`. At least one operand must be a `Generator` or `any ValidGeneratorInput`. ### BinaryOpGenerator — multi-channel broadcasting `BinaryOpGenerator` reads each operand's `outputChannelCount` at construction time and allocates `_result` to `max(lhs, rhs)` rows. Per-channel rules: - `1 × 1` → 1-row output (classic mono). - `1 × N` or `N × 1` → N-row output, mono operand broadcasts to every channel. - `N × N` → N-row output, element-wise. - `N × M` with both > 1 and N ≠ M → `precondition` traps at `init`. No implicit wrap-extend, no truncation. Compose explicitly via `ChannelSelect` or `GeneratorArray`. `outputChannelCount` is a `Generator` protocol requirement (default `1` from `GeneratorBase`). Multi-row generators (`Pan2`, `Pan4`, `PanN`, `AmbiEncoder1/Decoder1`, `SVF`, `FrequencyShifter.Audio`, `Chorus.Audio`, `GeneratorArray`, `TimeStretch.Audio`, multi-channel `In` / `BufferRead` / `PlayBuffer`, etc.) must override it. A missing override silently mono-izes the generator under arithmetic. > **Channel-aware `mul:` / `add:`** — `MulAddSpec.apply` follows the same broadcast policy > as `BinaryOpGenerator`: mono `mul`/`add` broadcasts across every output channel; `mul`/`add` > matching the output channel count applies per-channel; mismatched multi-row inputs trap at > the apply site. The `*` operator and `mul:` parameter now have parallel semantics. ### BinaryOpGenerator — scalar fast-path When one or both operands are non-Generator literals (`Double` or `Int`), `BinaryOpGenerator` uses `floatValue` instead of `calculatedSamples` for that side. This avoids the per-block `[[Double](repeating:count:)]` heap allocation that the `Double`/`Int` conformers would otherwise produce. The classification is performed once in `init` and stored as `lhsIsLiteral` / `rhsIsLiteral` — no type-metadata checks on the RT thread. ```swift // Fast path: rhs is a literal — only the generator side calls calculatedSamples. let sig = OscSin.Audio(freq: 440) * 0.5 // 0.5 → floatValue; OscSin → calculatedSamples // Both time-varying: both sides call calculatedSamples. let am = OscSin.Audio(freq: 440) * OscSin.Audio(freq: 2.0) ``` ### Fan-out caching A single `Generator` instance can safely feed multiple downstream consumers. The segment-serial fan-out cache ensures `_computeSamples` is called exactly once per `evaluateSegment` call regardless of how many consumers evaluate the same generator. State advances by exactly `count` samples per block — no double-advance artefacts. ```swift // osc is shared between two signal paths — fan-out cache ensures one evaluation per block: let osc = OscSin.Audio(freq: 440) let fm = OscSin.Audio(freq: osc * 200 + 880) // osc as FM modulator let mix = fm * 0.3 + osc * 0.05 // osc also in direct mix output(bus: 0, source: Pan2(input: mix)) ``` ## count: Int Parameter The `count` parameter in `calculatedSamples(graph:count:)` specifies exactly how many samples to produce. This is normally `blockSize`, but during sub-block splitting (scheduling) it may be smaller — a segment from event boundary to event boundary within a block. Generators **must** advance their stateful accumulators by exactly `count` samples per call, regardless of whether `count < blockSize`. This ensures correct timing across block boundaries. ## Pre-allocated output buffer pattern Every stdlib generator pre-allocates `_result` to `lyrebirdDefaultResultBufferSize` (512) samples in `init`, and opens `calculatedSamples` with: ```swift precondition(count <= _result[0].count, "count \(count) exceeds the pre-allocated buffer (\(_result[0].count) samples). ...") ``` This fires in both debug and release if the buffer is undersized — no grow path, no RT allocation. `SynthesisEngine.init` enforces `blockSize <= lyrebirdDefaultResultBufferSize`, so the precondition is never violated in engine-driven usage. New generators **must** follow this pattern exactly. ```swift // Canonical new-generator calculatedSamples skeleton: public func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]] { precondition(count <= _result[0].count, "count \(count) exceeds pre-allocated buffer. " + "Ensure blockSize <= lyrebirdDefaultResultBufferSize.") // ... fill _result[0][0..