# Dynamics Generators Five signal-processing generators for amplitude tracking, pitch tracking, limiting, compression, and expansion. All generators are **single-channel in / single-channel out** (except `FreqTracker`, which outputs two channels). Multi-channel use relies on MCE — wiring a multi-channel source creates N independent instances. For linked-mode stereo compression, compute a shared side-chain level with `AmplitudeFollower` and pass it as the input to shared `threshold`/`ratio` controls. --- ## `AmplitudeFollower` — Envelope Follower File: `Sources/Lyrebird/Generators/Dynamics/AmplitudeFollower.swift` Tracks the instantaneous amplitude of an input signal using a one-pole smoother with independent attack and release time constants. ```swift AmplitudeFollower.Audio(in:attackTime:releaseTime:) AmplitudeFollower.Control(in:attackTime:releaseTime:) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `in` | `ValidGeneratorInput` | — | Signal to track | | `attackTime` | `ValidGeneratorInput` | `0.01` | Rise time in seconds | | `releaseTime` | `ValidGeneratorInput` | `0.1` | Fall time in seconds | **Output:** single channel, amplitude estimate ≥ 0. **Algorithm:** ``` attackCoeff = exp(−1 / (sr × attackTime)) releaseCoeff = exp(−1 / (sr × releaseTime)) abs_x = |x[n]| coeff = abs_x > prevAmp ? attackCoeff : releaseCoeff out[n] = coeff × prevAmp + (1 − coeff) × abs_x ``` Setting `attackTime` or `releaseTime` to `0` makes that transition instantaneous (coefficient → 0). `denormalsToZero()` applied to state after each sample. **Control variant:** computes block-peak, applies one smoothing step, outputs linear ramp to downstream audio consumers. **Usage:** ```swift let mic = In.Audio(bus: 0) let level = AmplitudeFollower.Audio(in: mic, attackTime: 0.005, releaseTime: 0.5) // Use level as a modulation source: let vca = mic * level ``` --- ## `FreqTracker` — Monophonic Pitch Tracker File: `Sources/Lyrebird/Generators/Dynamics/FreqTracker.swift` Estimates the fundamental frequency of a monophonic signal using the **YIN algorithm** (de Cheveigné & Kawahara 2002). Produces a two-channel output: frequency in Hz and a confidence value. ```swift FreqTracker(in:fftSize:hopSize:minFreq:maxFreq:) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `in` | `ValidGeneratorInput` | — | Signal to analyse | | `fftSize` | `Int` | `512` | Analysis window (power of 2, in [64, 512]). Set at init. | | `hopSize` | `Int?` | `fftSize / 2` | Samples between analyses. Set at init. | | `minFreq` | `Double` | `60.0` | Lower search bound in Hz | | `maxFreq` | `Double` | `3000.0` | Upper search bound in Hz | **Output:** two channels. - `result[0]` — tracked frequency in Hz (`0.0` when no pitch detected) - `result[1]` — confidence in `[0, 1]` (`1.0` = certain, `0.0` = no pitch) Output holds the previous hop result between analyses. On init, both channels output `0.0` until the first hop completes (after `hopSize` samples). **YIN Algorithm:** 1. Accumulate samples in a `fftSize`-sample ring buffer. 2. Every `hopSize` samples: compute squared difference function `d[τ]`. 3. Compute cumulative mean normalised difference function (CMNDF). 4. Find first `τ` where CMNDF `< 0.1` (adjustable threshold). 5. Parabolic interpolation for sub-sample period accuracy. 6. Confidence `= 1 − CMNDF[τ_peak]` (clamped to `[0, 1]`). **Pre-allocated buffers (RT-safe):** - `_inputRing: [Double]` of length `fftSize` - `_yinBuffer: [Double]` of length `fftSize / 2` **No Control variant** — pitch tracking is sample-accurate by design. **Usage:** ```swift let tracker = FreqTracker(in: In.Audio(bus: 0)) // Write freq to bus 2, confidence to bus 3: output(bus: 2, source: tracker) ``` --- ## `LookAheadLimiter` — True Look-Ahead Limiter File: `Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift` Delays the output by `lookAheadTime` seconds and uses the look-ahead window to detect peaks before they arrive, guaranteeing the output never exceeds `±maxAmplitude`. No overshoot. ```swift LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `in` | `ValidGeneratorInput` | — | Signal to limit | | `maxAmplitude` | `ValidGeneratorInput` | `1.0` | Peak ceiling (absolute value) | | `lookAheadTime` | `Double` | `0.005` | Delay in seconds. Set at init. | | `releaseTime` | `ValidGeneratorInput` | `0.050` | Gain-release time constant (seconds), read per block; decoupled from `lookAheadTime`. Clamped to ≥ 0. Keep it above the period of the lowest expected frequency to avoid low-frequency distortion. | | `sampleRate` | `Double` | `44100.0` | Used to size ring buffers at init. | **Output:** single channel, delayed by `lookAheadSamples = Int(lookAheadTime × sampleRate)`. **Algorithm:** 1. Write incoming sample into delay and peak ring buffers. 2. Scan the look-ahead window (`lookAheadSamples`) for peak. 3. Required gain = `min(1, maxAmplitude / peak)`. 4. Attack is **instantaneous** (gain can always be reduced within the window). 5. Release smoothed: `releaseCoeff = exp(−1 / (sr × releaseTime))`, recomputed per block (so `releaseTime` may track a live parameter) rather than fixed at init. 6. Output = delayed sample × current gain. **Pre-allocated buffers:** - `_delayRing`, `_peakRing`: length `lookAheadSamples + 513`. > **Note:** Pass `sampleRate` at init if you know the engine's sample rate in advance (e.g. from `SynthesisEngine.sampleRate`). If not supplied, the default 44100 Hz is used to size the ring buffers. A mismatch causes the delay to differ from `lookAheadTime`, but will not crash. **No Control variant** — latency management is meaningless at block rate. **Usage:** ```swift let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005, releaseTime: 0.050, sampleRate: engine.sampleRate) ``` --- ## `Compressor` — Feed-Forward Compressor File: `Sources/Lyrebird/Generators/Dynamics/Compressor.swift` Reduces gain when the signal level exceeds `threshold`. Gain is smoothed with attack and release time constants — fast transients may briefly overshoot. ```swift Compressor.Audio(in:threshold:ratio:attack:release:kneeWidth:makeupGain:) Compressor.Control(in:threshold:ratio:attack:release:kneeWidth:makeupGain:) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `in` | `ValidGeneratorInput` | — | Signal to compress | | `threshold` | `ValidGeneratorInput` | `-6.0` | Level in dB above which compression engages | | `ratio` | `ValidGeneratorInput` | `4.0` | Compression ratio (> 1; e.g. `4.0` = 4:1) | | `attack` | `ValidGeneratorInput` | `0.01` | Attack time in seconds | | `release` | `ValidGeneratorInput` | `0.1` | Release time in seconds | | `kneeWidth` | `ValidGeneratorInput` | `0.0` | Soft-knee width in dB (`0` = hard knee) | | `makeupGain` | `ValidGeneratorInput` | `0.0` | Output gain in dB added after compression | **Output:** single-channel compressed signal. **Gain computation:** - Hard knee: `gain_dB = (level − threshold) × (1/ratio − 1)` when `level > threshold`. - Soft knee (when `kneeWidth > 0`): parabolic interpolation within `±kneeWidth/2` of threshold. - Makeup gain applied linearly after ratio. - Gain smoothed per sample with attack/release one-pole filter. **Control variant:** computes block-peak level, applies one smoothing step, ramps gain linearly across the block and applies it to the input. **Usage:** ```swift let comp = Compressor.Audio(in: bass, threshold: -12.0, ratio: 4.0, attack: 0.005, release: 0.08, makeupGain: 4.0) ``` --- ## `Expander` — Downward Expander / Gate File: `Sources/Lyrebird/Generators/Dynamics/Expander.swift` Reduces gain when the signal level falls below `threshold`. Ratio of `0.0` is a hard gate; ratio of `1.0` is bypass. ```swift Expander.Audio(in:threshold:ratio:attack:release:kneeWidth:) Expander.Control(in:threshold:ratio:attack:release:kneeWidth:) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `in` | `ValidGeneratorInput` | — | Signal to expand | | `threshold` | `ValidGeneratorInput` | `-40.0` | Level in dB below which expansion engages | | `ratio` | `ValidGeneratorInput` | `0.5` | `0` = gate, `1` = bypass, values between = expansion | | `attack` | `ValidGeneratorInput` | `0.01` | Attack time in seconds | | `release` | `ValidGeneratorInput` | `0.1` | Release time in seconds | | `kneeWidth` | `ValidGeneratorInput` | `0.0` | Soft-knee width in dB | **Output:** single-channel expanded signal. **Gain computation:** - Hard knee: `gain_dB = (threshold − level) × (1 − ratio)` when `level < threshold`. - Soft knee: parabolic interpolation near threshold. **Control variant:** same block-rate approach as `Compressor.Control`. **Usage:** ```swift let gated = Expander.Audio(in: drums, threshold: -35.0, ratio: 0.0, attack: 0.001, release: 0.05) ``` --- ## Multi-Channel Use and Side-Chain Compression All generators are single-channel. Use MCE for parallel processing: ```swift // Two independent mono compressors on a stereo signal let left = Compressor.Audio(in: In.Audio(bus: 0), threshold: -12.0, ratio: 4.0) let right = Compressor.Audio(in: In.Audio(bus: 1), threshold: -12.0, ratio: 4.0) ``` For linked stereo (preserve image), derive a shared level signal and gate both channels identically: ```swift // Side-chain from a mono mix let monoMix = (In.Audio(bus: 0) + In.Audio(bus: 1)) * 0.5 let level = AmplitudeFollower.Audio(in: monoMix) // Use level to drive amplitude-based VCAs externally (not directly supported as // a side-chain input to Compressor — compose manually with BinaryOpGenerator). ```