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

2258 lines
91 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.
# Built-in Generator Library
Most generators conform to `AudioGenerator` or `ControlGenerator` (and therefore `Generator` and `ValidGeneratorInput`). Exception: `DemandGenerator` (`DemandSequence`, `DemandRandom`) is a separate pull-based value-source protocol — not a `Generator`. It is consumed by `Demand.Audio` and `Demand.Control`, which are full `Generator` conformers. `TimedDemandGenerator` extends `DemandGenerator` with elapsed-seconds + call-counter context; consumed by `TimedDemand.Audio` and `TimedDemand.Control`.
Generators that expose both an Audio and a Control variant are grouped under a caseless namespace enum and conform to `GeneratorEnum`:
```swift
// Any paired generator namespace conforms to GeneratorEnum:
// associatedtype AudioType: AudioGenerator
// associatedtype ControlType: ControlGenerator
//
// Example:
extension OscSin: GeneratorEnum {
public typealias AudioType = OscSin.Audio
public typealias ControlType = OscSin.Control
}
```
All paired built-in generators (`OscSin`, `OscTable`, `Impulse`, `WhiteNoise`, `LFStepNoise`, `LFLineNoise`, `PinkNoise`, `BrownNoise`, `GrayNoise`, `ClipNoise`, `Dust`, `Dust2`, `Crackle`, `LFCurveNoise`, `UniformNoise`, `GaussNoise`, `LpRandNoise`, `HpRandNoise`, `MeanRandNoise`, `ExpRandNoise`, `ExponentialNoise`, `GammaNoise`, `LaplaceNoise`, `ALaplaceNoise`, `HcosNoise`, `LogisticNoise`, `PoissonNoise`, `ArcsinNoise`, `BetaRandNoise`, `CauchyNoise`, `EnvelopeGen`, `PlayBuffer`, `RecordBuffer`, `In`, `Out`, `SendTrigger`, `Demand`, `TimedDemand`) conform to `GeneratorEnum`. New paired generators must do the same — see `docs/protocols/writing-generators.md`.
## RT-allocation model (all generators)
`_result` is pre-allocated to `lyrebirdDefaultResultBufferSize` (512 samples) in `init`. Each
`calculatedSamples` implementation begins 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 builds if a caller passes `count > 512`. The
`SynthesisEngine.init` precondition (`blockSize <= lyrebirdDefaultResultBufferSize`) guarantees the
condition is never violated in engine-driven usage. No heap allocation occurs in steady state.
`BinaryOpGenerator` and `Out.Control` follow the same pre-allocated buffer pattern:
- **`BinaryOpGenerator`**: `_result` pre-allocated in `init`; scalar inputs (`Double`/`Int` literals)
use `floatValue` instead of `calculatedSamples`, avoiding a second allocation per block.
Input literalness is classified once at `init` time (`lhsIsLiteral`/`rhsIsLiteral`) — no
runtime type checks on the RT thread.
- **`Out.Control`**: `_result` pre-allocated in `init`; fills in-place and returns the pre-allocated
buffer rather than constructing `[[LyrebirdFloat](repeating:count:)]` on every block.
- **`Out.Audio`**: returns the source's own `calculatedSamples` result directly — no additional
wrapper allocation.
---
## `ParameterNode` — Live Parameter Node
`ParameterNode` is an `AudioGenerator` that carries a single `LyrebirdFloat` value from
the main thread to the RT audio thread through a lock-free `Atomic<UInt64>`. It is
typically created implicitly via the `@LiveParam` property wrapper.
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0 // $freq is a ParameterNode
@LiveParam var amp: LyrebirdFloat = 0.2
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp)
}
}
tone.freq = 880.0 // main thread — no try, no string; RT picks it up next block
```
**`_computeSamples`** produces a linear ramp from `_previousValue` (last block's target)
to the current atomic target, reaching the target exactly at the last sample. On the first
block both values are equal, so the output is flat with no ramp artefact.
**Fan-out** — `ParameterNode` has the standard segment-serial cache. Wiring `$freq` into
multiple oscillators is safe; `_computeSamples` runs exactly once per block.
**Ramp delivery** — `ParameterNode` is a `ControlGenerator`. Generators that check
`input is any Generator` (e.g. `OscSin`) call `calculatedSamples` and obtain a
linearly-interpolated audio-rate buffer ramping from the previous block's last value to
the new atomic target. When `controlBlockSize == blockSize` (default), one ramp covers the
audio block; when `controlBlockSize < blockSize`, K segments cover it.
| Property | Value |
|----------|-------|
| Type | `ControlGenerator` |
| Cross-thread channel | `Atomic<UInt64>` bit-cast from `Double` |
| Main write | `node.value = x` — releasing store |
| RT read | acquiring load at start of each (sub-)block |
| Output | Linear ramp from previous to current target |
See `Sources/Lyrebird/Parameters/ParameterNode.swift` and `Sources/Lyrebird/Parameters/LiveParam.swift`.
---
## Implemented
### Oscillators
#### OscSin
Table-lookup sine oscillator. 32768-sample single-cycle table with selectable interpolation.
```swift
OscSin.Audio(freq: 440.0) // constant frequency, linear interp (default)
OscSin.Audio(freq: lfo, phase: 0.25) // generator input, quarter-phase offset
OscSin.Audio(freq: 440.0, interpolation: .cubic) // Catmull-Rom cubic interpolation
OscSin.Audio(freq: 440.0, table: engine.sharedTables.sineTable) // use engine's shared copy
```
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** (literal, String) call `floatValue` once per block. **Generator inputs** are read at audio rate — one frequency value per sample — enabling true FM synthesis with no block-rate aliasing.
- `phase` parameter is a fraction of a full cycle [0, 1).
- `interpolation` — `TableInterpolation` enum: `.none` (nearest), `.linear` (default), `.cubic`
(Catmull-Rom, ~4× arithmetic cost; only audibly better than `.linear` at table sizes < 256 or
near-Nyquist frequencies).
- `table` parameter (optional) accepts any power-of-two `LyrebirdBuffer`. Defaults to the
module-level `oscSinDefaultTable` (a lazy global filled once per process). Pass
`engine.sharedTables.sineTable` to share the engine's pre-computed copy and eliminate the
second allocation.
- **Power-of-two required**: `OscSin.init` enforces this with a `precondition`. Use `OscTable`
for non-power-of-two sizes.
- The table reference is stored as a non-Optional `let` ivar — zero ARC traffic on the RT thread.
- State: `LyrebirdFloat` phase accumulator, advanced per sample.
#### OscTable
Table-lookup oscillator reading from a user-supplied `LyrebirdBuffer`. Accepts any table content
and any size (power-of-two or not), with selectable interpolation.
```swift
// Custom waveform (linear interpolation, default)
let table = LyrebirdBuffer(count: lyrebirdDefaultTableSize)
table.fill { i, n in LyrebirdFloat(i) / LyrebirdFloat(n) * 2.0 - 1.0 } // sawtooth
let osc = OscTable.Audio(table: table, freq: 440.0)
// Cubic interpolation for a small custom table
let smallTable = LyrebirdBuffer(count: 64)
smallTable.fillSine()
let osc = OscTable.Audio(table: smallTable, freq: 440.0, interpolation: .cubic)
// Reuse engine's shared sine table (no extra allocation)
let osc = OscTable.Audio(table: engine.sharedTables.sineTable, freq: 440.0, phase: 0.25)
```
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** call `floatValue` once per block. **Generator inputs** are read at audio rate — one value per sample — enabling FM/PM with arbitrary waveform tables.
- `table` must have `count > 0` (`LyrebirdBuffer.init` enforces this).
- `phase` is a fraction of a full cycle [0, 1).
- `interpolation` — `TableInterpolation` enum: `.none`, `.linear` (default), `.cubic`.
- Index wrapping always uses `%`. Benchmarked on Apple Silicon M-series: `%` and `& mask`
are within measurement noise (< 1%) for all power-of-two sizes, so there is no separate
fast path for power-of-two tables.
- Checks `table.isValid` (acquiring load) each block; outputs silence if the table has been
invalidated. The freq input generator is always evaluated — its state advances even when silent.
- State: `LyrebirdFloat` phase accumulator, advanced per sample.
#### VectorOscillator
Vector-synthesis (XY) wavetable oscillator. Audio + Control variants; `GeneratorEnum` conformance. Crossfades between four mono `LyrebirdBuffer` waveforms on a 2D plane: `x` blends A↔B and C↔D, `y` blends the resulting AB↔CD pair. Linear blend on both axes; per-buffer reads use `TableInterpolation` (`.none` / `.linear` / `.cubic`).
```swift
let size = lyrebirdDefaultTableSize
let a = LyrebirdBuffer(count: size); a.fillSine()
let b = LyrebirdBuffer(count: size); b.fill(partials: 16)
let c = LyrebirdBuffer(count: size); c.fillTriangle()
let d = LyrebirdBuffer(count: size); d.fillHanning()
VectorOscillator.Audio(
bufferA: a, bufferB: b, bufferC: c, bufferD: d,
freq: 220.0,
x: LFNoise2.Audio(freq: 0.4) * 0.5 + 0.5, // animated X
y: LFNoise2.Audio(freq: 0.3) * 0.5 + 0.5 // animated Y
)
```
- `freq`, `x`, `y`, `phase` accept any `ValidGeneratorInput`. Per-sample evaluation in `.Audio` when supplied as a Generator (true FM on `freq`); block-rate (first sample) read in `.Control`.
- All four buffers must be mono and equal `count` (precondition at `init`). No power-of-two requirement.
- `x` and `y` clamp to `[0, 1]` per sample. Out-of-range values are clamped, not wrapped.
- All four buffers are validity-checked once per block; if any is `invalidate()`d the generator outputs silence while still advancing all modulation Generators (`.Control` ramps to 0).
- Mono output.
#### Impulse
Outputs 1.0 once per period, 0.0 otherwise.
```swift
Impulse.Audio(freq: 4.0) // fires 4× per second
Impulse.Audio(freq: 1.0, initPhase: 0.5) // first fire at half-period offset
```
- `freq` accepts any `ValidGeneratorInput`. **Scalar inputs** compute a constant phase increment once per block. **Generator inputs** are read at audio rate — one frequency value per sample — so the impulse spacing can be modulated at full audio precision.
- `initPhase` is a fraction [0, 1) — `0.0` fires at sample 0 of the first block.
- State: `LyrebirdFloat` phase accumulator.
---
### Noise
All three noise generators use the xorshift64 algorithm — lock-free, allocation-free on the RT
thread. Default seeds use `clock_gettime_nsec_np(CLOCK_UPTIME_RAW)` for nanosecond resolution
(eliminates same-millisecond seed collisions). Pass an explicit `seed:` for deterministic output
in tests.
#### WhiteNoise
Full-spectrum white noise in [-1, 1].
```swift
WhiteNoise.Audio()
WhiteNoise.Audio(seed: 42) // deterministic
```
#### LFStepNoise
Holds a random value for each step period, then jumps abruptly.
```swift
LFStepNoise.Audio(freq: 2.0) // new value 2× per second
LFStepNoise.Audio(freq: 2.0, seed: 42) // deterministic
```
- `floatValue` returns the current held value even before the first `calculatedSamples` call
(seeded in `init`).
#### LFLineNoise
Linearly interpolates between consecutive random values.
```swift
LFLineNoise.Audio(freq: 2.0)
LFLineNoise.Audio(freq: 2.0, seed: 42)
```
#### PinkNoise
Pink noise (~−3 dB/oct) using Paul Kellet's 7-stage IIR filter on white input.
```swift
PinkNoise.Audio()
PinkNoise.Audio(seed: 42) // deterministic
```
Output is scaled by `pinkNoiseScalingFactor` (0.11) to keep values approximately in [-1, 1].
`denormalsToZero()` is applied to IIR state after each block.
#### BrownNoise
Brown (red) noise via random walk. Each sample moves the previous value by ±`brownNoiseStepSize` (0.125), clamped to [-1, 1]. Produces ~−6 dB/oct.
```swift
BrownNoise.Audio()
BrownNoise.Audio(seed: 42)
```
#### GrayNoise
Stochastic Gray-code counter noise. Each sample, a random bit (0–31) of a running `Int32` counter is flipped; the scaled counter value is the output.
```swift
GrayNoise.Audio()
GrayNoise.Audio(seed: 42)
```
#### ClipNoise
Binary noise — sign of a white noise source. Every sample is exactly +1.0 or -1.0 with equal probability.
```swift
ClipNoise.Audio()
ClipNoise.Audio(seed: 42)
```
#### Dust
Probabilistic positive impulse generator. At density `d` Hz, each sample fires with probability `d/sampleRate`, emitting a value in `(0, 1)`.
```swift
Dust.Audio(density: 10.0) // ~10 impulses/second
Dust.Audio(density: lfo) // modulated firing rate
Dust.Audio(density: 10.0, seed: 42)
```
#### Dust2
Probabilistic bipolar impulse generator. Same as `Dust` but fired impulses lie in `(-1, 1)` instead of `(0, 1)`.
```swift
Dust2.Audio(density: 10.0)
Dust2.Audio(density: 10.0, seed: 42)
```
#### Crackle
2-pole chaotic map: `y[n] = |y[n-1] × chaos − y[n-2] − 0.05|`, bipolarised to [-1, 1].
Deterministic — no seed parameter. Initial state is fixed (`y1=0.3, y2=0.0`).
```swift
Crackle.Audio() // default chaos = 1.5
Crackle.Audio(chaos: 1.8) // denser crackle texture
Crackle.Control(chaos: 1.5) // block-rate chaotic modulator
```
- `chaos` controls chaotic complexity. Stable range: ~1.0–2.0. Values outside this range may diverge.
- Output is always bounded in [-1, 1] within the stable range.
#### LFCurveNoise
Quadratic-interpolated noise oscillator. Maintains a 3-point ring buffer of random values and
interpolates between steps with a parabola, producing smoother output than `LFLineNoise`.
```swift
LFCurveNoise.Audio(freq: 2.0)
LFCurveNoise.Audio(freq: 2.0, seed: 42) // deterministic
LFCurveNoise.Control(freq: 1.0)
```
- Output can overshoot the random data points by up to ~1.25× (parabolic overshoot).
- Smoother than `LFLineNoise` by a factor of ~1.05–1.5× in second-difference RMS.
---
### Filters
#### FirstOrderSection
Single-pole IIR: `y[n] = a0·x[n] + a1·x[n-1] + b1·y[n-1]`
```swift
FirstOrderSection(input: sig, a0: 1.0, a1: 0.0, b1: 0.5)
```
All coefficient inputs (`a0`, `a1`, `b1`) accept any `ValidGeneratorInput`. **Scalar inputs** are read once per block via `floatValue`. **Generator inputs** are read at audio rate — one value per sample — allowing dynamic waveshaping and audio-rate coefficient modulation. State: `x1`, `y1` persist across block boundaries.
#### SecondOrderSection
Two-pole biquad (Direct Form I): `y[n] = a0·x + a1·x[n-1] + a2·x[n-2] − b1·y[n-1] − b2·y[n-2]`
```swift
SecondOrderSection(input: sig, a0: 1.0, a1: 0.0, a2: 0.0, b1: 0.5, b2: 0.25)
```
All coefficient inputs (`a0`, `a1`, `a2`, `b1`, `b2`) accept any `ValidGeneratorInput`. **Scalar inputs** are read once per block via `floatValue`. **Generator inputs** are read at audio rate — one value per sample — allowing audio-rate coefficient modulation.
**Note:** pass `b1` and `b2` as positive magnitudes — the subtraction is applied internally.
State: `x1`, `x2`, `y1`, `y2` persist across block boundaries.
#### RBJ Filter Overview
All RBJ filters share the same modulation model:
- All parameter inputs accept any `ValidGeneratorInput` (literals, Strings, Generators).
- **Scalar inputs**: coefficients recomputed only when a parameter or `sampleRate` changes between blocks.
- **Generator inputs**: coefficients computed at block boundaries (first and last sample) and linearly interpolated across the block — at most 6 trig/pow calls per block regardless of block size.
- Frequencies above 0.999 × Nyquist return `BiquadCoeffs.zero` (silence).
- Shared infrastructure: `BiquadCoeffs` (normalised `nb0..na2`) and `BiquadState` (Direct Form I, `denormalsToZero()` on `y1`/`y2`) live in `Generators/Filters/RBJBiquad.swift`.
#### RBJLowPass
Second-order Butterworth-style lowpass. Rolls off above `freq` with Q controlling resonance.
```swift
RBJLowPass(input: sig, freq: 800.0, q: 0.707) // Butterworth LPF
RBJLowPass(input: sig, freq: sweepGen, q: 2.0) // audio-rate frequency sweep
```
#### RBJHighPass
Second-order highpass. Rolls off below `freq` with Q controlling resonance.
```swift
RBJHighPass(input: sig, freq: 400.0, q: 0.707)
```
#### RBJBandPass
Bristow-Johnson Audio EQ Cookbook bandpass filter. "Constant 0 dB peak gain" formulation.
```swift
RBJBandPass(input: sig, freq: 1000.0, bandwidth: 1.0) // 1-octave BPF at 1 kHz
RBJBandPass(input: sig, freq: sweepGen, bandwidth: 0.5) // swept centre frequency
```
- `bandwidth` is in octaves; `rbjLn2Half` (= `log(2.0)/2.0`) is computed once at module load.
#### RBJBandPassSkirt
Bandpass with constant skirt gain (peak gain = Q). Wider passthrough than `RBJBandPass` at high Q.
```swift
RBJBandPassSkirt(input: sig, freq: 1000.0, q: 4.0)
```
#### RBJNotch
Band-reject (notch) filter. Unity gain outside the notch, deep null at `freq`.
```swift
RBJNotch(input: sig, freq: 60.0, q: 10.0) // hum removal
```
#### RBJAllPass
Second-order allpass. Unity amplitude at all frequencies; rotates phase ±180° around `freq`.
```swift
RBJAllPass(input: sig, freq: 1000.0, q: 0.707)
RBJAllPass(input: sig, freq: lfoGen, q: 1.0) // phaser stage
```
#### RBJPeakingEQ
Parametric EQ bell filter. Boosts or cuts by `gain` dB in a bell centred at `freq`.
```swift
RBJPeakingEQ(input: sig, freq: 1000.0, gain: 6.0, q: 1.0) // +6 dB at 1 kHz
RBJPeakingEQ(input: sig, freq: 500.0, gain: -3.0, q: 2.0) // narrow cut
```
- `gain` is in dB; positive = boost, negative = cut. Unity outside the band.
#### RBJLowShelf
Low-shelf filter. Applies `gain` dB of boost or cut to frequencies below `freq`.
```swift
RBJLowShelf(input: sig, freq: 200.0, gain: 6.0, slope: 1.0) // +6 dB bass boost
RBJLowShelf(input: sig, freq: 120.0, gain: -3.0, slope: 0.5) // gentle bass cut
```
- `slope` controls transition steepness (1.0 = maximum slope for a 2nd-order shelf; smaller = gentler).
- `gain` is in dB.
#### RBJHighShelf
High-shelf filter. Applies `gain` dB of boost or cut to frequencies above `freq`.
```swift
RBJHighShelf(input: sig, freq: 8000.0, gain: 3.0, slope: 1.0) // gentle treble boost
RBJHighShelf(input: sig, freq: 6000.0, gain: -6.0, slope: 0.5) // treble cut
```
#### MuTronIII
Envelope-controlled resonant filter modelling the Musitronics Mu-Tron III (1972) auto-wah pedal.
Topology: full-wave rectifier → asymmetric one-pole envelope follower → exponential cutoff sweep → Chamberlin SVF.
Mono output; mode (LP/BP/HP) and sweep direction are constants set at `init`.
```swift
// Classic bandpass auto-wah
MuTronIII.Audio(input: guitar, sensitivity: 1.5, peak: 4.0)
// Reverse lowpass wah
MuTronIII.Audio(input: guitar, mode: .lowpass, direction: .down,
sensitivity: 2.0, freqLo: 120.0, freqHi: 4000.0)
// Control-rate (block-rate envelope and SVF state)
MuTronIII.Control(input: guitar, sensitivity: 1.0, peak: 3.0)
```
**Parameters:**
- `mode`: `.lowpass` / `.bandpass` / `.highpass`. Set at init. Selects SVF output.
- `direction`: `.up` (louder input raises cutoff) / `.down` (louder input lowers cutoff). Set at init.
- `sensitivity`: Drive into the envelope follower. Higher = more response to quiet signals. Typical `[0, 4]`.
- `peak`: Filter Q (resonance). Clamped to minimum `1.0` for Chamberlin stability across the full Nyquist sweep range.
- `freqLo` / `freqHi`: Cutoff range in Hz. Ratio `freqHi/freqLo` sets the sweep extent (default 40×).
- `attackTime` / `releaseTime`: Envelope time constants in seconds.
- Companion types: `MuTronIIIMode`, `MuTronIIISweep`.
---
### Envelopes
#### Envelope (value type)
The data model for an `EnvelopeGen`. Not itself a generator.
```swift
// Explicit per-segment durations
Envelope(levels: [0, 1, 0.5, 0], durations: [0.01, 0.3, 0.2], curves: [5, 0, -5])
// Equal-duration segments
Envelope(levels: [0, 1, 0], duration: 1.0, curves: [0, 0])
```
- `levels`: N+1 values. `durations` and `curves`: N values each (one per segment).
- Both `durations` and `curves` are padded/trimmed to `segmentCount` in `init` — a mismatched
array never reaches the RT thread.
- `totalDuration: LyrebirdFloat` is pre-computed in `init` (not a `reduce` computed property).
**Curve values** (formula per segment: `(1 − exp(curve·t/N)) / (1 − exp(curve))`):
| Value | Shape | Typical use |
|---|---|---|
| `0` (or `\|curve\| < 0.001`) | Linear | Test, gates |
| Positive (e.g. `5`) | Stays near start level, rushes to end — slow start, fast end | Build-up or swell effects |
| Negative (e.g. `-4`) | Moves quickly from start, decelerates to end — fast start, slow end | Natural ADSR attack / decay / release |
Negative curves (e.g. `-4`) produce natural ADSR shapes — fast start, decelerating to end.
#### EnvelopeGen.Audio / EnvelopeGen.Control
Multi-segment envelope generator.
`EnvelopeGen.Audio` evaluates one envelope sample per output sample — use for amplitude
envelopes and any case where per-sample shape accuracy matters.
`EnvelopeGen.Control` advances the envelope by `count` samples per block (so timing matches
`EnvelopeGen.Audio` exactly) and fills the output buffer with a linear ramp to the block's
target level — use for filter cutoff, pitch, or other parameters where block-rate resolution
is sufficient. Intra-block shape detail is lost; use `.Audio` when that matters.
```swift
let env = Envelope(levels: [0, 1, 0], duration: 0.5, curves: [-4, -4])
// Audio-rate: per-sample envelope shape (amplitude, fast transients)
let ampEnv = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
// After processBlock: if ampEnv.needsFree { engine.remove(synth) }
// Control-rate: block-rate envelope shape (filter cutoff, pitch)
let filtEnv = EnvelopeGen.Control(envelope: env)
let filter = RBJLowPass(input: osc, freq: filtEnv * 2000.0 + 200.0, q: 0.707)
```
**Parameters:**
- `envelope`: the `Envelope` value describing levels, durations, and curves.
- `levelScale`: multiplied into every output sample (default `1.0`). Accepts any `ValidGeneratorInput`.
- `levelBias`: added after scale (default `0.0`). `output = level × levelScale + levelBias`.
- `doneAction`: what happens when the last segment completes (see table below).
**Done actions:**
| Value | Behaviour |
|---|---|
| `.nothing` | Freeze at final level |
| `.freeNode` | Freeze and set `needsFree = true` |
| `.loop` | Restart from beginning |
**`needsFree`:** `Atomic<Bool>` — releasing store on the RT thread, acquiring load on the public
accessor. Read from a non-RT context after `processBlock` returns; never act on it from inside
the RT callback.
**Curve optimisation:** `exp()` is called at most 3× per segment entry to pre-compute
per-sample step coefficients; steady-state work is one multiply per sample.
#### Line.Control
Linear ramp from `start` to `end` over `dur` seconds with `DoneAction` dispatch on completion.
Control-rate only (no Audio variant — use `EnvelopeGen.Audio` when per-sample resolution matters).
```swift
Line.Control(start: 1.0, end: 0.0, dur: 2.0, doneAction: .freeNode)
```
- `start` / `end`: `Double` literals. Sign and magnitude unrestricted.
- `dur`: seconds, `>= 0`. `0` snaps to `end` and dispatches `doneAction` on the first block.
- `doneAction`: `.nothing` (freeze at end), `.freeNode` (set `needsFree`), `.loop` (restart).
- `mul` / `add`: standard output mul/add. Default identity.
#### ExponentialLine.Control
Exponential (geometric) ramp from `start` to `end` over `dur` seconds — interpolated in log
space. **Init traps** if `start` or `end` is zero, or if they have opposite signs.
```swift
ExponentialLine.Control(start: 100.0, end: 1000.0, dur: 1.0)
```
- `start` / `end`: non-zero, same sign. Magnitudes unrestricted.
- `dur`, `doneAction`, `mul`, `add`: same semantics as `Line.Control`.
#### RateRamp.Control
Open-ended linear accumulator. Initialises to `start`, grows by `rate` units per second; on
a `≤0 → >0` rising edge of `trigger`, resets to the current value of `start` and continues.
No done action — runs for the lifetime of its node.
```swift
let trig = Impulse.Control(freq: 1.0)
let ramp = RateRamp.Control(trigger: trig, rate: 1.0)
```
- `trigger`: any `ValidGeneratorInput`. Read at audio rate for sample-accurate edge detection.
At most one reset fires per audio block.
- `rate`: any `ValidGeneratorInput`, units per second. Read once per audio block via
`lastGeneratorSampleOrFloat` (captures `ParameterNode` ramp endpoints).
- `start`: any `ValidGeneratorInput`. Sampled at the first audio block (to seed the
accumulator) and at every trigger edge — modulating between edges has no effect.
Default `0.0`.
- `mul` / `add`: standard output mul/add.
Modelled on SuperCollider's `Sweep`, with an added modulatable `start`.
---
### Delays
#### DelayLine
Variable delay, no feedback. Power-of-2 circular buffer.
```swift
DelayLine(input: sig, maxDelay: 1.0, delay: 0.25)
DelayLine(input: sig, maxDelay: 1.0, delay: modGen, interpolation: .cubic)
```
**Interpolation modes:**
| Mode | Quality | Cost |
|---|---|---|
| `.none` | Truncated to integer samples | Lowest |
| `.linear` | Linear between adjacent samples (default) | Low |
| `.cubic` | Catmull-Rom 4-point stencil | Higher |
- `delay` accepts any `ValidGeneratorInput`. **Scalar inputs** compute a constant delay in samples once per block. **Generator inputs** are read at audio rate — one delay value per sample — enabling vibrato, chorus, and other audio-rate time-varying effects.
- **Read-before-write ordering**: output[n] = buffer at delay offset *before* input[n] is written.
Zero delay reads the previous sample, not a lookahead.
- `maxDelay` sizes the buffer at init; requesting more than `maxDelay` is clamped.
- `sampleRate` default (`44100`) is used only for buffer sizing — live rate is read from
`graph.engine.sampleRate` each block.
#### DelayLineFeedback
Delay with feedback and decay time. Integer-sample delay only (no interpolation).
```swift
DelayLineFeedback(input: sig, maxDelay: 1.0, delay: 0.25,
decayTime: 2.0, targetAmp: 0.001)
```
- Feedback coefficient: `exp(log(targetAmp) × delay / decayTime)`
- Coefficient is cached and recomputed only when `delaySecs`, `decayTime`, or `targetAmp` change
between blocks (mirroring `RBJBandPass`'s change-detection pattern).
- Minimum 1-sample delay is enforced — inherent to the feedback topology.
- `targetAmp` defaults to `0.001` (−60 dB).
---
### Math Generators
#### BipolarMappingGenerator
Maps [-1, 1] → [low, high]. Formula: `low + (input + 1) × 0.5 × (high − low)`.
```swift
BipolarMappingGenerator(input: lfo, low: 200.0, high: 800.0) // LFO → frequency sweep
```
#### UnipolarMappingGenerator
Maps [0, 1] → [low, high]. Formula: `low + input × (high − low)`.
```swift
UnipolarMappingGenerator(input: env, low: 200.0, high: 800.0) // envelope → frequency sweep
```
#### CosGenerator
Applies cosine sample-by-sample. Input treated as radians.
```swift
CosGenerator(input: phasor)
```
#### SquaredGenerator
Squares each sample: `output = input × input`. Full-wave rectifier when input is a sine.
```swift
SquaredGenerator(input: osc)
```
#### NegativeGenerator
Negates each sample: `output = −input`. Phase inversion.
```swift
NegativeGenerator(input: osc)
```
#### Unary Math Generators (Audio + Control)
All single-input, per-sample. `NaN`/`Inf` propagate per IEEE 754.
| Generator | Operation | Notes |
|-----------|-----------|-------|
| `Abs` | `\|signal\|` | Full-wave rectifier |
| `Sign` | −1 / 0 / +1 | Zero-crossing detection |
| `Floor` | ⌊signal⌋ | Staircase at audio rate |
| `Ceil` | ⌈signal⌉ | |
| `Round` | nearest integer | Half away from zero |
| `Sqrt` | √signal | NaN for negative input |
| `Reciprocal` | 1/signal | ±Inf for zero input |
| `Log` | ln(signal) | NaN/−Inf for non-positive |
| `Exp` | eˢⁱᵍⁿᵃˡ | |
```swift
let rect = Abs.Audio(osc)
let gate = Sign.Control(lfo)
```
#### Binary Math Generators (Audio + Control)
| Generator | Operation |
|-----------|-----------|
| `Min` | `min(a, b)` element-wise |
| `Max` | `max(a, b)` element-wise |
```swift
let limited = Min.Audio(osc, ConstantAudioGen(0.8)) // soft upper limit
```
#### Mapping Quartet (Audio + Control)
| Generator | Input → Output | Precondition |
|-----------|---------------|--------------|
| `LinLin` | linear → linear | — |
| `LinExp` | linear → exponential | outLo > 0 |
| `ExpLin` | exponential → linear | inLo > 0 |
| `ExpExp` | exponential → exponential | inLo > 0, outLo > 0 |
```swift
let freq = LinExp.Control(knob, inLo: 0.0, inHi: 1.0, outLo: 80.0, outHi: 8000.0)
let norm = ExpLin.Audio(tracker, inLo: 80.0, inHi: 8000.0, outLo: 0.0, outHi: 1.0)
```
---
## Demand-Rate Generators
Pull-based generators that advance one step per trigger (≤0→>0 crossing). Between triggers the output holds the last fetched value. When the source is exhausted the last value is held indefinitely.
### DemandGenerator protocol
Not a `Generator` — pure value source. Implemented by `DemandSequence` and `DemandRandom`.
```swift
public protocol DemandGenerator: AnyObject {
func nextValue() -> Double? // nil = exhausted
func reset()
var isExhausted: Bool { get }
}
```
### DemandSequence
Cycles through `values` in order. `repeats` = full cycles (-1 = infinite). Mirrors `Pattern<Double>` semantics.
```swift
DemandSequence(values: [261.63, 293.66, 329.63, 349.23]) // infinite
DemandSequence(values: [1.0, 2.0, 3.0], repeats: 2) // 6 values then exhausted
```
### DemandRandom
Picks one value at random from `values` per trigger. `repeats` = total trigger-responses (-1 = infinite). Seeded xorshift64 PRNG.
```swift
DemandRandom(values: [100.0, 200.0, 300.0, 400.0]) // infinite random
DemandRandom(values: [1.0, 2.0, 3.0], repeats: 5, seed: 42) // deterministic, 5 responses
```
### Demand.Audio
Sample-accurate puller. Outputs `_heldValue` every sample; updates on each rising edge of `trig`.
```swift
Demand.Audio(
trig: Impulse.Audio(freq: 4),
demand: DemandSequence(values: [261.63, 329.63, 392.0, 523.25])
)
```
`reset` parameter (default `0.0`) resets the demand source and clears the held value on a rising edge. Reset fires before trigger within the same sample.
### Demand.Control
Block-rate puller. Scans the full trigger block per-sample to catch mid-block rising edges. Output ramps from previous block target to new held value (matches the standard `ControlGenerator` ramp convention).
```swift
let pitchSeq = Demand.Control(
trig: Impulse.Control(freq: 4),
demand: DemandSequence(values: [261.63, 293.66, 329.63, 349.23])
)
addOutputGenerator(Out.Audio(bus: 0, source: OscSin.Audio(freq: pitchSeq)))
```
`floatValue(graph:)` returns `previousOutputValue` without advancing the sequence.
---
## Temporal Demand Generators
Time-aware demand generators where distribution parameters evolve with elapsed time. See `docs/Lyrebird.docc/TemporalDemand.md` for the full guide.
### TimedDemandGenerator protocol
Extends `DemandGenerator` with timing context.
```swift
public protocol TimedDemandGenerator: DemandGenerator {
func nextValue(elapsedSeconds: Double, counter: Int) -> Double?
}
```
### DemandTemporalTendency
RT-safe demand generator sampling from any of 16 statistical distributions. Parameters are `RTTemporalParameter` (`.value` or `.envelope` only — no closures on RT thread).
```swift
// Gaussian pitch — mean drifts from 220 → 880 Hz over 20 s
let tendency = DemandTemporalTendency(
distribution: .gauss,
parX: .value(30.0), // stddev
parY: .envelope(Envelope(levels: [220, 880], durations: [20.0])),
seed: 42
)
let pitch = TimedDemand.Control(trig: Impulse.Control(freq: 4), demand: tendency)
```
### DemandTemporalBrownian
RT-safe random walk. Bounds and step size are `RTTemporalParameter`.
```swift
let walk = DemandTemporalBrownian(lo: .value(200), hi: .value(800), stepSize: .value(50))
let pitch = TimedDemand.Control(trig: Impulse.Control(freq: 2), demand: walk)
```
### TimedDemand.Audio / TimedDemand.Control
Drop-in replacements for `Demand.Audio/Control`. Pass elapsed seconds (sample-accurate) and call counter to the demand source on each trigger edge.
```swift
TimedDemand.Audio(trig: trigGen, demand: tendency)
TimedDemand.Control(trig: trigGen, reset: resetGen, demand: walk)
```
---
## Operators and Bus I/O
### BinaryOpGenerator
Created via operator overloading on any `Generator` operand. Not instantiated directly.
```swift
let sig = osc * 0.5 // BinaryOpGenerator (*)
let mix = sig1 + sig2 // BinaryOpGenerator (+)
let diff = a - b // BinaryOpGenerator (-)
let ratio = a / b // BinaryOpGenerator (/)
```
### In.Audio / In.Control
Read from one or more consecutive buses. Do not modify bus memory. Channel count is fixed at init — no RT allocation.
```swift
// Single-channel (default)
In.Audio(bus: 2) // AudioGenerator — reads audioBuses[2]
In.Control(bus: 10) // ControlGenerator — reads controlBuses[10], interpolated ramp
// Multi-channel — N consecutive buses, N-channel [[LyrebirdFloat]] output
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps
// AudioBus convenience — channel count comes from the allocation
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
In.Audio(bus: stereo) // equivalent to In.Audio(bus: stereo.index, channels: 2)
```
`floatValue` always returns channel 0. `In.Control` maintains per-channel ramp state; `previousOutputValue` proxies channel 0 for `ControlGenerator` protocol conformance.
Use `In.Audio.multi(bus:channels:)` to get a `GeneratorArray` of independent single-channel generators instead of one multi-output generator:
```swift
In.Audio.multi(bus: 4, channels: 2) // GeneratorArray — two separate In.Audio instances
In.Audio.multi(bus: stereo) // same, from an AudioBus allocation
```
Use `input(bus:channels:)` inside `build()` for the same GeneratorArray pattern:
```swift
input(bus: 2, channels: 2) // -> GeneratorArray reading buses 2 and 3
```
### Out.Audio / Out.Control
Accumulate into a bus using `+=`. Multiple Synthesizers writing the same bus sum (mixing/polyphony).
```swift
Out.Audio(bus: 0, source: sig) // AudioGenerator — accumulates into audioBuses[0]
Out.Control(bus: 10, source: lfo) // ControlGenerator — accumulates into controlBuses[10]
```
`Out` writes each channel of a multi-channel source to consecutive buses (`bus`, `bus+1`, …).
Mono sources are unaffected. `Out.Audio.calculatedSamples` passes through the source samples
as its return value (passthrough semantics). `Out.Control` returns the source value, not
the post-accumulated bus state.
### GeneratorArray / Pan2
See `docs/stdlib/multichannel.md`.
### ChannelSelect.Audio / ChannelSelect.Control
Single-channel extractor. Wraps any `ValidGeneratorInput` and extracts one channel by
index from its `calculatedSamples` output. Enables inline channel decoupling without
bus routing.
All `AudioGenerator` and `ControlGenerator` instances inherit a `[n]` subscript and
`.channel(n)` method returning typed `ChannelSelect` instances. Named aliases exist on
`Pan2` (`.left`, `.right`), the `Pan4` subclass family (`.frontLeft`, `.frontRight`, `.rearRight`,
`.rearLeft`), and `FreqTracker` (`.freq`, `.confidence`).
Out-of-range `n` returns silence. See `docs/stdlib/multichannel.md` for full examples.
---
## LyrebirdMusicMath — Musical Conversion Utilities
Numeric conversion utilities. All conversions are plain free functions; scalar and array forms share the same name.
**RT safety:** Scalar functions (`Double`/`Int` arguments) are RT-safe — pure floating-point math, no allocation. Array overloads (`[Double]` arguments) allocate and must not be called from the RT thread.
### Tuning constants
```swift
lyrebirdA4TuningHz // 440.0 — A4 reference in Hz
lyrebirdA4MidiNote // 69.0 — MIDI note for A4
```
### MIDI ↔ Hz
Fractional MIDI supported. `hzToMidi` returns `-.infinity` for non-positive input.
```swift
midiToHz(60) // 261.63 Hz — Int overload
midiToHz(60.5) // quarter-tone above middle C
midiToHz(69.0) // 440.0
hzToMidi(440.0) // 69.0
midiToHz(69.0, tuning: 432.0) // 432.0 — custom A4
midiToHz(69, tuning: 432.0) // same, Int overload
```
### Amplitude / dB
| Function | Direction | Scale factor |
|----------|-----------|-------------|
| `ampToDb` | linear amp → dBFS | 20 × log₁₀ |
| `dbToAmp` | dBFS → linear amp | 10^(x/20) |
| `powToDb` | power → dB | 10 × log₁₀ |
| `dbToPow` | dB → power | 10^(x/10) |
```swift
ampToDb(1.0) // 0.0
ampToDb(0.5) // −6.02
dbToAmp(0.0) // 1.0
```
### Intervals
```swift
semitonesToRatio(12.0) // 2.0 — one octave
ratioToSemitones(2.0) // 12.0
centsToRatio(100.0) // ~1.0595 — one semitone
ratioToCents(2.0) // 1200.0
```
`midiToRatio` / `ratioToMidi` are SC-flavored synonyms (matches `midiToHz` /
`hzToMidi` naming) and also exist as dot-syntax on `Double` and `Int` —
handy for driving pitch-shift / playback-rate generators with semitone
intervals:
```swift
midiToRatio(12) // 2.0 — one octave up
midiToRatio(-12) // 0.5 — one octave down
ratioToMidi(2.0) // 12.0
// Dot syntax (SC-style):
12.midiToRatio // 2.0
(-12).midiToRatio // 0.5
2.0.ratioToMidi // 12.0
// In context — PitchShift driven from semitone intervals:
PitchShift.Audio(input: src, pitchRatio: 7.midiToRatio) // perfect fifth up
```
### Tempo / time
```swift
bpmToSeconds(120.0) // 0.5
secondsToBpm(0.5) // 120.0
hzToPeriod(440.0) // ~0.00227
periodToHz(0.00227) // ~440.0
```
### Mapping / equal-power
```swift
linToExp(knobValue, low: 200.0, high: 2000.0) // exponential sweep, low must be > 0
let (dryGain, wetGain) = equalPowerFade(0.5) // constant-power crossfade
```
### Array overloads
Every scalar function has a `[Double]` overload. All allocate — **not RT-safe**, language-side only.
```swift
midiToHz([60.0, 64.0, 67.0]) // [261.63, 329.63, 392.0]
ampToDb([1.0, 0.5, 0.25]) // [0.0, −6.02, −12.04]
semitonesToRatio([0.0, 12.0]) // [1.0, 2.0]
```
Full list: `midiToHz`, `hzToMidi`, `ampToDb`, `dbToAmp`, `powToDb`, `dbToPow`, `semitonesToRatio`, `ratioToSemitones`, `centsToRatio`, `ratioToCents`, `bpmToSeconds`, `secondsToBpm`, `hzToPeriod`, `periodToHz`.
---
## Waveshaping + Mapping
Eight audio-rate generators for waveshaping, clipping, boundary wrapping, and range mapping. All live in `Sources/Lyrebird/Generators/MathGenerators.swift`. All carry `MulAddSpec`.
Each generator has `.Audio` (per-sample) and `.Control` (block-rate, interpolated ramp) variants.
| Generator | Operation | Parameters |
|-----------|-----------|------------|
| `Tanh` | `tanh(signal)` | signal |
| `Pow` | `pow(signal, exp)` | signal, exp |
| `Clip` | `max(lo, min(hi, signal))` | signal, lo, hi |
| `Fold` | mirror-reflect at lo/hi | signal, lo, hi |
| `Wrap` | fmod-based wrap into [lo, hi) | signal, lo, hi |
| `SoftClip` | `tanh(signal × drive) / tanh(drive)` | signal, drive |
| `LinLin` | linear→linear range map | signal, inLo, inHi, outLo, outHi |
| `LinExp` | linear→exponential range map | signal, inLo, inHi, outLo, outHi |
**`Fold` algorithm:** while `signal < lo`: `lo + (lo − signal)`; while `signal > hi`: `hi − (signal − hi)`. Iterates until in range — handles multiple fold levels.
**`Wrap` algorithm:** `signal − floor((signal − lo) / (hi − lo)) × (hi − lo)` — correct for negative values.
**`LinExp` precondition:** `outLo > 0`. Matches `LyrebirdMusicMath.linToExp` at t = (signal − inLo) / (inHi − inLo).
```swift
let driven = SoftClip.Audio(osc, drive: 5.0)
let clipped = Clip.Audio(osc, lo: -0.5, hi: 0.5)
let folded = Fold.Audio(osc, lo: -0.7, hi: 0.7)
let freq = LinExp.Audio(lfo, inLo: -1.0, inHi: 1.0, outLo: 200.0, outHi: 2000.0)
let freqCR = LinExp.Control(env, inLo: 0.0, inHi: 1.0, outLo: 80.0, outHi: 8000.0)
```
---
## Dynamics
Five signal-processing generators for amplitude tracking, pitch detection, limiting, compression, and expansion. Full API reference: `docs/stdlib/dynamics.md`.
| Generator | Variants | Description |
|-----------|----------|-------------|
| `AmplitudeFollower` | Audio + Control | Envelope follower; asymmetric attack/release one-pole smoother |
| `FreqTracker` | Audio only | YIN-based pitch tracker; 2-channel out (Hz + confidence 0..1) |
| `LookAheadLimiter` | Audio only | True look-ahead limiter; no overshoot; `lookAheadTime` latency |
| `Compressor` | Audio + Control | Feed-forward compressor; threshold/ratio/attack/release/knee/makeup |
| `Expander` | Audio + Control | Downward expander/gate; mirrors `Compressor` below threshold |
All generators are single-channel in/out. Multi-channel use via MCE. `AmplitudeFollower`, `Compressor`, `Expander` conform to `GeneratorEnum`.
---
## Reverb — FreeVerb
### FreeVerb
Stereo reverb implementing the Freeverb algorithm (Jezar at Dreampoint, public domain).
Mono input → two-channel output (channel 0 = left, channel 1 = right).
**Architecture:** 8 parallel filtered-feedback comb filters → 4 series allpass filters per channel.
Left and right use different delay lengths (detuned by `spread` samples) for stereo width.
**File:** `Sources/Lyrebird/Generators/Reverb/FreeVerb.swift`
```swift
FreeVerb(source: sig) // defaults: roomSize=0.5, damping=0.5, mix=0.33
FreeVerb(source: sig, roomSize: 0.8, damping: 0.3, mix: 0.4)
FreeVerb(source: sig, roomSize: 0.7, mix: 0.5, spread: 23, sampleRate: 48000)
```
| Parameter | Range | Default | Notes |
|-----------|-------|---------|-------|
| `roomSize` | 0–1 | 0.5 | Maps to comb feedback 0.7–0.98 |
| `damping` | 0–1 | 0.5 | High-freq absorption in comb LP path |
| `mix` | 0–1 | 0.33 | Wet/dry blend; 0 = dry, 1 = fully wet |
| `spread` | samples | 23 | L/R delay detuning; fixed at init |
| `sampleRate` | Hz | 44100 | Scales delay buffers for your engine rate |
**Named channel aliases** (same pattern as `Pan2`):
```swift
let verb = FreeVerb(source: sig, roomSize: 0.8, mix: 0.4)
output(bus: 0, source: verb.left) // channel 0
output(bus: 1, source: verb.right) // channel 1
```
**Pass directly to `output(bus:source:)` for two-channel write:**
```swift
override func build() {
let src = OscSin.Audio(freq: 220.0) * 0.5
output(bus: 0, source: FreeVerb(source: src, roomSize: 0.75, mix: 0.35,
sampleRate: 44100))
}
```
**RT-allocation model:** All comb and allpass circular buffers pre-allocated in `init`.
No heap allocation in `_computeSamples`. Audio-only; no Control variant.
---
## Reverb — GVerb
### GVerb
Stereo algorithmic reverb implementing SC's `GVerb` UGen faithfully (Griesinger FDN algorithm).
Mono input → two-channel output (channel 0 = left, channel 1 = right).
**Architecture:**
1. Input one-pole LP damper (`inputBandwidth` controls bandwidth).
2. Pre-tap Schroeder allpass diffuser (shared L/R).
3. 4-tap fixed tap-delay (44000 samples) — early reflections `u[j]`.
4. 4-line FDN with negative feedback gains + one-pole LP damping — late tail `d[j]`.
5. Alternating-sign mix: `±(tail·d[j] + early·u[j]) + x·earlyLevel`.
6. 4×4 Hadamard matrix feedback.
7. 3-stage post-sum allpass diffusion per side (asymmetric L/R for stereo).
8. `out = lsum/rsum + x·dryLevel` (dry bypasses all diffusion).
**File:** `Sources/Lyrebird/Generators/Reverb/GVerb.swift`
```swift
GVerb(source: sig)
GVerb(source: sig, roomSize: 20.0, reverbTime: 4.0)
GVerb(source: sig, roomSize: 15.0, reverbTime: 3.0, damping: 0.5,
earlyLevel: 0.4, tailLevel: 0.5, dryLevel: 0.1, sampleRate: 48000)
```
| Parameter | Range | Default | Notes |
|-----------|-------|---------|-------|
| `roomSize` | 1–300 m | 30.0 | Scales FDN delay lengths and early tap positions. Block-rate. |
| `reverbTime` | 0.001–300 s | 5.0 | T60 decay; controls FDN feedback gains via `alpha`. Block-rate. |
| `damping` | 0–1 | 0.5 | FDN HF absorption (one-pole LP after each FDN read). |
| `spread` | any | 15.0 | **Init-time only.** Scales asymmetric L/R post-sum diffuser sizes. |
| `inputBandwidth` | 0–1 | 0.75 | Input LP bandwidth; 1.0 = flat. |
| `earlyLevel` | 0–1 | 0.4 | Early reflections + x·earlyLevel into mix sum (before diffusion). |
| `tailLevel` | 0–1 | 0.5 | Late reverb (FDN) output gain. |
| `dryLevel` | 0–1 | 0.0 | Dry bypass gain added after post-sum diffusion. |
| `sampleRate` | Hz | 44100 | Engine rate; scales pre-allocated FDN/tap buffers. |
**Named channel aliases** (same pattern as `FreeVerb`):
```swift
let verb = GVerb(source: sig, roomSize: 20.0, reverbTime: 4.0)
output(bus: 0, source: verb.left) // channel 0
output(bus: 1, source: verb.right) // channel 1
```
**RT-allocation model:** FDN and tap-delay circular buffers pre-allocated in `init` for `maxRoomSize = 300 m`.
Runtime `roomSize` / `reverbTime` changes update delay lengths and gains at block rate — no RT alloc.
Audio-only; no Control variant.
## Mouse Input Generators
The `Mouse.X` / `Mouse.Y` / `Mouse.Click` generators compile on every platform — they
read from a `MouseInputBridge` registered via `MouseInput.install(_:)`. When no bridge
is installed (iOS, headless macOS, unit tests) they output the no-op default constants
`0.5` (`X`/`Y`) and `0.0` (`Click`).
### MouseInputBridge / MouseInput
`MouseInputBridge` (`Sources/Lyrebird/Generators/UI/MouseInputBridge.swift`) is the
platform-neutral base class the Mouse generators read from. The base class returns
constants; subclasses override `x` / `y` / `button` (each `Double`) to expose live
input. `MouseInput.install(_:)` registers a bridge process-wide;
`MouseInput.uninstall()` restores the default. The lookup is one atomic-acquire load
plus one indirect call — RT-safe.
### MouseTracker (LyrebirdUI, macOS only)
`LyrebirdUI.MouseTracker` (`Sources/LyrebirdUI/MouseTracker.swift`) is a `MouseInputBridge`
subclass that installs `NSEvent` global monitors on the main thread and exposes the
results through lock-free `Synchronization.Atomic<Double>` fields. Wire it up at app
startup:
```swift
import LyrebirdSynth
import LyrebirdUI
MouseTracker.installShared()
```
**Files:** `Sources/Lyrebird/Generators/UI/Mouse.swift`,
`Sources/Lyrebird/Generators/UI/MouseInputBridge.swift`,
`Sources/LyrebirdUI/MouseTracker.swift`
### Mouse.X.Control
Normalized horizontal mouse position. Output range `[0.0, 1.0]`:
- `0.0` = left edge of main screen
- `1.0` = right edge of main screen
Ramps linearly from previous value to current position within each audio block.
```swift
Mouse.X.Control()
let freq = Mouse.X.Control() * 2000.0 + 200.0 // 200–2200 Hz
```
### Mouse.Y.Control
Normalized vertical mouse position. Output range `[0.0, 1.0]`:
- `0.0` = bottom edge of main screen
- `1.0` = top edge of main screen (screen Y coordinate is inverted)
Ramps linearly from previous value to current position within each audio block.
```swift
Mouse.Y.Control()
let amp = Mouse.Y.Control() // amplitude 0–1
```
### Mouse.Click.Control
Left mouse button state. Output:
- `0.0` = button released
- `1.0` = button held down
Ramps over one block on state change, avoiding clicks in driven audio signals.
```swift
Mouse.Click.Control()
let gate = Mouse.Click.Control()
let env = EnvelopeGen(envelope: Envelope([0,1,0], [0.01,0.5]), gate: gate)
```
### Composition example
```swift
// SC-style: x→freq, y→amp, click→gate
let osc = OscSin.Audio(
freq: Mouse.X.Control() * 400 + 100,
mul: Mouse.Y.Control()
) * Mouse.Click.Control()
```
**RT-allocation model:** No allocation on the RT thread. Each generator pre-allocates `_result`
at `init` and reads `MouseInput.current` (atomic-acquire + indirect dispatch) once per block.
Audio-rate variants are intentionally omitted: mouse HID rate (125–1000 Hz) is far below audio
sample rate, so per-sample reads would be identical within each block.
---
## Additional Oscillators
All band-limited oscillators below are paired (`Audio` + `Control`), conform to `GeneratorEnum`, and use the `OscBandLimitedHelpers` shared module. Defaults: `mul = 1.0`, `add = 0.0`. `freq` accepts any `ValidGeneratorInput` — generator inputs are read at audio rate for true FM/PM. `phase` is an init-only fraction of a cycle in `[0, 1)`.
### OscSawtooth
Band-limited sawtooth. Polynomial transition near each edge — no aliasing up to roughly `0.45·Fs`.
```swift
OscSawtooth.Audio(freq: 220.0)
OscSawtooth.Audio(freq: lfo, phase: 0.25, mul: 0.5)
```
### OscSquare
Band-limited square. Equivalent to two anti-aliased sawtooths offset by half a cycle.
```swift
OscSquare.Audio(freq: 110.0)
```
### OscTriangle
Band-limited triangle. Integrated band-limited square; -12 dB/octave harmonic rolloff.
```swift
OscTriangle.Audio(freq: 440.0)
```
### OscDutyCycle
Band-limited variable-pulse-width oscillator. `dutyCycle` ∈ `[0, 1]` continuously controls pulse width — `0.5` ≈ square. Generator inputs drive PWM at audio rate.
```swift
OscDutyCycle.Audio(freq: 220.0, dutyCycle: 0.3)
OscDutyCycle.Audio(freq: 220.0, dutyCycle: OscSin.Audio(freq: 0.5) * 0.4 + 0.5)
```
### LFSawtooth / LFSquare / LFTriangle / LFDutyCycle
Non-band-limited low-frequency variants for control-rate modulation and synth modulators. Cheaper than the `Osc*` family but alias when used in the audible range. `LFDutyCycle` takes a `dutyCycle` parameter like its band-limited counterpart.
```swift
LFSawtooth.Control(freq: 0.25) // 4-second sweep ramp
LFSquare.Audio(freq: 2.0) // sub-audio gate train
LFTriangle.Audio(freq: 4.0, mul: 0.1) // gentle tremolo LFO
LFDutyCycle.Audio(freq: 6.0, dutyCycle: 0.2)
```
### WavetableMorph
Linear-interpolation wavetable scanner across an array of equal-length mono `LyrebirdBuffer` tables. `position` ∈ `[0, table_count − 1]` selects between adjacent tables; fractional positions blend.
```swift
let tables: [LyrebirdBuffer] = [a, b, c, d] // four single-cycle waveforms
WavetableMorph.Audio(
tables: tables,
freq: 220.0,
position: LFSin.Audio(freq: 0.25) * 1.5 + 1.5, // sweeps 0..3
interpolation: .cubic
)
```
- All tables must share `count` (precondition at init).
- `interpolation` controls the **inner table read**; cross-table morphing is always linear.
- `phase` (any `ValidGeneratorInput`) supports per-sample audio-rate phase modulation.
---
## EnvelopePoll
Read a fixed-shape `Envelope` at arbitrary times. Output is the envelope's level at `time` seconds. No internal phase or trigger — purely a value lookup. Useful for driving filter cutoff curves, panning trajectories, or pattern-driven scoring.
```swift
let env = Envelope(levels: [0, 1, 0], duration: 1.0, curves: [0, -4])
EnvelopePoll.Control(envelope: env, time: phasor) // phasor in seconds
EnvelopePoll.Audio(envelope: env, time: 0.5) // constant 0.5 s into env
```
- `time` accepts any `ValidGeneratorInput`. Audio-rate input scans the envelope per sample (sample-accurate); block-rate input ramps from previous to current target.
- `levelScale`/`levelBias` apply a final affine map. Defaults `1.0`/`0.0`.
---
## Extended Filters
All filters in this section conform to `GeneratorEnum` (Audio + Control variants) unless noted Audio-only. `freq` and similar inputs accept any `ValidGeneratorInput` and are evaluated at audio rate per sample when supplied as a Generator. `mul`/`add` follow the standard `MulAddSpec` fast path.
### Butterworth Family
Cascaded biquad implementations of Nth-order Butterworth filters. Order ≥ 1; odd orders prepend a first-order section, even orders are pure biquad cascades.
```swift
ButterworthLowPass.Audio(input: sig, freq: 2000.0, order: 4) // -24 dB/oct LP
ButterworthHighPass.Audio(input: sig, freq: 100.0, order: 6) // -36 dB/oct HP
ButterworthBandPass.Audio(input: sig, freqLo: 400.0, freqHi: 4000.0, order: 4)
ButterworthBandReject.Audio(input: sig, freqLo: 220.0, freqHi: 880.0, order: 4)
```
- `order` is init-only; passing a `ValidGeneratorInput` for `freq` retunes coefficients via a lock-free SPSC queue (no allocation, no blocking).
- All four conform to `GeneratorEnum`.
### SVF — State Variable Filter
Single Chamberlin SVF stage with four simultaneous outputs available through the same instance.
```swift
SVF.Audio(input: sig, freq: 800.0, q: 0.707) // Butterworth Q
SVF.Audio(input: sig, freq: env, q: 4.0, mode: .bandpass)
```
- Modes: `.lowpass` (default), `.highpass`, `.bandpass`, `.notch`. Init-only.
- `q` defaults to `svfButterworthQ` (= 0.707).
- Audio-rate `freq` modulation supported; Chamberlin clamping ensures stability at the Nyquist limit.
### Lag Family — One-Pole Smoothers
`Lag`, `LagUpDown`, `Lag2`, `Lag2UpDown` provide symmetric and asymmetric exponential smoothing. Common for de-zippering control signals and CV smoothing.
```swift
Lag.Control(input: $cutoff, time: 0.05) // 50 ms RC smoother
LagUpDown.Control(input: $env, lagUp: 0.005, lagDown: 0.2) // fast attack / slow release
Lag2.Control(input: $sig, time: 0.05) // cascade of two Lag stages
Lag2UpDown.Control(input: $sig, lagUp: 0.01, lagDown: 0.3) // cascade asymmetric
```
- `time`, `lagUp`, `lagDown` are 60 dB time constants in seconds.
- All accept audio-rate inputs; coefficient recomputation per block.
### Decay / Decay2 / LeakDC
- **`Decay`**: One-pole exponential decay tail on each non-zero input sample. `decayTime` is the 60 dB decay time in seconds.
- **`Decay2`**: Differenced pair of Decays — produces a percussive attack-then-release envelope from an impulse train.
- **`LeakDC`**: One-pole DC-blocking high-pass. `coef` is the pole position in `[0, 1)`; `leakDCDefaultAudioCoef` (= 0.995) is a typical setting.
```swift
Decay.Audio(input: Impulse.Audio(freq: 4.0), decayTime: 0.3)
Decay2.Audio(input: trig, attackTime: 0.005, decayTime: 0.5)
LeakDC.Audio(input: sig) // default coef
```
### MoogLadder.Audio
2× oversampled four-pole Moog ladder. Audio-only.
```swift
MoogLadder.Audio(input: sig, freq: 1000.0, resonance: 0.8)
MoogLadder.Audio(input: sig, freq: $cutoff, resonance: 1.2, mul: 0.5)
```
- `freq` clamped to `moogLadderMinCutoffHz`; internal cutoff coefficient clamped at `moogLadderMaxCutoffCoeff` (≈ `0.45·Fs_os`).
- `resonance` is dimensionless ladder feedback gain (not RBJ Q), clamped to `moogLadderMaxResonance` (1.4). `1.0` ≈ self-oscillation threshold.
- 2× internal oversampling via shared `HalfbandUpsampler2x` / `HalfbandDownsampler2x`; total group delay 11 input-rate samples.
### ResonatorBank.Audio
Fixed-coefficient parallel resonator bank driven by a multi-channel `LyrebirdBuffer` of `(freq, decay, gain)` triples. Audio-only.
```swift
let buffer = LyrebirdBuffer(numChannels: 3, ...) // 3 channels: freq, decay, gain
// fill rows with N resonator specs
ResonatorBank.Audio(input: excitation, buffer: buffer)
```
- Buffer `channelCount` precondition: `resonatorBankChannelCount` (= 3).
- Each row is a complex resonator; bank is summed to mono output.
### MuTronIII.Audio / .Control
*See [MuTronIII](#mutroniii) under Filters above for full description.*
### Classic Delay-Based Filters
`CombFilter`, `AllpassFilter`, `ResonatingFilter`, `RingingFilter` are pre-`_Base`-pattern Audio-only generators retained for SC parity.
```swift
CombFilter(input: sig, maxDelay: 0.5, delay: 0.05, decayTime: 1.0, sampleRate: 44100.0)
AllpassFilter(input: sig, maxDelay: 0.5, delay: 0.03, decayTime: 0.8, sampleRate: 44100.0)
ResonatingFilter(input: noise, freq: 1000.0, decayTime: 0.5) // tuned ringing band
RingingFilter(input: trig, freq: 440.0, bandwidth: 80.0) // tuned ringing band, BW in Hz
```
- `Comb` / `Allpass` use a circular delay line allocated to `maxDelay × sampleRate`; `delay` and `decayTime` can be retuned per block. Feedback coefficient derives from the shared `combFeedbackCoeff(decayTime:delay:)` helper.
- `Resonating` and `Ringing` are biquads tuned by `freq` + (`decayTime` | `bandwidth`).
---
## Triggers
Edge-detected control primitives. A "trigger" fires on a `<= 0 → > 0` transition.
### Gate
Sample-and-hold whose held value updates whenever `trig` is non-zero. While `trig > 0`, output tracks `input`; when `trig ≤ 0`, output holds the last sampled value.
```swift
Gate.Audio(input: sig, trig: gateGen)
Gate.Control(input: $value, trig: $gate)
```
### SampleAndHold
Edge-triggered sample-and-hold. Captures the input value on each rising edge of `trig` and holds until the next edge.
```swift
SampleAndHold.Audio(input: sig, trig: Impulse.Audio(freq: 8.0))
SampleAndHold.Control(input: $cv, trig: clockTrig)
```
### SignalChanged
Outputs `1.0` for one block whenever `|input - prevInput| > threshold`, otherwise `0.0`. Useful as a trigger source from continuous control signals.
```swift
SignalChanged.Control(input: $cutoff, threshold: 0.01)
```
### SendTrigger
RT→language trigger sender; pairs with `TriggerListener`. Emits an event tagged with the integer `id` and a snapshot `value` whenever the `trig` input crosses `<= 0 → > 0`.
```swift
SendTrigger.Control(trig: onsetGen, id: 1)
SendTrigger.Control(trig: Impulse.Control(freq: 4.0), id: 7, value: $cutoff)
```
- `id` is `Int32`, init-only.
- Events delivered via the engine's lock-free `TriggerListener` queue.
---
## Random Generators
### Jitter
Continuous random walker with low-pass smoothing. Internal xorshift64 PRNG (seeded via `lyrebirdSeedXorshift64`).
```swift
Jitter.Control(center: 1.0, speed: 5.0, amount: 0.3) // 5 Hz wobble, ±30% around 1.0
Jitter.Audio(center: 220.0, speed: 8.0, amount: 50.0, // 50 Hz random detune
seed: 12345)
```
- `center` is the steady-state output value; `amount` is the ±deviation; `speed` is the rate (Hz) at which new random targets are drawn.
- Smoothed via cubic Hermite between target draws — output never jumps discontinuously.
### TriggeredRandom
Picks a new uniform random value in `[lo, hi]` on each rising edge of `trigger`, ramps to it over the following block.
```swift
TriggeredRandom.Control(trigger: clock, lo: 100.0, hi: 2000.0)
TriggeredRandom.Control(trigger: $tick, lo: -1.0, hi: 1.0, seed: 42)
```
---
## Granular Synthesis
Buffer-driven, oscillator-driven, FM, and input-grain synthesis. All use the shared `GranularBase` infrastructure: a fixed-capacity grain pool (default `lyrebirdGrainPoolSize` = 64), per-grain density-based triggering, optional per-grain pitch and time dispersion. Output is **mono** unless noted (use MCE for multi-channel spread).
### BufferGrain
Reads grains from a `LyrebirdBuffer` at sample-accurate positions.
```swift
BufferGrain.Audio(
buffer: bufferRef,
position: 0.5, positionSpread: 0.1,
duration: 0.08,
amp: 0.5,
pan: 0.0,
density: 50.0
)
```
- `position` in `[0, 1)` (normalized buffer position); `positionSpread` is the per-grain ± random offset.
- `density` triggers per second.
### SineGrain
Sine-window grain cloud. `freq` is the grain pitch.
```swift
SineGrain.Audio(freq: 440.0, amp: 0.4, duration: 0.05, density: 100.0)
```
### FMGrain
Per-grain FM synthesis. `carrierFreq` × `modFreq` × `modIndex` defines the grain's spectrum.
```swift
FMGrain.Audio(carrierFreq: 880.0, modFreq: 440.0, modIndex: 2.0,
amp: 0.3, duration: 0.1)
```
### InputGrain
Records live audio into a circular capture buffer, then triggers grains from arbitrary read positions. Use for "freeze" effects, stutter, micro-looping live input.
```swift
InputGrain.Audio(input: micIn, position: 0.1, positionSpread: 0.4,
duration: 0.15, density: 30.0)
```
- `position` is fractional offset back from the live write head; `positionSpread` randomises per-grain start.
### FormantGrain
Formant-FOF synthesis. Glottal source × bandwidth-shaped formant impulse trains. SC's `Formant` UGen equivalent.
```swift
FormantGrain.Audio(glottalFreq: 100.0, formantFreq: 700.0, bandwidth: 80.0)
```
- `octaviation` adds octave displacements; useful for vocal-fry / sub-octave textures.
### PitchShift.Audio / TuneablePitchShift.Audio (granular pitch shift)
Granular pitch shifters. `PitchShift.Audio` is the default SC-faithful 4-head SOLA primary; `TuneablePitchShift.Audio` is the dynamic grain-pool variant with tunable `overlap` and selectable grain-read `interpolation`. See `Sources/Lyrebird/Lyrebird.docc/Generators/PitchShifting.md` for full details.
```swift
PitchShift.Audio(input: mic, pitchRatio: 0.75, windowSize: 0.05) // SC-style 4-head, default
TuneablePitchShift.Audio(input: sig, pitchRatio: 1.5, overlap: 8) // tunable grain-pool variant
```
- `pitchRatio` clamped to `[0.25, 4.0]`. Live audio-rate ratio supported.
- `PitchShift.Audio` parameters: `windowSize`, `pitchDispersion`, `timeDispersion`, `captureSize`, `seed`, `mul`, `add`.
- `TuneablePitchShift.Audio` parameters: `windowSize`, `overlap` (default 8), `pitchDispersion`, `timeDispersion`, `captureSize`, `interpolation`, `seed`, `mul`, `add`.
### TimeStretch.Audio
Buffer-driven time-stretching granular reader. Independent control of playback position and pitch.
```swift
TimeStretch.Audio(buffer: buf, pos: phasor, pitchRatio: 1.0, windowSize: 0.1, overlap: 4)
```
- `pos` in `[0, 1)` (normalized buffer position). Drive with an `LFSaw` for stretched playback at arbitrary speed.
---
## Karplus-Strong
Plucked-string physical model with delay-line + lowpass-feedback topology. `freq` sets the delay length (`Fs / freq`); `feedback` controls decay; `coef` controls the lowpass-in-loop damping.
### KarplusStrong.Audio
Triggered version — `trigger` rising edge re-excites the string with the `exciter` signal.
```swift
KarplusStrong.Audio(
exciter: WhiteNoise.Audio() * 0.5,
trigger: Impulse.Audio(freq: 2.0),
freq: 220.0,
feedback: 0.995,
coef: 0.5,
sampleRate: engine.sampleRate,
maxDelayTime: 0.05
)
```
### GatedKarplusStrong.Audio
Gate-driven version — continuous excitation while `gate > 0`.
```swift
GatedKarplusStrong.Audio(
exciter: PinkNoise.Audio(),
gate: $note,
freq: 440.0,
feedback: 0.99, coef: 0.5,
sampleRate: engine.sampleRate,
maxDelayTime: 0.05
)
```
- Both: `maxDelayTime` is init-time only and bounds the delay-line buffer (size = `ceil(maxDelayTime · sampleRate)`).
---
## Modulation Effects
### Flanger.Audio
Short-delay (1–10 ms) modulated comb with optional feedback. Audio-only.
```swift
Flanger.Audio(input: sig, delayTime: 0.005, depth: 0.5, rate: 0.5,
feedback: 0.4, mix: 0.5)
```
- `delayTime` is the base delay (centred); `depth` ∈ `[0, 1]` scales the LFO modulation around it; `rate` is the LFO frequency in Hz.
- `feedback` ∈ `[-1, 1]` (negative = phase-inverted feedback for "metallic" flange).
- `mix` ∈ `[0, 1]` blends dry / wet.
- `maxDelayTime` init-only — sets the delay-line size.
### Chorus.Audio
Medium-delay (15–40 ms) modulated copy summed with the dry signal. Audio-only.
```swift
Chorus.Audio(input: sig, delayTime: 0.025, depth: 0.002, rate: 1.5, mix: 0.5)
```
### Phaser.Audio
Cascaded all-pass-filter chain with LFO-swept notches. Audio-only.
```swift
Phaser.Audio(input: sig, rate: 0.5, depth: 1.0, centerFreq: 800.0,
feedback: 0.4, stages: 6, mix: 0.5)
```
- `stages` is the all-pass cascade count (init-only); each stage adds one notch.
- `centerFreq` is the LFO sweep midpoint; `depth` ∈ `[0, 1]` scales the sweep range.
### Hilbert.Audio
Audio-rate 90° phase splitter (analytic-signal pair). Mono input → 2-row output: row 0 is the in-phase ("real") component, row 1 leads row 0 by approximately 90° across the audible range (~60 Hz – 20 kHz). Implementation: two parallel cascades of 4 second-order all-pass sections each (Niemitalo "4+4 8th-order" squared-pole design) with a 1-sample input delay on path A for group-delay alignment.
```swift
let h = Hilbert.Audio(input: sig)
output(bus: 0, source: h.real) // in-phase
output(bus: 1, source: h.imag) // 90°-leading quadrature
```
- Use for single-sideband modulation, frequency shifting, UHJ ambisonic encode/decode, envelope extraction, or any process needing a Hilbert pair.
- Approximate — practical SSB sideband suppression ≈ 30 dB. Low-frequency settling is slow (slowest pole at radius ≈ 0.9994 → τ ≈ 1500 samples at 44.1 kHz).
### FrequencyShifter.Audio
SSB Bode-style frequency shifter — adds `shiftHz` to every spectral component (inharmonic). Two-channel output: `.upper` (channel 0) and `.lower` (channel 1) sidebands. Built on `Hilbert.Audio`.
```swift
let f = FrequencyShifter.Audio(input: sig, shiftHz: 50.0, sampleRate: engine.sampleRate)
output(bus: 0, source: f.upper)
output(bus: 1, source: f.lower)
```
- `shiftHz` accepts audio-rate Generator inputs (Bode-style vibrato, ring-mod-like effects).
- See `docs/stdlib/generators.md` ↑ `PitchShifting.md` for the pitch-shifter vs frequency-shifter distinction.
### SpatialDistance.Audio
Acoustic-distance simulator: gain attenuation (inverse-square law), Doppler delay (propagation lag), and air absorption (frequency-dependent loss). Audio-only.
```swift
SpatialDistance.Audio(
input: source,
distance: $d, // metres
velocity: $v, // metres/sec along listener axis
referenceDistance: 1.0,
airAbsorptionCutoff: 16000.0,
speedOfSound: 343.0,
sampleRate: engine.sampleRate,
maxDelayTime: 1.0 // max one-second propagation buffer
)
```
- `distance` ≥ 0; `referenceDistance` is the gain = 1 reference. Both can modulate at audio rate.
- `velocity` modulates the propagation delay (Doppler).
- `airAbsorptionCutoff` Hz controls the one-pole LP that grows steeper with distance.
---
## Physical Models
STK-derived single-voice physical models. All take `sampleRate` and `maxDelayTime` as init-only sizing parameters; `freq` and timbral parameters accept audio-rate Generator inputs.
### BowedString.Audio
Bowed-string model after McIntyre/Schumacher/Woodhouse. Single voice, mono.
```swift
BowedString.Audio(
freq: 220.0,
bowVelocity: 0.5,
bowForce: 3.0,
bowPosition: 0.127,
sampleRate: engine.sampleRate,
maxDelayTime: 0.005
)
```
- `bowPosition` is fractional string length where the bow contacts (typical 0.05–0.2).
### Flute.Audio
Cook/Smith waveguide flute. Jet at one end, end-reflection at the other.
```swift
Flute.Audio(
freq: 440.0,
breathPressure: 0.5,
noiseGain: 0.03,
jetRatio: 0.32,
jetReflection: 0.5,
endReflection: 0.5,
sampleRate: engine.sampleRate,
maxDelayTime: 0.01
)
```
- `breathPressure` is the steady-state DC component of the jet; `noiseGain` scales the additive turbulence noise.
- `jetRatio` is the embouchure-jet length ratio; `jetReflection`/`endReflection` are tube-end reflection coefficients.
### Clarinet.Audio
Cook/Smith waveguide clarinet. Reed-driven nonlinear excitation.
```swift
Clarinet.Audio(
freq: 220.0,
breathPressure: 0.6,
reedStiffness: -0.44,
noiseGain: 0.03,
sampleRate: engine.sampleRate,
maxDelayTime: 0.01
)
```
- `reedStiffness` is the reed table's nonlinear coefficient; typical values around `-0.4` to `-0.5`.
### ScannedSynthesizer.Audio
Mathews/Verplank 1D mass-spring scanned synthesis. N coupled masses on a ring; a per-sample phasor scans the ring as a wavetable. Audio-only, no `.Control`.
```swift
ScannedSynthesizer.Audio(
excitation: Impulse.Audio(freq: 1.0),
freq: 220.0,
massCount: 64, // power of two ≤ 1024
stiffness: 200.0,
damping: 0.05,
centeringForce: 1.0,
excitationIndex: 0,
initialDisplacement: .gaussian,
sampleRate: engine.sampleRate
)
```
- `initialDisplacement`: `ScannedSynthesizerShape` enum — `.gaussian` (default) / `.sine` / `.impulse` / `.zeros`.
- `excitation` is injected at `excitationIndex`'s mass once per block; `freq` sets the phasor read rate against the ring.
---
## Additional Reverbs
### ConvolutionReverb.Audio
Partitioned FFT convolution against a stored impulse response. Audio-only, mono in / mono out.
```swift
let ir = LyrebirdBuffer(count: 88200) // 2-second IR @ 44.1 k
// ... load ir.fillFromFile / AIFF ...
ConvolutionReverb.Audio(input: src, ir: ir, partitionSize: 1024, mix: 0.3)
```
- `partitionSize` is the FFT block size, init-only, power of two in `[4, convolutionReverbMaxPartitionSize]`.
- IR longer than `partitionSize` is split into N partitions and convolved with the live STFT chain.
- `mix` is wet/dry blend.
### SpringReverb.Audio
Caltech-style spring-tank model — cascaded chirped allpass network with damping and nonlinear excitation. Single-channel by default; stereo via `stereo: true`.
```swift
SpringReverb.Audio(input: sig, decay: 2.0, tension: 0.5, damping: 0.3, mix: 0.3)
SpringReverb.Audio(input: sig, decay: 3.0, stereo: true) // stereo 2-channel out
```
- `decay` in seconds; `tension` ∈ `[0, 1]` shifts the spring chirp pitch; `damping` ∈ `[0, 1]` controls high-frequency absorption.
- `preDelay` is init-only.
### PlateReverb.Audio
Dattorro plate reverb model. Stereo 2-channel output. Audio-only.
```swift
PlateReverb.Audio(input: sig, decay: 0.7, bandwidth: 0.9995, damping: 0.0005,
modDepth: 0.5, modRate: 1.0, mix: 0.3)
output(bus: 0, source: plate.left)
output(bus: 1, source: plate.right)
```
- `bandwidth` ∈ `[0, 1]` — input one-pole LP coefficient (`0.9995` ≈ flat).
- `damping` ∈ `[0, 1]` — in-loop one-pole damping per tank.
- `modDepth` × `modRate` modulates the internal tank delays (chorus-like dispersion).
- `preDelay` accepts `ValidGeneratorInput`; ≤ a fixed pre-allocated max.
---
## Disk I/O
### DiskIn.Audio
Streams audio frames from a file URL. Throwing init — fails on invalid URL, format mismatch, or unreadable file.
```swift
let url = URL(fileURLWithPath: "/path/to/loop.wav")
let player = try DiskIn.Audio(
url: url,
channelCount: 2,
sampleRate: engine.sampleRate,
rate: 1.0, // 1.0 = native pitch, audio-rate Generator OK
loop: true,
doneAction: .freeSynth, // node-tree action when EOF hit (loop=false)
bufferFrames: 8192
)
output(bus: 0, source: player)
```
- Reads in a background thread; RT pulls from a lock-free SPSC queue. `bufferFrames` sizes the pre-read buffer.
- `rate` accepts Generator inputs for varispeed playback.
- `doneAction` mirrors SC node-tree actions: `.nothing` / `.freeSynth` / `.pause` / `.releaseNode(n)`. See `Sources/Lyrebird/Generators/BufferIO/DiskInError.swift` for error cases.
### DiskOut.Audio
Streams `source` audio to a file URL. Throwing init.
```swift
let url = URL(fileURLWithPath: "/tmp/rendered.wav")
let writer = try DiskOut.Audio(
source: masterMix,
channelCount: 2,
url: url,
sampleRate: engine.sampleRate,
format: .wavFloat32, // .aiff / .wavFloat32 / .wavInt16 / .wavInt24 / .aiffFloat32
bufferFrames: 8192
)
```
- Format encoded by `DiskOutFormat` enum (file extension + sample format).
- Writes from a background thread; RT pushes to a lock-free SPSC queue.
---
## Panning Extensions
`Pan2` is covered earlier under Implemented. The 4-speaker family is built around an
open `Pan4` base class (output-buffer infrastructure, `mul` / `add`, named
channel aliases). Four concrete subclasses pick the coordinate system and
whether distance shaping is applied:
| Subclass | Coordinates | Distance modelling |
|----------|-------------|--------------------|
| `PanAz` | polar — azimuth radians, position fixed to unit-square boundary | none |
| `PanAzDistance` | polar — azimuth + radial distance | `1/d` amp + air-absorption LP + Doppler past `distance = 1` |
| `PanXY` | cartesian — `x`, `y ∈ [-1, 1]` | none |
| `PanXYDistance` | cartesian — `x`, `y` with Chebyshev distance metric | `1/d` amp + air-absorption LP + Doppler past `max(|x|, |y|) = 1` |
Speaker layout (channel order shared across all four): 0 = front-left, 1 =
front-right, 2 = rear-right, 3 = rear-left. Named aliases (`frontLeft`,
`frontRight`, `rearRight`, `rearLeft`) are inherited from `Pan4` by every
subclass.
### PanAz
Polar 4-speaker pan. `azimuth` (radians) — `0` is front centre, `π/2` is
right side, `π` is rear centre, `-π/2` is left. The angle is projected onto
the unit-square boundary so that `±π/4` and `±3π/4` land exactly on the
speaker corners. `azimuth` is a `@LiveParam`; values wrap modulo `2π`.
```swift
let q = PanAz(input: sig)
q.azimuth = .pi / 4 // RF corner
output(buses: [0, 1, 2, 3], source: q)
```
### PanAzDistance
Polar pan with full distance model. `azimuth` (radians) + `distance`
(unitless: `0` = listener, `1` = speaker plane, `> 1` = beyond) + `velocity`
(m/s) all accept any `ValidGeneratorInput`. Inside the unit boundary the
generator passes through to `PanAz` semantics; outside, applies
`1 / |distance|` amplitude, air-absorption lowpass with cutoff `∝ (1/d)²`,
and a velocity-driven Doppler delay line. Structural params
(`airAbsorptionCutoff`, `speedOfSound`, `sampleRate`, `maxDelayTime`)
match `SpatialDistance`.
```swift
PanAzDistance(input: sig, azimuth: $az, distance: $r, velocity: $vel,
sampleRate: 44100)
```
### PanXY
Cartesian 4-speaker pan. `x` (left/right, `[-1, 1]`) and `y` (rear/front,
`[-1, 1]`) are `@LiveParam` properties. Values are clamped per sample.
Power invariant `LF² + RF² + RR² + LR² = 1` everywhere.
```swift
let q = PanXY(input: sig)
q.x = -0.5 // mostly left
q.y = 0.8 // mostly front
output(buses: [0, 1, 2, 3], source: q)
```
### PanXYDistance
Cartesian pan with full distance model engaged when `max(|x|, |y|) > 1`.
Chebyshev metric — the unit-square corner `(1, 1)` is hard-RF (no √2
attenuation). Same `airAbsorptionCutoff` / `speedOfSound` / `sampleRate` /
`maxDelayTime` parameters as `PanAzDistance` / `SpatialDistance`. Distance
shaping is applied to the mono signal once before panning to avoid
per-channel phase decorrelation.
```swift
PanXYDistance(input: sig, x: $x, y: $y, velocity: $vel, sampleRate: 44100)
```
### PanN
N-channel equal-power pan. `position` ∈ `[-1, 1]` maps linearly across the `channels`-wide speaker ring.
```swift
PanN(input: sig, channels: 6, position: $pan)
```
- `channels` ≥ 2, init-only.
- `position` accepts audio-rate Generator inputs.
### AmbiEncoder1
First-order Ambisonics encoder. Mono input → 4-channel `W, X, Y, Z` output. `azimuth` and `elevation` are `any ValidGeneratorInput` — scalar `Double`, audio-rate Generator, or `ParameterNode` (via `$liveParam`). The source can move continuously in space at audio rate.
```swift
// Static placement:
AmbiEncoder1(input: sig, azimuth: .pi / 4, elevation: 0.0)
// Continuously moving source (azimuth swept by an LFO):
let sweep = LFSaw.Audio(freq: 0.1, mul: .pi)
AmbiEncoder1(input: sig, azimuth: sweep, elevation: 0.0)
// Live-parameter control:
// @LiveParam var az: Double = 0.0
AmbiEncoder1(input: sig, azimuth: $az, elevation: 0.0)
```
### AmbiDecoder1
First-order Ambisonics decoder. 4-channel `W, X, Y, Z` input → N-channel speaker output. Speaker layout passed as `[(az: Double, el: Double)]` tuples (radians).
```swift
let speakers = [
(az: 0.0, el: 0.0),
(az: .pi * 0.5, el: 0.0),
(az: .pi, el: 0.0),
(az: .pi * 1.5, el: 0.0)
]
AmbiDecoder1(input: encoded, speakers: speakers)
```
- Input must have `outputChannelCount == 4` (precondition).
### AmbiSpeakerLayout
Non-RT helper that builds `[(az: Double, el: Double)]` arrays for the common symmetric rigs, so callers don't have to hand-write tuples for every layout. Caseless enum with static methods; returns a fresh `Array` of tuples ready to pass straight to `AmbiDecoder1(input:speakers:)`.
Single-ring presets place N speakers evenly around the horizontal plane (`el = 0`):
| Method | Speakers |
|---|---|
| `AmbiSpeakerLayout.quad()` | 4 |
| `AmbiSpeakerLayout.hexagon()` | 6 |
| `AmbiSpeakerLayout.octagon()` | 8 |
Double-ring presets stack two aligned rings — upper at `+elevation`, lower at `-elevation`:
| Method | Speakers |
|---|---|
| `AmbiSpeakerLayout.cube(elevation:)` | 8 (4 + 4) |
| `AmbiSpeakerLayout.doubleHexagon(elevation:)` | 12 (6 + 6) |
| `AmbiSpeakerLayout.doubleOctagon(elevation:)` | 16 (8 + 8) |
General form `stackedRings(vertices:layers:elevation:azimuthOffset:)` covers any `vertices × layers` configuration — `layers == 1` → single ring at `el = 0`; `layers == 2` → `[+e, -e]`; `layers == 3` → `[+e, 0, -e]`; `layers ≥ 4` → even step `2e/(layers - 1)`. All preset methods delegate to it.
Every method accepts an optional `azimuthOffset: Double = 0` (radians) that rotates every ring uniformly. Pass `.pi / Double(N)` for a symmetric front-pair rig (no speaker pointing straight ahead).
```swift
let enc = AmbiEncoder1(input: sig, azimuth: $az, elevation: $el)
let quad = AmbiDecoder1(input: enc, speakers: AmbiSpeakerLayout.quad())
let oct = AmbiDecoder1(input: enc,
speakers: AmbiSpeakerLayout.octagon(azimuthOffset: .pi / 8))
let cube = AmbiDecoder1(input: enc,
speakers: AmbiSpeakerLayout.cube(elevation: .pi / 6))
// Arbitrary stack — 7 vertices, 2 layers:
let rig = AmbiDecoder1(
input: enc,
speakers: AmbiSpeakerLayout.stackedRings(vertices: 7, layers: 2,
elevation: .pi / 6)
)
```
- Helper is non-RT — call at synth-graph build time only.
- For a true geometric cube (vertices on the unit sphere) pass `elevation: asin(1.0 / 3.0.squareRoot())` ≈ `0.6155`.
- `stackedRings` precondition-traps on `vertices < 3` or `layers < 1`.
### AmbiDecoderStereo
Headphone-friendly pseudo-stereo decoder (Keating method). 4-row B-format `[W, X, Y, Z]` → 2-row L/R. Empirical matrix `L = W + 0.35·X + 0.61·Y`, `R = W + 0.35·X − 0.61·Y`. Z silently dropped.
```swift
let enc = AmbiEncoder1(input: source, azimuth: az, elevation: el)
let dec = AmbiDecoderStereo(input: enc)
output(buses: [0, 1], source: dec)
```
- Input must report `outputChannelCount == 4`.
- For full HRTF binauralisation use a proper binaural decoder from the `LyrebirdATK` extension package.
### AmbiEncoderStereo
Stereo source encoder. L/R mono pair + `spread` angle → 4-row B-format. Equivalent to two `AmbiEncoder1` instances at `(±spread, 0)` summed. Z output is always silent.
```swift
// Static spread:
let bformat = AmbiEncoderStereo(left: leftMic, right: rightMic, spread: .pi / 4)
output(buses: Array(0..<4), source: bformat)
// Modulated spread (slow LFO between mono sum and wide image):
let lfo = LFSaw.Audio(freq: 0.1, mul: .pi / 4, add: .pi / 4)
let breathing = AmbiEncoderStereo(left: leftMic, right: rightMic, spread: lfo)
```
- `spread` is `any ValidGeneratorInput` — scalar `Double`, audio-rate Generator, or `ParameterNode`.
- `spread` in radians. `0` = centred mono sum, `π/4` = ±45° (typical), `π/2` = ±90° hard L/R.
### AmbiDecoderMono
Virtual-microphone mono decoder. 4-row B-format → 1-row output via fixed look direction (`azimuth`, `elevation`) and pickup-pattern coefficient. Formula:
```
out = (1 − pattern/2) · √2 · W
+ (pattern/2) · ( cos(az)·cos(el)·X + sin(az)·cos(el)·Y + sin(el)·Z )
```
| `pattern` | Mic |
|---|---|
| `0.0` | Omni |
| `0.5` | Subcardioid |
| `1.0` | Cardioid |
| `1.5` | Supercardioid / hypercardioid |
| `2.0` | Figure-8 |
```swift
let cardioidFront = AmbiDecoderMono(input: bformat, azimuth: 0, elevation: 0, pattern: 1.0)
output(bus: 0, source: cardioidFront)
```
- All three parameters fixed at init (constant gain matrix). For audio-rate steering, route through two `AmbiEncoder1` instances + a custom dot-product generator.
- Use multiple instances to extract directional mixes from one ambisonic field.
### AmbiBToA / AmbiAToB — soundfield ↔ capsule conversion
Two-way conversion between 4-row B-format `[W, X, Y, Z]` and 4-row tetrahedral A-format `[LFU, RFD, LBD, RBU]` (`AmbiAFormatCapsule` enum lists the index/direction map). Use to decompose a soundfield into per-capsule streams for processing (compression, EQ, distortion, etc.) before recomposing.
Matrices (with `0.5` scale folded in):
```
A → B: B → A:
W = 0.5·(LFU + RFD + LBD + RBU) LFU = 0.5·(W + X + Y + Z)
X = 0.5·(LFU + RFD − LBD − RBU) RFD = 0.5·(W + X − Y − Z)
Y = 0.5·(LFU − RFD + LBD − RBU) LBD = 0.5·(W − X + Y − Z)
Z = 0.5·(LFU − RFD − LBD + RBU) RBU = 0.5·(W − X − Y + Z)
```
```swift
let aFormat = AmbiBToA(input: bformat)
// ... per-capsule processing here ...
let processedBFormat = AmbiAToB(input: processedAFormat)
```
- Round trip `B → A → B` (or `A → B → A`) is bit-identical (orthogonal 4×4 matrix × `0.25` scale composes to identity).
- Both classes precondition `input.outputChannelCount == 4`.
### AmbiEncoderUHJ
B-format → UHJ stereo encoder. 4-row B-format `[W, X, Y, Z]` → 2-row UHJ-compatible stereo. UHJ plays back on conventional stereo equipment and can be decoded back to (horizontal-plane) B-format with ``AmbiDecoderUHJ``. Z is silently dropped — UHJ carries no height.
Per Gerzon 1985:
```
L = 0.5 · ( 0.9397·W − j·0.342·W + 0.1856·X + j·0.5099·X + 0.655·Y )
R = 0.5 · ( 0.9397·W + j·0.342·W + 0.1856·X − j·0.5099·X − 0.655·Y )
```
`j` denotes a Hilbert 90° quadrature component. Three internal `Hilbert.Audio` instances (one per W/X/Y) supply the in-phase + quadrature signals; Y consumes only the in-phase output but still passes through a Hilbert cascade so its group delay matches W and X.
```swift
let bformat = AmbiEncoder1(input: source, azimuth: az, elevation: el)
let uhj = AmbiEncoderUHJ(input: bformat)
output(bus: 0, source: uhj[0]) // L
output(bus: 1, source: uhj[1]) // R
```
- Input must report `outputChannelCount == 4`.
- Sample-by-sample equality L = R for a centred (Y=0) source does NOT hold — the quadrature components have fixed signs between L and R. Energy is balanced (RMS(L) ≈ RMS(R)) within Hilbert phase-error tolerance.
### AmbiDecoderUHJ
UHJ stereo → B-format decoder. 2-row UHJ stereo → 4-row B-format with Z written silent (so the result drops straight into ``AmbiDecoder1``).
Per Gerzon 1985:
```
W = 0.5 · ( 0.982·L + 0.982·R + j·0.164·L − j·0.164·R )
X = 0.5 · ( 0.419·L + 0.419·R − j·0.828·L + j·0.828·R )
Y = 0.5 · ( 0.763·L − 0.763·R + j·0.385·L + j·0.385·R )
Z = 0
```
Two internal `Hilbert.Audio` instances (one per L/R) supply the matrix's quadrature terms.
```swift
let bformat = AmbiDecoderUHJ(input: uhjStereo)
let dec = AmbiDecoder1(input: bformat, speakers: AmbiSpeakerLayout.quad())
output(buses: Array(0..<4), source: dec)
```
- Input must report `outputChannelCount == 2`.
- `mul`/`add` apply to all 4 rows including the silent Z (Z becomes `0 · mul + add = add`).
---
## Ambisonic Toolkit (ATK FOA) — external package
The full SuperCollider Ambisonic Toolkit FOA UGen set (encoder, 20 single-angle soundfield transforms, 3 dominance transforms, 3 filters, 4 decoders incl. binaural) lives in the **separate `LyrebirdATK` package**, not in core Lyrebird. Add it to your `Package.swift` alongside the Lyrebird dependency and `import LyrebirdATK`. Authoritative reference: `docs/ATK-Guide.md` inside the LyrebirdATK repository.
LyrebirdATK is the worked example for the [Extension SDK](../protocols/extension-sdk.md) — see that doc and the upcoming `docs/extension-authors-guide.md` for how out-of-tree Generator packages depend on Lyrebird via SwiftPM.
The minimal `AmbiEncoder1` / `AmbiDecoder1` panning generators above remain in core; they predate the ATK extraction and are unrelated to the `Foa*` UGen set.
---
## AdditiveSynthesizer
Plays a `SpectralFrameBuffer` as sinusoidal partials directly (additive resynthesis, no IFFT). Reads `position` ∈ `[0, frameCount)` and interpolates between consecutive frames.
```swift
let frameBuffer = SpectralFrameBuffer(fftSize: 2048, frameCount: 1024)
// ... fill from analysis or file ...
AdditiveSynthesizer(
frameBuffer: frameBuffer,
position: phasor, // 0..frameCount, drives playback through frames
maxPartials: 0 // 0 = all bins; positive caps to highest-N partials
)
```
- `maxPartials` is init-only. `0` (default) plays every spectral bin; non-zero caps the partial count to the loudest-N bins per frame.
- `position` accepts audio-rate Generator inputs for scrubbing / time-warping.
---
## Gendy — Dynamic Stochastic Synthesis (Xenakis)
Xenakis's GENDY algorithm — randomly-walked control points define a closed waveform whose amplitude and duration distributions can be reshaped per-segment. `Gendy1`/`Gendy2`/`Gendy3` mirror SC's three variants.
### Gendy1.Audio
Per-control-point amplitude + duration random walks, each with a selectable distribution kind.
```swift
Gendy1.Audio(
ampdist: .gauss, durdist: .gauss,
adparam: 1.0, ddparam: 1.0,
minfreq: 220.0, maxfreq: 660.0,
ampscale: 0.5, durscale: 0.5,
initCPs: 12,
knum: 12.0
)
```
- `ampdist` / `durdist` use `DistributionKind`: `.linear` / `.cauchy` / `.logist` / `.hyperbcos` / `.arcsine` / `.expon` / `.gauss` / `.poisson`.
- `adparam` / `ddparam` are distribution shape parameters (kind-specific).
- `initCPs` is init-only — max control-point count; `knum` is the active count (audio-rate).
### Gendy2.Audio / Gendy3.Audio
Variant deterministic-walk formulations of the same algorithm with different recursion kernels — see `Sources/Lyrebird/Generators/Gendy/`.
---
## Spectral Pipeline
The spectral system is a single audio-rate Generator, `SpectralChain.Audio`, that owns analysis + processor chain + IFFT bank. It populates a shared `SpectralBuffer` polar frame, runs registered `SpectralProcessor` transforms after each FFT hop, and resynthesises audio via overlap-add. Full reference: `docs/stdlib/spectral.md`. Brief catalog below.
### SpectralChain.Audio
Consolidated STFT pipeline. Four operating modes:
```swift
// Mono resynthesis: audio in → stages → audio out
let chain = SpectralChain.Audio(
input: sig,
fftSize: 2048,
hopSize: 512,
stages: [
.mono(pitchShift),
.mono(formantShift),
.mono(freeze),
.dual(crossMap, sideChain: sideChain),
]
)
output(bus: 0, source: chain)
// Analyze-only (no IFFT, silent audio) — feeds spectral feature extractors
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512,
analyzeOnly: true)
// Mono → N fan-out (e.g. decorrelated stereo) via SpectralFanOutProcessor
let stereo = SpectralChain.Audio(input: monoIn, fftSize: 2048,
fanOut: SpectralStereoDiffuse(amount: 0.8))
// Synth-only — IFFT bank driven by a SpectralBufferGenerator
let player = SpectralPlayBuffer(frameBuffer: frames, fftSize: 2048, hopSize: 512)
let synth = SpectralChain.Audio(spectralSource: player)
```
- `fftSize` power of two ≥ 4; `hopSize` ∈ `[1, fftSize]`.
- `stages` is an ordered list of ``SpectralStage`` entries. Use `.mono(p)` to wrap a single-buffer `SpectralProcessor`; use `.dual(p, sideChain: s)` to wrap a `SpectralProcessor2` together with its paired side-chain `SpectralChain.Audio`. Stages run in the order given.
- Output latency is `hopSize` samples (one hop) — block 0 silent, block 1 emits the first IFFT result.
- Synthesis window pre-scaled by WOLA normalisation; default sine window gives per-sample unity-gain reconstruction at 50% overlap.
### SpectralFreeze
Continuous frame freeze. While frozen, holds magnitudes and advances synthesis phase at each bin's last-computed instantaneous frequency. Atomic `freeze()` / `unfreeze()`.
```swift
let freeze = SpectralFreeze(fftSize: 2048)
let chain = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512,
stages: [.mono(freeze)])
// later, from any thread:
freeze.freeze() // capture current frame, hold spectrum
freeze.unfreeze() // resume live analysis
```
### SpectralPlayBuffer / SpectralRecordBuffer / SpectralBufferRead
Record a chain into a `SpectralFrameBuffer` for offline playback, or play back from one. `SpectralPlayBuffer` and `SpectralBufferRead` conform to `SpectralBufferGenerator` and drive `SpectralChain.Audio`'s synthOnly mode directly.
```swift
let frames = SpectralFrameBuffer(fftSize: 2048, frameCount: 256)
// Record into frames
let rec = SpectralRecordBuffer(frameBuffer: frames, loop: false)
let recChain = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512,
stages: [.mono(rec)], analyzeOnly: true)
rec.run = true // start recording
// Later, play back via synthOnly mode
let player = SpectralPlayBuffer(
frameBuffer: frames, fftSize: 2048, hopSize: 512,
rate: 1.0, startPos: 0.0, loop: true
)
let synth = SpectralChain.Audio(spectralSource: player)
```
### SpectralPitchShift / SpectralFormantShift
Phase-vocoder pitch shifter and magnitude-envelope-preserving formant shifter — pair to decouple pitch from formants.
```swift
let ps = SpectralPitchShift(fftSize: 2048, hopSize: 512, pitchRatio: 0.5) // -1 octave
let fs = SpectralFormantShift(fftSize: 2048, shiftRatio: 2.0) // formants ×2 to compensate
SpectralChain.Audio(input: voice, fftSize: 2048, hopSize: 512,
stages: [.mono(ps), .mono(fs)])
```
- `pitchRatio` / `shiftRatio` are `Atomic<Float>`, clamped `[0.25, 4.0]`. Live retunable from any thread.
- `SpectralFormantShift` envelope-estimation: `.cepstral` (default) or `.magnitudeSmoothing(radiusBins:)`. See `docs/stdlib/spectral.md`.
### Spectral filter / phase / magnitude processors
| Processor | Operation | Live params |
|-----------|-----------|-------------|
| `SpectralBrickwall` | Hard low/high/band/notch via `vDSP_vclr` outside passband | `lowHz`, `highHz` |
| `SpectralPhaseShift` | Rotate every bin's phase (Hilbert-like) | `radians` (for `.radians` case) |
| `SpectralGate` | Per-bin gate; below `threshold` × `floor` blend | `threshold`, `floor` |
| `SpectralTilt` | dB/octave slope around pivot Hz (init-only) | — |
| `SpectralBlur` | Magnitude box blur (running sum, O(halfSize)) | `radius` |
| `SpectralDiffuse` | Continuous phase randomisation 0→1 | `amount` |
| `SpectralConvolve` | Frequency-domain complex multiply with second buffer | — |
| `SpectralBinDelay` | Per-bin delay + per-bin feedback ring of frames | per-bin (init buffers) |
| `SpectralNoiseFilter` / `SpectralPartialFilter` | Multi-frame rolling-average bin classification | `threshold` |
| `SpectralHarmonicEnhance` | Boost harmonics of an estimated fundamental | `ratio`, `strength`, `numPartials` |
| `SpectralMagnitudeMap` | Apply a transfer curve to normalised magnitudes | — |
| `SpectralMagnitudeScale` | Global magnitude multiplier | `scale` |
| `SpectralCrossMap` | Cross-synthesis with side-chain analysis | `freeze`, `floor`, `mode` |
Full descriptions of each filter / phase / magnitude processor in `docs/stdlib/spectral.md` § "Spectral Filtering & Phase".
### Spectral metric generators
Pull-based control-rate readers of the live `spectralBuffer`. Each is a `ControlGenerator` returning one or two scalars per block.
| Generator | Output | Description |
|-----------|--------|-------------|
| `SpectralCentroid.Control` | Hz | Centre-of-mass of the magnitude spectrum |
| `SpectralSpread.Control` | Hz | RMS deviation about the centroid |
| `SpectralFlatness.Control` | 0..1 | Geometric / arithmetic mean ratio (noise-like ≈ 1, tonal ≈ 0) |
| `SpectralEntropy.Control` | bits | Shannon entropy of normalised magnitudes |
| `SpectralRolloff.Control` | Hz | Frequency below which `pct` of total energy lies |
| `SpectralFlux.Control` | unit | Half-rectified frame-to-frame magnitude delta |
| `OnsetDetector.Control` | 0/1 trigger | Onset edge from a chosen detection method |
```swift
let analysis = SpectralChain.Audio(input: sig, fftSize: 2048, hopSize: 512,
analyzeOnly: true)
let centroid = SpectralCentroid.Control(analysis: analysis, sampleRate: 48_000)
let flatness = SpectralFlatness.Control(analysis: analysis)
let onset = OnsetDetector.Control(analysis: analysis, method: .spectralFlux,
threshold: 0.3)
```
- All read `analysis.spectralBuffer` after analysis runs each hop.
- `OnsetDetector` exposes `OnsetDetectionMethod` enum (`.spectralFlux`, `.complexDomain`, etc.); fires `1.0` for one block at each detected onset.
---