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

12 KiB
Raw Blame History

Generator Protocol

The base unit of signal production in Lyrebird.

Protocol Hierarchy

protocol Generator: AnyObject {
    var rate: ProcessingRate { get }
    func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
    func floatValue(graph: SynthGraph) -> LyrebirdFloat
}

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:

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:

func describe<G: GeneratorEnum>(_ type: G.Type) {
    print("Audio:", G.AudioType.self, "Control:", G.ControlType.self)
}
describe(OscSin.self)  // Audio: OscSin.Audio  Control: OscSin.Control

Type Aliases

typealias LyrebirdFloat = Double
typealias LyrebirdInt = Int
typealias LyrebirdFloatClosureBody = (SynthGraph, Int) -> LyrebirdFloat

ValidGeneratorInput Protocol

Enables seamless mixing of constants, generators, parameter keys, and closures as generator inputs. All of the following are valid:

OscSin.Audio(freq: 440.0)           // Float literal
OscSin.Audio(freq: someGenerator)   // another Generator
OscSin.Audio(freq: "FreqParam")     // string parameter key — resolved at runtime
OscSin.Audio(freq: { g, i in ... }) // closure
protocol ValidGeneratorInput {
    func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
    func floatValue(graph: SynthGraph) -> LyrebirdFloat
    func intValue(graph: SynthGraph) -> LyrebirdInt
    func needsInterpolation() -> Bool
    func sampleBlock(graph: SynthGraph, count: Int, previousValue: LyrebirdFloat) -> [LyrebirdFloat]
}

// Conforming types: Double, Int, String, any Generator, Closure
// Contract: calculatedSamples must always return a non-empty outer array (at least one channel).

Operator Overloading

Math operators on Generator inputs create BinaryOpGenerator instances:

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:

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 [[LyrebirdFloat](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.

// 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.

// 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:

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.

// Canonical new-generator calculatedSamples skeleton:
public func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]] {
    precondition(count <= _result[0].count,
                 "count \(count) exceeds pre-allocated buffer. "
                 + "Ensure blockSize <= lyrebirdDefaultResultBufferSize.")
    // ... fill _result[0][0..<count] ...
    return _result
}

Statefulness

Each Generator instance owns its own state. Examples:

  • OscSin: phase accumulator
  • EnvelopeGen.Audio / EnvelopeGen.Control: current segment, elapsed time
  • DelayLine: circular buffer, write head position
  • FirstOrderSection: previous input and output sample

State is never shared between instances — graph-copy-per-Synthesizer ensures isolation.

Legacy Reference

These files are in legacy/Lyrebird/LyrebirdSynth/Lyrebird/ — the legacy prototype. They are not in the current codebase; they are design references only.

  • LyrebirdTypes.swift — ValidGeneratorInput pattern, type aliases
  • LyrebirdUgen.swift — base Generator class (legacy name: UGen)
  • MathUGens.swift — BinaryOpGenerator pattern, operator overloading
  • OscUGens.swift — sine table, phase accumulator pattern