# 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`, `Phasor`, `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`, `Trig`, `Trig1`, `TriggeredDelay`, `PulseCount`, `Stepper`, `Schmidt`, `Slew`, `ZeroCrossing`, `Slope`, `RunningMin`, `RunningMax`, `CrossFade`, `LinearCrossFade`, `Select`, `Waveshaper`, `CrossoverDistortion`, `Formlet`, `LFGauss`, `LorenzLinear`, `HenonStepped`, `QuadStepped`, `LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`, `LatoocarfianStepped`, `CuspStepped`) 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 `[[Double](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 `Double` value from the main thread to the RT audio thread through a lock-free `Atomic`. 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: Double = 440.0 // $freq is a ParameterNode @LiveParam var amp: Double = 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` 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** (a `Double`/`Int` literal) 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: `Double` 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 Double(i) / Double(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: `Double` 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: LFCurveNoise.Audio(freq: 0.4) * 0.5 + 0.5, // animated X y: LFCurveNoise.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: `Double` phase accumulator. #### Phasor Linear phase accumulator (ramp generator). Equivalent to SuperCollider `Phasor`. Accumulates `rate` units per sample within the half-open range `[start, end)`. On a ≤0 → >0 rising edge of `trig`, phase resets to `resetPos`. ```swift Phasor.Audio() // default: ramp 0..1 at 1/sample Phasor.Audio(rate: 440.0 * 1024.0 / 44100.0, start: 0, end: 1024) // 1024-sample wavetable scan at 440 Hz Phasor.Audio(trig: Impulse.Audio(freq: 2.0), rate: 0.01, resetPos: 0) // reset on trigger Phasor.Control(rate: 0.001) // slow ramp at control rate ``` - `rate` is the **per-sample phase increment** (not Hz). For table scanning: `rate = freq * tableSize / sampleRate`. - `start` / `end` define the half-open range `[start, end)`. Wrapping is via `truncatingRemainder` — safe for rates larger than the span. - `trig` scans the full audio-rate trigger block per audio block in both `.Audio` and `.Control` variants. - Standalone sync/ramp primitive; works at any rate in the signal graph. --- ### 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, Generators, closures). - **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`. #### ToneStack Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender / Marshall / Vox EQ network, not three independent bands, so the controls load each other exactly as on the real amp. The selected model's continuous-time transfer function (Yeh & Smith closed form) is bilinear-discretized to a 3rd-order IIR; coefficients recompute only when a control changes. Audio-only, mono output. ```swift ToneStack(input: sig, bass: 0.6, mid: 0.4, treble: 0.7) // Fender (default) ToneStack(input: sig, bass: 0.5, mid: 0.7, treble: 0.5, model: .marshall) ``` **Parameters:** - `input`: Signal to filter. - `bass` / `mid` / `treble`: Controls in `[0, 1]` (clamped). Bass uses an exponential taper; mid/treble are linear. Default `0.5`. - `model`: `ToneStackModel` — `.fender` / `.marshall` / `.vox` (component values). Set at init. Default `.fender`. - Companion type: `ToneStackModel`. --- ### 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: Double` 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` — 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` 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 [[Double]] 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. ### CrossFade.Audio / CrossFade.Control (SC `XFade2`) Equal-power crossfade between two inputs. Maps `pan ∈ [−1, 1]` to a quarter-sine/cosine gain pair so that `gainA² + gainB² = 1` at every position. `mul` plays the role of SC's `level` argument. Mono output (channel 0 of each input). Both `Audio` and `Control` variants. ```swift let xfade = CrossFade.Audio(inA: osc1, inB: osc2, pan: modLFO) ``` ### LinearCrossFade.Audio / LinearCrossFade.Control (SC `LinXFade2`) Linear crossfade between two inputs. `gainA = (1 − pan) * 0.5`, `gainB = (1 + pan) * 0.5` so `gainA + gainB = 1` everywhere. Useful when constant-amplitude sum is preferred over constant power. `mul` plays the role of SC's `level` argument. Mono output. Both variants. ```swift let xfade = LinearCrossFade.Audio(inA: dry, inB: wet, pan: sendLevel) ``` ### Select.Audio / Select.Control (SC `Select`) Index-selected N-input switch. Outputs the input at integer index `which` (truncated toward zero, clamped to `[0, N−1]`). All inputs are pulled every block regardless of selection — SC parity: non-selected sources advance their internal state. Both `Audio` and `Control` variants. ```swift let sel = Select.Audio(which: modLFO, inputs: [osc1, osc2, osc3]) ``` --- ## 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 Seven signal-processing generators for amplitude tracking, pitch detection, limiting, normalizing, RMS matching, 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 | | `Normalizer` | Audio only | Look-ahead peak normalizer; scales up AND down to `level`; `dur` latency | | `Balance` | Audio only | RMS level matcher; scales `in` to track the running RMS of `test`; decoupled `hp`/`smooth`; optional `logDomain` glide | | `Compressor` | Audio + Control | Feed-forward compressor; threshold/ratio/attack/release/knee/makeup | | `Expander` | Audio + Control | Downward expander/gate; mirrors `Compressor` below threshold | `Balance` (sc3-plugins `Balance`, JoshUGens) tracks the running mean-square of two signals via a one-pole lowpass on squared samples (pole `b1 = exp(-2π·hp/sr)` from the `hp` cutoff in Hz, snapshotted per block) and outputs `in · sqrt(ms_test / (ms_in + tiny))`. Because the gain is a ratio of two identically-normalised mean-squares, the normalisation cancels — only the `hp` window length matters (equivalent to SC's unnormalised running-sum form, but bounded + denormal-safe). Canonical use: bring a filtered signal back up to the level of the unfiltered source. Silent `in` stays silent; silent `test` drives `in` toward zero; `tiny` (1e-10) guards the divide. Takes `mul`/`add`. A single one-pole on `x²` ripples at twice the signal frequency, so a high `hp` lets that ripple modulate the gain (amplitude-modulation sidebands, worst on bass). `Balance` adds a second, **decoupled** one-pole on the gain via `smooth` (seconds): raise `hp` for fast level detection, then raise `smooth` to suppress the ripple independently. `smooth == 0` (default) bypasses the lag — bit-identical to the classic single-pole form. Set `logDomain: true` to smooth the gain in the **decibel (log) domain** instead: it smooths the level *difference in dB* (`log10(ms_test/ms_in)`) then exps back, so a `+6 dB` and a `−6 dB` correction glide with the same shape and time (symmetric, perceptually even — like an analogue auto-leveller), versus the default linear-gain lag which is faster on boosts than cuts. The log path costs one `log10` + one `exp` per sample and floors the power so silence stays finite. `Normalizer` (SC `Normalizer`) shares `LookAheadLimiter`'s ring-buffer + monotonic sliding-window-max deque, but its gain law is `level / windowPeak` applied unconditionally (vs the limiter's `maxAmp / windowPeak` only when over the ceiling), so quiet passages are scaled **up** and loud ones **down** to track `level`. Instant attack (no overshoot) + one-pole smoothed release (time constant `dur`); output delayed by `Int(dur·sampleRate)`. `sampleRate` is required at init. An exactly-silent window holds gain (no `level/0`); a near-silent non-zero window amplifies its noise floor toward `level` (intended normalizer behaviour). 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` 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) ``` ### LFGauss (SC `LFGauss`) Gaussian bell-shaped oscillator. Over each `period` (seconds) the output traces a Gaussian bell — near `0` at the period boundaries, peaking at `1.0` at the period midpoint. `width` is the standard deviation as a fraction of the half-period (smaller → narrower spike). Output range `(0, 1]`. A smooth non-band-limited LFO and a ready-made grain-window shape. Paired `GeneratorEnum` (Audio + Control). `period` and `width` accept generator inputs; `phase` is an init-only `[0, 1)` offset (`0` starts at a trough, `0.5` at the peak). ``` x = 2·phase − 1 (phase advances 1 / (period · sr) per sample) out = exp(−0.5 · (x / width)²) ``` ```swift LFGauss.Audio(period: 0.02, width: 0.15) // ~50 Hz bell-train LFO LFGauss.Audio(period: 0.5, width: 0.1, phase: 0.0) // grain envelope, starts at trough LFGauss.Control(period: 2.0, width: 0.25) // slow swell ``` ### 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. --- ## Chaotic / Strange-Attractor Oscillators `Generators/Chaotic/`. Oscillators that iterate a discrete chaotic map at a chosen `freq` (iterations/sec, **not** once per sample) and bridge successive iterations with `interpolation` (`.none` held/aliased, `.linear`, `.cubic`). Shared base `ChaoticBase` (analogous to `NoiseBase`) owns `freq`, `mulAdd`, the interpolation kernel, a 4-value history ring, and the sub-iteration phase accumulator; per-map `_Base` subclasses add the map variables + `iterate()`. `freq` and map parameters are read once per block (no per-sample audio-rate modulation). `Control` advances one audio block per call and ramps via `fillRampedResult`. `Crackle` (under Noise) is the only per-sample chaotic map and is unrelated to this family. ### LorenzLinear (SC `LorenzL`) Lorenz strange attractor by forward Euler (`x' = x + h·s·(y−x)`, etc.), output = `x`. Default `interpolation: .linear`. Output is the **raw** `x` coordinate (`|x|` ≲ 25 on the attractor) — scale with `mul`. The Euler step `h` defaults to `0.02`: SC's nominal `0.05` diverges under plain forward Euler (verified — blows up within ~25 steps), so keep `h` below ~0.03. ```swift LorenzLinear.Audio(freq: 22050.0, mul: 0.05) // classic attractor tone, scaled to ~[-1,1] LorenzLinear.Control(freq: 200.0, mul: 0.05) // slow chaotic LFO ``` ### HenonStepped (SC `HenonN`) Hénon map `x[n+1] = 1 − a·x[n]² + b·x[n−1]`, output = `x`. Default `interpolation: .none` (held/stepped — the aliased SC `HenonN` character). Canonical `a = 1.4`, `b = 0.3` → bounded chaotic orbit in roughly `[-1.5, 1.5]`. ```swift HenonStepped.Audio(freq: 22050.0) // gritty stepped chaos HenonStepped.Audio(freq: 8000.0, interpolation: .cubic) // smoothed ``` ### QuadStepped (SC `QuadN`) General quadratic map `x[n+1] = a·x[n]² + b·x[n] + c`, output `x`, default `.none`. Canonical `a = 1`, `b = −1`, `c = −0.75` → chaotic, bounded ~`[-1.25, 1.25]` (conjugate to the logistic map). ```swift QuadStepped.Audio(freq: 6000.0) ``` ### LinCongStepped (SC `LinCongN`) Linear-congruential map `x[n+1] = (a·x[n] + c) mod m`, output stays in `[0, m)`, default `.none`. Canonical `a = 1.1`, `c = 0.13`, `m = 1`. ```swift LinCongStepped.Audio(freq: 6000.0) // output in [0, 1) LinCongStepped.Audio(freq: 6000.0, mul: 2.0, add: -1.0) // bipolarised to [-1, 1) ``` ### GbmanStepped (SC `GbmanN`) Gingerbreadman map `x[n+1] = 1 − y[n] + |x[n]|`, `y[n+1] = x[n]`; output `x`, default `.none`. No shape parameters — only initial conditions `xi`/`yi`. Bounded chaotic (`|x| ≲ 8`). ```swift GbmanStepped.Audio(freq: 6000.0, mul: 0.2) ``` ### StandardStepped (SC `StandardN`) Chirikov standard map (kicked rotor): `y' = (y + k·sin(x)) mod 2π`, `x' = (x + y') mod 2π`; output `x` ∈ `[0, 2π)`. Larger `k` → stronger chaos (default `1`). Scale with `mul: 1/π, add: -1` for `[-1, 1)`. ```swift StandardStepped.Audio(freq: 6000.0, k: 1.0) ``` ### FBSineStepped (SC `FBSineN`) Feedback sine map: `x' = sin(im·y + fb·x)`, `y' = (a·y + c) mod 2π`; output `x` ∈ `[-1, 1]`. Defaults `im=1`, `fb=0.1`, `a=1.1`, `c=0.5`. ```swift FBSineStepped.Audio(freq: 6000.0) ``` ### LatoocarfianStepped (SC `LatoocarfianN`) Pickover's Latoocarfian: `x' = sin(b·y) + c·sin(b·x)`, `y' = sin(a·x) + d·sin(a·y)`; output `x` ∈ ~`[-1.5, 1.5]`. Chaos generally needs `|a|, |b| ≤ 3` (defaults `a=1`, `b=3`, `c=d=0.5`). ```swift LatoocarfianStepped.Audio(freq: 6000.0) ``` ### CuspStepped (SC `CuspN`) Cusp map: `x' = a − b·√|x|`; output `x`. Canonical `a=1`, `b=1.9` → chaotic, bounded ~`[-0.9, 1.0]`. ```swift CuspStepped.Audio(freq: 6000.0) ``` --- ## 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).bandpass // select the bandpass output ``` - Outputs: `.lowpass`, `.highpass`, `.bandpass`, `.notch` accessors (all four are computed simultaneously; pick one, or read several from the same instance). - `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. ### Slew Linear slew-rate limiter. Equivalent to SuperCollider `Slew`. Moves the output toward `input` at a maximum rate of `up` units per second when rising and `dn` units per second when falling. On the first block the output is initialised directly to the first input value. ```swift Slew.Audio(input: controlSignal, up: 500.0, dn: 200.0) // asymmetric slopes Slew.Control(input: $cv, up: 100.0, dn: 100.0) // smooth CV at control rate ``` - `up` / `dn` are slopes in **units per second** (not per sample). The per-sample step is `up / sampleRate` (audio) or `up / (sampleRate / blockSize)` (control). - **Linear** rate-limiting — distinct from the **exponential** smoothing produced by the `Lag` family. Use `Lag` for an RC-filter curve; use `Slew` for a linear ramp at a controlled maximum slope. - `Slew.Control` produces a flat output block (like `Lag.Control`); use `Slew.Audio` for smoothly interpolated output. ### 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. ### Klank.Audio (SC `Klank`) Modulatable counterpart of `ResonatorBank` — parallel two-pole resonator bank with the three SC `Klank` block-rate modulation parameters. Spec buffer rows are `(freq, amp, decay)` (SC channel order). Audio-only. ```swift let spec = LyrebirdBuffer(count: 3, channelCount: klankSpecChannelCount) // freq, amp, decay // fill rows with N resonator specs Klank.Audio(input: excitation, buffer: spec, freqscale: 1.0, freqoffset: 0.0, decayscale: 1.0) ``` - `freqscale` / `freqoffset` / `decayscale` are any `ValidGeneratorInput`, snapshotted once per audio block: `freq_eff = freq·freqscale + freqoffset`, `decay_eff = decay·decayscale`. - Buffer `channelCount` precondition: `klankSpecChannelCount` (= 3); channel indices `klankFreqChannel` / `klankAmpChannel` / `klankDecayChannel`. - Whole-table live swap via `setBuffer(_:engine:)` (RT-safe `RTBufferSlot`); new buffer must match the initial bank size. `freq_eff` floored at `0.1` Hz, `decay_eff` at `1e-6` s; `amp` unclamped. - Same vDSP per-sample kernel as `ResonatorBank`; summed to mono. ### Klang.Audio (SC `Klang`) Additive sine-partial bank — the source counterpart of `Klank` (no input). Outputs the sum of N table-lookup sines. Spec buffer rows are `(freq, amp, phase)` (SC channel order). Audio-only. ```swift let spec = LyrebirdBuffer(count: 4, channelCount: klangSpecChannelCount) // freq, amp, phase // fill rows with N partial specs Klang.Audio(buffer: spec, freqscale: 1.0, freqoffset: 0.0, interpolation: .linear) ``` - `freqscale` / `freqoffset` snapshotted once per block: `freq_eff = freq·freqscale + freqoffset`. - `freq` / `amp` re-read from the table each block (live `setValue` + `setBuffer(_:engine:)` swap retune the bank). The `phase` channel seeds each partial's phase accumulator at `init` only — phases free-run thereafter, so table swaps never click. - Buffer `channelCount` precondition: `klangSpecChannelCount` (= 3); channel indices `klangFreqChannel` / `klangAmpChannel` / `klangPhaseChannel`. - `interpolation: TableInterpolation` (`.none` / `.linear` / `.cubic`) on the shared sine table; `amp` and `freq_eff` unclamped (negatives invert / reverse). ### 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`). ### Formlet (SC `Formlet`) FOF-like resonant filter parameterised by `attackTime` / `decayTime` rather than `freq` + `Q`. The impulse response is a sine at `freq` under a rise-then-fall (Decay2-style) envelope — the basis of formant / vowel synthesis. Defined as the difference of two `ResonatingFilter` (Ringz) outputs at the same `freq`: ``` Formlet(in, freq, attack, decay) == ResonatingFilter(in, freq, decay) − ResonatingFilter(in, freq, attack) ``` Paired `GeneratorEnum` (Audio + Control). Reuses `runTwoPoleResonatorScalarBlock` / `…InterpolatedBlock` and `resonatingCoeffs`. `freq`, `attackTime`, `decayTime` all accept generator inputs (block-boundary coefficient interpolation). ```swift Formlet.Audio(input: impulse, freq: 880.0, attackTime: 0.001, decayTime: 0.1) Formlet.Control(input: trig, freq: 220.0, attackTime: 0.01, decayTime: 0.5) ``` --- ## 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. ### Trig SC `Trig`. On each ≤0 → >0 rising edge of `input`, captures the input value at that frame and outputs it for `dur` seconds, then returns to `0.0`. A new edge during the hold restarts the timer and re-captures the level. ```swift Trig.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.1) Trig.Control(input: envTrig, dur: 0.5) ``` - `dur`: hold duration in seconds (init-time scalar; converted to samples via engine sample rate; minimum 1 sample). - The `input` signal is both the trigger source and the level captured on each rising edge. ### Trig1 SC `Trig1`. Identical to `Trig` but always outputs `1.0` (unity) regardless of the input level for `dur` seconds after each ≤0 → >0 rising edge. Useful for generating fixed-amplitude gate pulses. ```swift Trig1.Audio(input: Impulse.Audio(freq: 4.0), dur: 0.05) Trig1.Control(input: envTrig, dur: 0.2) ``` - `dur`: hold duration in seconds (init-time scalar; minimum 1 sample). ### TriggeredDelay SC `TDelay`. Delays a trigger by `dur` seconds: on a ≤0 → >0 rising edge of `input`, starts a countdown. When the countdown elapses, emits a single-sample `1.0`. Additional edges arriving while the countdown is active are **ignored** (only the first edge per idle cycle is honoured). ```swift TriggeredDelay.Audio(input: Impulse.Audio(freq: 2.0), dur: 0.2) TriggeredDelay.Control(input: clockTrig, dur: 0.1) ``` - `dur`: delay duration in seconds (init-time scalar; minimum 1 sample). ### PulseCount SC `PulseCount`. Running counter that increments by 1 on each ≤0 → >0 rising edge of `trig`. A rising edge of `reset` clears the counter to `0.0` before the `trig` increment at that sample. ```swift PulseCount.Audio(trig: Impulse.Audio(freq: 4.0)) PulseCount.Control(trig: clock, reset: resetTrig) ``` - Counter is never clamped and grows without bound. ### Stepper SC `Stepper`. Wrapping integer step counter. On each rising edge of `trig`, advances by `step` within `[min, max]`, wrapping at the boundaries. `reset` returns the value to `resetval`. All range/step/reset parameters are init-time scalars. ```swift // 8-step sequencer index cycling 0..7 Stepper.Audio(trig: Impulse.Audio(freq: 4.0), min: 0, max: 7, step: 1, resetval: 0) Stepper.Control(trig: clock, reset: resetSig, min: 0, max: 15) ``` - `min`, `max`: range (inclusive). `max` must be ≥ `min`. Defaults: `0` / `7`. - `step`: signed increment per edge. Defaults to `1`. Negative values step downward. - `resetval`: value written on a reset edge; clamped to `[min, max]`. Defaults to `0`. ### Schmidt SC `Schmidt`. Schmitt trigger with hysteresis. Maintains binary `0.0` / `1.0` state with separate switch-on (`hi`) and switch-off (`lo`) thresholds. Prevents chatter near the threshold. - State `0.0` → `1.0`: when `input > hi`. - State `1.0` → `0.0`: when `input < lo`. - In the hysteresis band `[lo, hi]`: state unchanged. ```swift Schmidt.Audio(input: amp, lo: 0.1, hi: 0.3) Schmidt.Control(input: $cv, lo: 0.2, hi: 0.8) ``` - `lo`, `hi`: any `ValidGeneratorInput` — scalar literals, `ParameterNode`, `@LiveParam`, or audio/control-rate generators. When using audio-rate generators for per-sample varying thresholds, ensure they conform to `Generator` (not `Closure`). --- ## 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.Control(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( 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(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(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(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, blockSize: engine.blockSize ) ``` - `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: .freeNode, // 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` sets the node-tree action on EOF: `.nothing` / `.freeNode` / `.loop`. 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, // .wavFloat32 / .wavInt16 / .wavInt24 / .aiffFloat32 / .cafFloat32 / .rf64Float32 / .rf64Int24 bufferFrames: 8192 ) ``` - Format encoded by the `AudioFileFormat` enum (`DiskOutFormat` is an alias) — file extension + sample format. - **PCM / RF64 only**: the compressed codecs (`.aacHigh` / `.aacMedium` / `.alac`) throw `DiskOutError.compressedFormatNotSupported` — real-time streaming of a compressed encoder is out of scope. Render AAC/ALAC offline via `LyrebirdBuffer.write` or `NRTDriver`. - Writes from a background thread; the RT thread publishes into a lock-free ring buffer via atomic frame counters (not an `SPSCQueue`). - **4 GB cap on WAV/AIFF**: a long streaming recording to a WAV or AIFF-C target stops growing once the file reaches the 4 GB container limit (`lyrebirdMaxRIFFBytes`) — a recording already in flight can't retroactively throw, so frames past the cap are **silently dropped** and the audio already written stays valid. Poll `writer.fileTooLarge` after `close()` to detect it. For long sessions record to a 64-bit container: `.cafFloat32`, or `.rf64Float32` / `.rf64Int24` (RF64/BW64 — keeps the `.wav` extension, streamed via `RF64Writer` with the `ds64` sizes patched on `close()`). --- ## 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, hopSize: 512, frameCount: 1024, sampleRate: 44100.0) // ... 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, hopSize: 512, frameCount: 256, sampleRate: 44100.0) // 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`, 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. --- ## Time-Domain Analysis Four SuperCollider-parity time-domain analysis and measurement generators. Source files live in `Sources/Lyrebird/Generators/Analysis/`. | Generator | SC equivalent | Audio | Control | Description | |-----------|--------------|-------|---------|-------------| | `ZeroCrossing` | `ZeroCrossing` | yes | yes | Frequency estimate (Hz) from rising zero-crossing spacing. Output held between crossings; `0.0` until the first full period is measured. | | `Slope` | `Slope` | yes | yes | Per-second rate of change: `(x[n] − x[n−1]) × sampleRate`. First sample/block outputs `0.0` (lazy init — no startup spike). | | `RunningMin` | `RunningMin` | yes | yes | Running minimum since the last trigger reset. Lazy-initialised to the first input value. Rising `trig` edge resets to the current input. | | `RunningMax` | `RunningMax` | yes | yes | Running maximum since the last trigger reset. Identical behaviour to `RunningMin` but tracking the maximum. | All four are paired generators conforming to `GeneratorEnum`. `Control` variants bypass the sub-block loop (scan the full audio-rate input block once per audio cycle and output a flat result). ```swift // Frequency estimation. let zcFreq = ZeroCrossing.Audio(input: audioSignal) let zcFreqCtl = ZeroCrossing.Control(input: audioSignal) // block-rate measurement // Rate-of-change differentiation. let diff = Slope.Audio(input: envelope) // per-sample differentiation let diffCtl = Slope.Control(input: $cv) // block-rate differentiation // Peak / trough tracking. let peakTracker = RunningMax.Audio(input: signal) let peakTrackerReset = RunningMax.Audio(input: signal, trig: resetClock) let troughTracker = RunningMin.Control(input: $cv, trig: gate) ``` Parameters common to all four: - `input`: signal to analyse (`any ValidGeneratorInput`) - `mul`: output multiplier, default `1.0` - `add`: output offset, default `0.0` - `RunningMin` / `RunningMax` additionally accept `trig` (default `0.0`) --- ## Waveshaping / Distortion Transfer-function and stochastic distortion generators. Source files live in `Sources/Lyrebird/Generators/Waveshaping/`. | Generator | SC equivalent | Audio | Control | Description | |-----------|--------------|-------|---------|-------------| | `Waveshaper` | `Shaper` | yes | yes | Table-lookup transfer-function waveshaper. Input clamped to `[-1, 1]` before linear-interpolated table lookup. RT-safe live table swap via `setTable(_:engine:)`. | | `CrossoverDistortion` | `CrossoverDistortion` | yes | yes | Dead-zone / crossover distortion. Signals in `[-amp, amp]` are silenced; signals outside that range are shifted toward zero. Optional C¹ smooth knee. | | `Disintegrator` | `Disintegrator` | yes | — | Stochastic sample-dropping distortion. Each sample is independently disintegrated (replaced by `input × multiplier`) with probability `probability`. Audio-only. | | `TriodeStage` | — | yes | — | Tube-style preamp stage: biased asymmetric `tanh` soft-clip (`drive` gain, `bias` grid offset → even harmonics), evaluated at 2×/4× oversampling, with an output coupling (DC-block) high-pass. Audio-only. | `Waveshaper` and `CrossoverDistortion` conform to `GeneratorEnum`. `Disintegrator` and `TriodeStage` are Audio-only and do not. ### TriodeStage A single tube preamp stage. A grid `bias` makes the `tanh` transfer asymmetric — generating even-order harmonics (single-ended tube warmth) and a program-dependent DC shift the output coupling removes. The nonlinearity is oversampled so its harmonics don't alias. A musically-voiced static waveshaper, not a SPICE circuit solve. ```swift TriodeStage(input: sig, drive: 3.0, bias: 0.3) // 4× oversampled (default) TriodeStage(input: sig, drive: 5.0, bias: 0.0, oversample: 2) // symmetric, 2× ``` ### Waveshaper (SC `Shaper`) Transfer-function waveshaper using a `LyrebirdBuffer` as the transfer curve. ```swift let table = LyrebirdBuffer(count: 1024) table.fill { i, n in let x = Double(i) / Double(n - 1) * 2.0 - 1.0 return tanh(x * 4.0) // soft saturation } let shaper = Waveshaper.Audio(table: table, input: signal) let lfoShaper = Waveshaper.Control(table: table, input: lfoSignal) ``` - `table`: mono `LyrebirdBuffer` (at least 2 samples). The transfer curve is indexed by the clamped input `x ∈ [-1, 1]` via `pos = (x × 0.5 + 0.5) × (tableSize − 1)` with linear interpolation. - `input`: signal to waveshape. Values outside `[-1, 1]` are clamped (saturating, not wrapping). - `mul` / `add`: standard output multiplier and offset. - `setTable(_:engine:)`: RT-safe live table swap. New table must be mono and same size as the initial table. ### CrossoverDistortion (inspired by SC `CrossoverDistortion`) Crossover / dead-zone distortion with optional smooth knee. The implementation is a clean owned formula — not claimed bit-exact with SuperCollider, but sharing the same conceptual model. ```swift // Hard-knee crossover: dead zone ±0.5, then linear continuation. let dist = CrossoverDistortion.Audio(input: signal, amp: 0.5, smooth: 0.0) // Soft-knee: C¹ quadratic ease-in at the dead-zone boundary. let softDist = CrossoverDistortion.Audio(input: signal, amp: 0.3, smooth: 0.5) ``` - `amp`: dead-zone half-width (≥ 0). Signals in `[−amp, amp]` are zeroed. **Not an output gain** — use `mul` for gain. SC also names this `amp`. - `smooth`: knee smoothness `[0, 1]`. `0` = hard knee (instantaneous transition); `1` = full-width C¹ ease-in over the full dead-zone width. - Transfer function: for `|x| > amp`, `over = |x| − amp`. Hard-knee: `out = sign(x) × over`. Soft-knee: `out = sign(x) × over² / (2 × kneeWidth)` within the knee, then linear continuation maintaining C¹ continuity. ### Disintegrator (SC `Disintegrator`) Stochastic sample-dropping distortion. Audio-only — "block-rate disintegration" has no meaningful physical interpretation; the random draw must happen per sample. ```swift // Drop ~50 % of samples to silence. let dist = Disintegrator.Audio(input: signal, probability: 0.5, multiplier: 0.0) // Attenuate ~30 % of samples by half. let grit = Disintegrator.Audio(input: signal, probability: 0.3, multiplier: 0.5) // Deterministic seed for tests. let det = Disintegrator.Audio(input: signal, probability: 0.5, seed: 42) ``` - `probability`: `[0, 1]` chance per sample of disintegration. Clamped internally. - `multiplier`: scale factor applied to disintegrated samples. `0.0` → silence; `1.0` → no change (same as `probability = 0`). - `seed`: optional PRNG seed. `nil` = time-derived unique seed; explicit value = deterministic/reproducible output. - `mul` / `add`: applied after disintegration to all samples (including undisintegrated ones). --- ## Neural amp modeling Real-time neural inference of guitar-amp/pedal captures. Source files live in `Sources/Lyrebird/Generators/Neural/`. ### LSTMAmp Runs a single-layer LSTM amp capture one audio sample at a time — the GuitarML "Proteus" / NeuralPi topology (`LSTM(inputSize: 1, hiddenSize: H)` → `Linear(H, 1)`, optional input skip). Weights come from a `NeuralAmpModel` (a `Codable` weight container) and are copied into contiguous storage at init; the render path does only pre-allocated scalar math (no allocation or locks), costing `O(4·H²)` multiply-adds per sample, so keep `H` modest (Proteus captures are typically `H = 20…40`). Audio-only, mono. Does not clamp — a well-trained capture stays near `[-1, 1]`. ```swift let model = NeuralAmpModel(hiddenSize: 20, residual: true, weightIH: ih, weightHH: hh, biasIH: bih, biasHH: bhh, denseWeight: dw, denseBias: db) let amp = LSTMAmp(input: di, model: model) ``` GuitarML Proteus / NeuralPi JSON models load via `ProteusModelImporter` (below). A binary NAM `.nam` importer remains a planned follow-up. ### ProteusModelImporter Imports a GuitarML **Proteus / NeuralPi** model JSON (single-layer PyTorch LSTM, `unit_type` `"LSTM"`, `input_size`/`output_size` 1) into a `NeuralAmpModel` for `LSTMAmp`. The tensors flatten straight onto `NeuralAmpModel`'s layout (PyTorch gate order i,f,g,o); `skip == 1` → `residual`. Unsupported topologies or inconsistent tensor shapes throw. ```swift let data = try Data(contentsOf: modelURL) // a user-supplied .json let model = try ProteusModelImporter.model(fromProteusJSON: data) let amp = LSTMAmp(input: di, model: model) ``` > Model files are **not** redistributed with Lyrebird — this only parses a file the user > supplies. GuitarML models are GPL-licensed; keep them out of MIT-licensed bundles.