1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
+375
View File
@@ -0,0 +1,375 @@
# Buffer I/O Generators — RecordBuffer + PlayBuffer
Record signal into a `LyrebirdBuffer` and play it back at variable rate.
Both generators come in two rate variants following the `_Base`/`Audio`/`Control` enum pattern:
| Type | Rate | Use |
|---|---|---|
| `RecordBuffer.Audio` | Audio (per-sample) | Record audio signals, multi-channel |
| `RecordBuffer.Control` | Control (per-block) | Record automation curves (LFO, envelopes) |
| `PlayBuffer.Audio` | Audio (per-sample) | Playback at variable rate with interpolation |
| `PlayBuffer.Control` | Control (per-block) | Playback of control automation data |
---
## RecordBuffer
Writes its input signal into a `LyrebirdBuffer` and passes the signal through as output. Recording and monitoring happen simultaneously.
### RecordBuffer.Audio
Audio-rate recording — writes one buffer frame per sample.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 1)
let rec = RecordBuffer.Audio(input: someOsc, buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: rec)
```
### RecordBuffer.Control
Control-rate recording — writes one buffer frame per block. Use for automation curves (LFO outputs, envelope followers).
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false)
```
Requires a **mono** buffer (`channelCount == 1`). Use `RecordBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from RecordBuffer._Base:
@LiveParam public var run: LyrebirdFloat // > 0 = recording, ≤ 0 = paused (default 1.0)
@LiveParam public var recLevel: LyrebirdFloat // scale on incoming signal (default 1.0)
@LiveParam public var preLevel: LyrebirdFloat // scale on existing buffer (default 0.0 = overwrite)
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool // acquiring Atomic<Bool> load
```
### Init
```swift
RecordBuffer.Audio(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool = true,
doneAction: DoneAction = .nothing
)
RecordBuffer.Control(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
doneAction: DoneAction = .nothing
)
```
### Write formula
Each frame:
```
buffer[frame, ch] = recLevel × input[ch] + preLevel × buffer[frame, ch]
```
`preLevel = 0.0` overwrites; `preLevel = 1.0` mixes new signal on top of existing content.
### Multi-channel (Audio variant)
Supply a `GeneratorArray` for stereo or N-channel buffers. Channel count must match `buffer.channelCount` — enforced by `precondition` in `_computeSamples`.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 2)
let stereoSrc = expand([leftSig, rightSig]) { $0 }
let rec = RecordBuffer.Audio(input: stereoSrc, buffer: buf)
output(bus: 0, source: rec) // stereo passthrough + stereo recording
```
### run param
Set `run = 0.0` to pause recording (write head holds position). Set `run = 1.0` to resume. The write head does not reset on resume.
### RT-safety note
Both variants write to `LyrebirdBuffer` storage from the RT thread. The buffer is **not safe for concurrent non-RT reads while recording is active**. Stop recording before reading from another thread.
### doneAction (loop == false)
| `DoneAction` | Behaviour |
|---|---|
| `.nothing` | Recording stops; generator stays in graph outputting passthrough |
| `.freeNode` | Sets `needsFree = true`; poll from main thread and call `engine.remove` |
| `.loop` | Resets write head to frame 0 (equivalent to `loop: true`) |
---
## PlayBuffer
Reads back a `LyrebirdBuffer` at a variable rate with interpolation.
### PlayBuffer.Audio
Audio-rate playback — reads one buffer frame per sample with interpolation. Output channel count equals `buffer.channelCount`.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: player)
```
### PlayBuffer.Control
Control-rate playback — advances phase once per block. Produces a linear-ramp output matching the `ControlGenerator` ramp convention. Use to play back automation curves recorded by `RecordBuffer.Control`.
```swift
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
```
Requires a **mono** buffer (`channelCount == 1`). Use `PlayBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from PlayBuffer._Base:
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool
```
### Init
```swift
PlayBuffer.Audio(
buffer: LyrebirdBuffer,
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0, // fractional frame index to begin playback
rate: any ValidGeneratorInput = 1.0, // playback rate multiplier
trigger: any ValidGeneratorInput = 0.0 // ≤0 → >0 edge resets play head
)
PlayBuffer.Control(
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0,
rate: any ValidGeneratorInput = 1.0,
trigger: any ValidGeneratorInput = 0.0
)
```
### Rate
| `rate` | Effect |
|---|---|
| `1.0` | Original speed (forward) |
| `2.0` | Double speed, pitch up one octave |
| `0.5` | Half speed, pitch down one octave |
| `-1.0` | Original speed, reversed |
| `-2.0` | Double speed, reversed, pitch up one octave |
`rate` accepts any `ValidGeneratorInput` — pass a generator for varispeed / vibrato:
```swift
// Constant rate (scalar at init):
let player = PlayBuffer.Audio(buffer: buf, rate: 2.0)
// Generator-driven rate (LFO vibrato):
let lfo = OscSin.Audio(freq: 5.0, mul: 0.05, add: 1.0)
let player = PlayBuffer.Audio(buffer: buf, rate: lfo)
```
### Reverse playback
Set `rate` negative to play the buffer in reverse. Use `startPos` to begin from the last frame:
```swift
let player = PlayBuffer.Audio(
buffer: buf,
loop: true,
startPos: Double(buf.count - 1),
rate: -1.0
)
```
With `loop: true` and a negative rate, `_phase` wraps from 0 back to the end of the buffer (seamless reverse loop). With `loop: false`, reaching `_phase < 0` fires `doneAction` and holds playback at frame 0.
### Trigger
`trigger` accepts any `ValidGeneratorInput`. Edge detection (≤0 → >0 transition) resets the play head to frame 0 and clears the `_isDone` flag.
```swift
// Scalar: always high — fires once on first sample (since _prevTrigger starts at 0).
let oneshot = PlayBuffer.Audio(buffer: buf, loop: false, trigger: 1.0)
// Generator: impulse-driven sample-accurate retrigger.
let imp = Impulse.Audio(freq: 2.0)
let player = PlayBuffer.Audio(buffer: buf, loop: false, trigger: imp)
// Mutable ParameterNode (when trigger must change over time):
let trigNode = ParameterNode(0.0)
let player = PlayBuffer.Audio(buffer: buf, trigger: trigNode)
// ... later, from non-RT thread:
trigNode.value = 1.0 // arm trigger
trigNode.value = 0.0 // lower, ready for next retrigger
```
### Multi-channel (Audio variant)
A stereo buffer produces two output channels. Wire through `output(bus:source:)`:
```swift
let stereoPlayer = PlayBuffer.Audio(buffer: stereoBuffer)
output(bus: 0, source: stereoPlayer) // bus 0 = left, bus 1 = right
```
### Interpolation
| Mode | Quality | Cost |
|---|---|---|
| `.none` | Truncate to nearest frame | Cheapest |
| `.linear` | Two-sample blend (default) | Low |
| `.cubic` | Catmull-Rom four-sample | Highest quality |
### doneAction (loop == false)
Same as `RecordBuffer` — `.freeNode` is the typical choice for one-shot samples.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
try engine.add(samplePlayer)
// Poll on main thread:
if player.needsFree { engine.remove(samplePlayer) }
```
---
## Sample-rate compensation
`LyrebirdBuffer` stores the native sample rate of its audio data:
```swift
public var sampleRate: Double? = nil
```
This is set automatically when loading from a file via `LyrebirdBuffer.load(url:)` or `loadAllChannels(url:)`. For manually-filled buffers, set `sampleRate` explicitly.
When playing a file recorded at a different sample rate than the engine, ask the buffer for the correcting `playRate` multiplier via `LyrebirdBuffer.nativeRateScale(engineSampleRate:)`. The helper is on the buffer itself so any buffer-consuming generator (`PlayBuffer`, granular, future warp/scrubbers) can reuse it:
```swift
let buf = try LyrebirdBuffer.loadAllChannels(url: url) // buf.sampleRate set automatically
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SamplePlayer: SynthesizerBase {
override func build() {
let rateScale = buf.nativeRateScale(engineSampleRate: engine.sampleRate)
let player = PlayBuffer.Audio(buffer: buf, loop: false,
doneAction: .freeNode, rate: rateScale)
output(bus: 0, source: player)
}
}
```
Returns `1.0` when `buffer.sampleRate` is `nil` (rate unknown).
---
## lyrebirdBufferRead
Free function used by `PlayBuffer` (and available to future generators like `GrainBuf`):
```swift
internal func lyrebirdBufferRead(
_ buffer: LyrebirdBuffer,
channel: Int,
phase: LyrebirdFloat,
interpolation: TableInterpolation,
loop: Bool
) -> LyrebirdFloat
```
Frame boundaries are **clamped** when `loop == false`, **wrapped modulo** `buffer.count` when `loop == true`.
---
## Combined example: looper
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class Looper: SynthesizerBase {
let recordBuf = LyrebirdBuffer(count: 44100 * 4, channelCount: 2) // 4-second stereo buffer
lazy var recorder = RecordBuffer.Audio(input: micInput, buffer: recordBuf, loop: false, doneAction: .nothing)
lazy var player = PlayBuffer.Audio(buffer: recordBuf, loop: true)
override func build() {
output(bus: 0, source: recorder) // monitor mic while recording
// player is added separately after recording finishes
}
}
// Stop recording after 4 seconds, start playback:
looper.recorder.run = 0.0
try engine.add(playerSynth)
```
## Combined example: control automation round-trip
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
// Record an LFO curve
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false, doneAction: .nothing)
// Play it back later
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
// Wire player output to a parameter (e.g. oscillator frequency)
```
---
## Live buffer swap
`PlayBuffer.Audio`, `PlayBuffer.Control`, `BufferRead.Audio`, and
`BufferRead.Control` all expose a `setBuffer(_:engine:)` method that replaces
the source buffer on a running engine without rebuilding the synth graph.
```swift
let player = PlayBuffer.Audio(buffer: bufA, loop: true)
// later, while the engine is running:
player.setBuffer(bufB, engine: engine) // swap source
player.setBuffer(nil, engine: engine) // silence (slot empty)
```
Constraints (precondition-trapped):
- New buffer's `channelCount` must equal the initial buffer's `channelCount` —
the generator's output buffer shape is fixed at init.
- Frame `count` may differ; phase wrapping uses the loaded buffer's `count` on
each block. If `_phase` overshoots the new (smaller) buffer, the next sample
read is clamped (`loop == false`) or wrapped (`loop == true`) by
`lyrebirdBufferRead`, and the in-loop wrap normalises `_phase` afterwards.
- `PlayBuffer.Control` was preconditioned mono at init; the setter inherits
that — any swap-in buffer must satisfy `channelCount == 1`.
The previously installed buffer's retain is routed through
`engine.bufferSwapKillQueue` and released by the engine's background
`freeWorker`, never on the RT thread. See ``BufferGuide`` § "Live Buffer Swap"
for the full pattern.
---
## See also
- `Sources/Lyrebird/Generators/RecordBuffer.swift`
- `Sources/Lyrebird/Generators/PlayBuffer.swift`
- `Sources/Lyrebird/Buffers/LyrebirdBuffer.swift` — buffer allocation, fill, invalidation, sampleRate
- `Sources/Lyrebird/Buffers/RTBufferSlot.swift` — atomic slot powering live buffer swap
- `docs/stdlib/generators.md` — built-in generator index
- `docs/engine/bus-system.md` — bus layout
+236
View File
@@ -0,0 +1,236 @@
# 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: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. |
| `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 × lookAheadTime))`.
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)
```
---
## `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).
```
File diff suppressed because it is too large Load Diff
+270
View File
@@ -0,0 +1,270 @@
# Granular Synthesis
Four granular generators share a common grain pool model. All are stereo (`AudioGenerator`,
2-channel output), pre-allocate `lyrebirdGrainPoolSize = 64` grain slots at `init`, and
trigger the first grain immediately at sample 0 of the first block.
---
## Common design
### Grain pool
Each generator holds `[GrainState]` of length `lyrebirdGrainPoolSize = 64`. When a grain
triggers, the first inactive slot is claimed. When all 64 slots are active, new triggers are
silently dropped — no allocation, no error.
### `GrainState` fields
```swift
struct GrainState {
var isActive: Bool // true while grain is playing
// Buffer-reading (BufferGrain, InputGrain)
var phase: LyrebirdFloat // fractional buffer frame
var phaseInc: LyrebirdFloat // playback rate (frames/sample)
// Common
var remaining: Int // samples left in grain
var amp: LyrebirdFloat // amplitude at trigger time
var pan: LyrebirdFloat // [-1, 1]; 0 = centre
var windowPhase: LyrebirdFloat // window table position (index units)
var windowInc: LyrebirdFloat // window advance per sample
// Synthesis (SineGrain, FMGrain)
var synthPhase: LyrebirdFloat // carrier oscillator phase (index units)
var synthPhaseInc: LyrebirdFloat // carrier phase increment
var modPhase: LyrebirdFloat // FM modulator phase (index units)
var modPhaseInc: LyrebirdFloat // FM modulator increment
var modIndex: LyrebirdFloat // FM β (modulation depth)
}
```
### Scheduling (all generators)
```
hopSize = sampleRate / density (samples between grain triggers)
Per sample:
hopCounter += 1
if !hasTriggeredFirstGrain OR hopCounter >= hopSize:
reset hopCounter
find first inactive slot → activate it
(if pool full: skip)
```
### Window
All generators default to `graph.engine.sharedTables.hanningTable`. Pass a custom
`LyrebirdBuffer` to `window:` at `init` to override. The window table is looked up
per active grain per sample using linear interpolation.
### PRNG
All generators use an xorshift64 PRNG seeded at `init` (`seed: UInt64? = nil` for
time-derived, explicit value for reproducibility). Lock-free, allocation-free, RT-safe.
### Output
All generators produce 2 channels [left, right] with grains centred (equal-power pan,
`L = R ≈ sample × 0.707`). Wire through `output(bus: N, source: gen)` — `Out` fans
channel 0 to bus N and channel 1 to bus N+1.
---
## BufferGrain
Reads windowed segments from a pre-recorded `LyrebirdBuffer`.
```swift
public final class BufferGrain: AudioGenerator {
@LiveParam public var density: Double = 10.0 // grains/sec
@LiveParam public var rateSpread: Double = 0.0
@LiveParam public var panSpread: Double = 0.0
public init(buffer: LyrebirdBuffer,
position: any ValidGeneratorInput = 0.5,
positionSpread: any ValidGeneratorInput = 0.0,
duration: any ValidGeneratorInput = 0.1,
amp: any ValidGeneratorInput = 1.0,
pan: any ValidGeneratorInput = 0.0,
pitchRatio: any ValidGeneratorInput = 1.0,
pitchDispersion: any ValidGeneratorInput = 0.0,
density: (any ValidGeneratorInput)? = nil,
window: LyrebirdBuffer? = nil,
loop: Bool = true,
interpolation: TableInterpolation = .linear,
seed: UInt64? = nil,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0)
}
```
**At grain trigger:** `phase = position × bufferFrames ± positionSpread × random`,
`phaseInc = pitchRatio ± pitchDispersion × random ± rateSpread × random`.
---
## SineGrain
Each grain generates a windowed sine tone. Tone parameters are **polled per grain trigger**
from their `ValidGeneratorInput` sources (block-constant via fan-out cache).
```swift
public final class SineGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0 // grains/sec
@LiveParam public var duration: LyrebirdFloat = 0.1 // seconds
public init(freq: any ValidGeneratorInput = 440.0, // Hz, polled at trigger
amp: any ValidGeneratorInput = 0.5, // amplitude, polled at trigger
window: LyrebirdBuffer? = nil,
seed: UInt64? = nil)
}
```
**Per-grain synthesis (table-index domain):**
```
synthPhaseInc = freq × tableSize / sampleRate
per sample:
output = sineTable[synthPhase] (linear interpolation)
synthPhase += synthPhaseInc (wraps modulo tableSize)
```
### Example — frequency spread via generator
```swift
let freqLFO = OscSin.Control(freq: 0.3) * 200.0 + 440.0
let sineGrains = SineGrain(freq: freqLFO, amp: 0.4)
sineGrains.density = 25.0
sineGrains.duration = 0.06
```
---
## FMGrain
Each grain generates a windowed two-operator FM tone. All four parameters are
**polled per grain trigger** from their `ValidGeneratorInput` sources.
```swift
public final class FMGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0
@LiveParam public var duration: LyrebirdFloat = 0.1
public init(carrierFreq: any ValidGeneratorInput = 440.0, // Hz
modFreq: any ValidGeneratorInput = 440.0, // Hz
modIndex: any ValidGeneratorInput = 1.0, // β
amp: any ValidGeneratorInput = 0.5,
window: LyrebirdBuffer? = nil,
seed: UInt64? = nil)
}
```
**FM formula (table-index domain):**
```
modOut = sineTable[modPhase] // ∈ [-1, 1]
fmDisplace = β × modOut × tableSize / (2π)
output = sineTable[carrierPhase + fmDisplace] (linear interpolation)
per sample:
carrierPhase += carrierFreq × tableSize / sampleRate
modPhase += modFreq × tableSize / sampleRate
(both wrap modulo tableSize)
```
`fmGrainTableSizeDivTwoPi = lyrebirdDefaultTableSize / (2π)` is a module-level
constant computed once at load time (never on the RT thread).
### Example — modulation index swept by envelope
```swift
let env = EnvelopeGen.Audio(envelope: ...) * 8.0 // β: 0 → 8 over envelope
let fmGrains = FMGrain(carrierFreq: 330.0, modFreq: 330.0,
modIndex: env, amp: 0.3)
fmGrains.density = 20.0
fmGrains.duration = 0.1
```
---
## InputGrain
Records a live audio input into an internal circular buffer
(`lyrebirdInputGrainSize = 131072` frames, ~3 s at 44 100 Hz) and reads windowed
grains from that history.
```swift
public final class InputGrain: AudioGenerator {
@LiveParam public var density: LyrebirdFloat = 10.0
@LiveParam public var duration: LyrebirdFloat = 0.1
@LiveParam public var position: LyrebirdFloat = 0.0 // 0=recent, 1=oldest
@LiveParam public var positionSpread: LyrebirdFloat = 0.0
@LiveParam public var rate: LyrebirdFloat = 1.0
@LiveParam public var rateSpread: LyrebirdFloat = 0.0
@LiveParam public var amp: LyrebirdFloat = 1.0 // output scaler
public init(input: any ValidGeneratorInput,
window: LyrebirdBuffer? = nil,
captureSize: Int = lyrebirdInputGrainSize,
interpolation: TableInterpolation = .linear,
seed: UInt64? = nil)
}
```
### Position semantics
| `position` | Grain reads from |
|------------|-----------------|
| `0.0` | Most recent captured audio (minimum latency) |
| `0.5` | Middle of capture history |
| `1.0` | Oldest audio in circular buffer |
`positionSpread` adds ± random offset per grain (in capture-buffer fractions).
### Circular buffer
- Size: `lyrebirdInputGrainSize = 131072` frames by default (~3 s at 44 100 Hz,
~2.7 s at 48 000 Hz). Override via `captureSize:` init param.
- Pre-allocated as a `LyrebirdBuffer` at `init`; written via `buffer.write(_:frame:channel:)`.
- Only channel 0 is recorded (mono capture). Use `Out` + `In` routing if stereo capture
is required.
### Example — live microphone granulator
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class MicGranulator: SynthesizerBase {
override func build() {
let mic = input(bus: 0) // live mic on audio input bus 0
let grains = InputGrain(input: mic)
grains.density = 25.0
grains.duration = 0.07
grains.position = 0.05 // 50 ms in the past
grains.positionSpread = 0.02
grains.amp = 0.9
output(bus: 0, source: grains) // stereo out on buses 0 & 1
}
}
```
---
## RT safety summary
| Concern | Handled by |
|---------|-----------|
| No allocation in `_computeSamples` | Pool pre-allocated in `init`; pool-full = silent skip |
| No CoW on output buffer | `_result` is a `var` on a `class`; single owner |
| No CoW on circular buffer | `LyrebirdBuffer` wraps `UnsafeMutablePointer` |
| Randomness | xorshift64 — no syscall, no lock |
| Sine/FM table access | `sharedTables.sineTable` — never invalidated |
| Window table access | `sharedTables.hanningTable` or guarded user `LyrebirdBuffer` |
| Per-grain input polling | `.floatValue(graph:)` routes through fan-out cache — at most one evaluate per block |
---
## Constants (`LyrebirdConstants.swift`)
| Constant | Value | Description |
|----------|-------|-------------|
| `lyrebirdGrainPoolSize` | `64` | Max simultaneous grains per generator |
| `lyrebirdInputGrainSize` | `131072` | Circular capture buffer frames for `InputGrain` |
+367
View File
@@ -0,0 +1,367 @@
# Multi-Channel Expansion (MCE)
Lyrebird supports multi-channel signal flow through two complementary mechanisms:
1. **Multi-row single Generators** — one Generator instance whose internal `_result` has
multiple rows (`Pan2`, the `Pan4` family — `PanAz` / `PanAzDistance` / `PanXY` / `PanXYDistance`, `PanN`, `AmbiEncoder1`, `AmbiDecoder1`, `SVF`, multi-channel
`In` / `BufferRead` / `PlayBuffer`, `FrequencyShifter.Audio`, `Chorus.Audio`,
`TimeStretch.Audio`).
2. **`GeneratorArray`** — explicit wrapper around N independent generators, each
contributing one channel.
The `+ - * /` operators understand both forms — see [Multi-channel operators](#multi-channel-operators)
below.
---
## `outputChannelCount`
Every `Generator` advertises its fixed output channel count via `var outputChannelCount: Int`.
The default (provided by `GeneratorBase`) is `1`. Multi-row generators override to return their
actual channel count (set at `init`, never changes at runtime). The arithmetic operators read
this property to decide how to broadcast across operand pairs.
When writing a custom multi-row Generator, you **must** override `outputChannelCount` to match
the row count of your `_result`. A missing override causes the `+ - * /` operators to treat
your generator as mono, silently dropping channels 1..N-1.
---
## Multi-channel operators
The `+ - * /` operators on `Generator` (and `any ValidGeneratorInput`) produce a
`BinaryOpGenerator` that is channel-aware. The output channel count and per-channel
combination rule are decided at graph-construction time from each operand's
`outputChannelCount`:
| lhs × rhs | Output | Behaviour |
|-----------|--------|-----------|
| `1 × 1` | 1-row | Classic scalar / mono fast path. |
| `1 × N` | N-row | Mono `lhs` broadcasts: row[i] = lhs[0] op rhs[i]. |
| `N × 1` | N-row | Mono `rhs` broadcasts: row[i] = lhs[i] op rhs[0]. |
| `N × N` | N-row | Element-wise: row[i] = lhs[i] op rhs[i]. |
| `N × M`, both > 1, N ≠ M | — | `precondition` traps at `init`. No implicit wrap-extend, no truncation — Lyrebird requires explicit per-channel composition. |
```swift
// Stereo × scalar — both channels scale.
let pan = Pan2(input: osc, pan: -0.3)
output(bus: 0, source: pan * 0.5)
// Mono + stereo — mono broadcasts to both channels.
let dry = OscSin.Audio(freq: 220)
output(bus: 0, source: dry + pan)
// Stereo + stereo — element-wise.
let dry2ch = input(bus: 0, channels: 2)
let wet2ch = input(bus: 4, channels: 2)
output(bus: 0, source: dry2ch * 0.7 + wet2ch * 0.3)
// 2 × 3 — traps. Compose explicitly via channel selection or GeneratorArray.
// stereoGen * tripleGen // precondition fail at init
```
### Channel-aware `mul:` / `add:` parameters
The `mul:` and `add:` parameters on every Generator (`OscSin.Audio(..., mul: x)`,
`SVF.Audio(..., add: y)`, etc.) follow the same broadcast policy as the `*` / `+` operators
above:
- A mono (1-channel) `mul`/`add` broadcasts to every output channel — the historical
scalar-gain case. A scalar literal, a `ParameterNode`, a `Lag`, or any other single-channel
generator works unchanged.
- A multi-channel `mul`/`add` whose channel count matches the output applies element-wise
per channel — useful for per-side gain on a stereo source, per-component scaling on an
ambisonic encoder, etc.
- A multi-channel `mul`/`add` whose channel count does **not** match the output traps via
`precondition` at the apply site (same shape-mismatch policy as `BinaryOpGenerator`).
Use `*` for free composition with the broadcast rules; use `mul:` for scalar gain trims and
matched-shape per-channel modulation that should ride alongside the generator's main output.
---
## GeneratorArray
`GeneratorArray` wraps N independent generators and produces an N-channel
`[[LyrebirdFloat]]`. It conforms to `Generator`, so it participates in the fan-out cache
and can be passed anywhere a `ValidGeneratorInput` is accepted.
```swift
let arr = GeneratorArray([OscSin.Audio(freq: 440.0), OscSin.Audio(freq: 880.0)])
```
### expand()
The `expand(_:factory:)` free function is the idiomatic way to create a `GeneratorArray`
from an array of inputs:
```swift
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
```
### Element-wise operators
All four arithmetic operators work element-wise and return a new `GeneratorArray`:
```swift
let quiet = oscs * 0.5 // each channel × 0.5
let louder = 2.0 * oscs // scalar op GeneratorArray
let sum = oscs + otherOscs // element-wise (counts must match)
let diff = oscs - 0.1 // subtract scalar from each channel
```
Mismatched-count `GeneratorArray op GeneratorArray` is caught by a `precondition` at
build time.
`GeneratorArray op multi-row-generator` (e.g. `oscs * Pan2(...)`) is also caught by a
`precondition`. `GeneratorArray._computeSamples` reads only row 0 of each inner generator,
so a multi-row operand would silently drop channels 1..N-1 inside each element-wise
product. The fix is to compose explicitly via `ChannelSelect` (`pan.left` / `pan.right`)
or by zipping per-channel into a `GeneratorArray`. For arithmetic on multi-row
generators directly, use the `+ - * /` operators on the generator itself (Pan2, SVF, etc.) —
those broadcast properly without needing a `GeneratorArray` wrapper.
---
## Multi-channel Out
`Out` writes each channel of its source to consecutive buses automatically:
| Source channels | Buses written |
|---|---|
| 1 (mono — current default) | `bus` |
| 2 (stereo) | `bus`, `bus + 1` |
| N | `bus` … `bus + N - 1` |
```swift
output(bus: 0, source: Pan2(input: osc, pan: 0.0)) // writes buses 0 and 1
output(bus: 0, source: expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }) // same
```
Mono sources remain unaffected — they return one channel and write only `bus`.
---
## Pan2
Equal-power stereo panner. Maps mono input + pan position `[-1, 1]` to a two-channel
output `[left, right]` using the sine/cosine law:
```
angle = (pan + 1) / 2 × π/2
left = cos(angle) × input
right = sin(angle) × input
```
Power invariant: `left² + right² = input²` at all pan positions.
```swift
output(bus: 0, source: Pan2(input: OscSin.Audio(freq: 440.0), pan: -0.3))
// bus 0 = left (slightly louder), bus 1 = right
```
Pan position accepts any `ValidGeneratorInput` and may be modulated at audio rate.
---
## Multi-channel input
Read N consecutive buses with `input(bus:channels:)` inside `build()`, mirroring
`output(bus:source:)`:
```swift
// Read stereo from buses 2–3, apply gain, route to output buses 0–1
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
```
To read hardware input, use the reserved bus offset:
```swift
// Assuming engine configured with numOutputChannels = 2
output(bus: 0, source: input(bus: engine.numOutputChannels, channels: 2))
```
`In.Audio(bus:channels:)` (or `In.Control(bus:channels:)`) is the underlying constructor
if you need it outside `SynthesizerBase`. The `bus:` parameter accepts any `ValidBus`:
plain `Int`, `AudioBus`, or `ControlBus`.
---
## Common patterns
### Stereo oscillator pair
```swift
override func build() {
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs * 0.5)
}
```
### Stereo panner
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class StereoPanner: SynthesizerBase {
@LiveParam var pan: LyrebirdFloat = 0.0
override func build() {
let osc = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc, pan: $pan))
}
}
```
### Stereo FX return
```swift
override func build() {
// Read wet signal from internal buses 4–5, mix back to output
let wet = input(bus: 4, channels: 2)
let dry = input(bus: 0, channels: 2)
output(bus: 0, source: dry * 0.7 + wet * 0.3)
}
```
---
---
## Inline Channel Selection
Multi-output generators can be decoupled into individual channels without bus routing.
All `AudioGenerator` and `ControlGenerator` instances support a `[n]` subscript and a
`.channel(n)` method that return a `ChannelSelect.Audio` (or `.Control`) wrapping the
source and extracting channel `n`. Out-of-range indices return silence — no crash.
Named semantic aliases are provided on specific generators as ergonomic sugar over `[n]`.
### Named aliases
| Generator | Property | Channel | Notes |
|---|---|---|---|
| `Pan2` | `.left` | 0 | |
| `Pan2` | `.right` | 1 | |
| `Pan4` subclasses (`PanAz`, `PanAzDistance`, `PanXY`, `PanXYDistance`) | `.frontLeft` | 0 | inherited from `Pan4` |
| `Pan4` subclasses | `.frontRight` | 1 | |
| `Pan4` subclasses | `.rearRight` | 2 | |
| `Pan4` subclasses | `.rearLeft` | 3 | |
| `FreqTracker` | `.freq` | 0 | Hz, 0.0 when no pitch |
| `FreqTracker` | `.confidence` | 1 | [0, 1] |
### Dynamic-channel generators
Generators whose channel count is determined at `init` also support `[n]`:
| Generator | Channel count | Index meaning |
|---|---|---|
| `PlayBuffer` | `buffer.channelCount` | one per audio file channel |
| `PanN` | `channels` (init param) | one per speaker in the ring |
| `AmbiEncoder1` | 4 | 0=W, 1=X, 2=Y, 3=Z |
| `AmbiDecoder1` | `speakers.count` (init param) | one per loudspeaker |
| `GeneratorArray` | `generators.count` | one per wrapped generator |
Out-of-range `[n]` always returns silence — no crash.
### Examples
```swift
// Pan2 — named or numeric
let pan = Pan2(input: src, pan: -0.3)
output(bus: 0, source: pan.left) // same as pan[0]
output(bus: 1, source: pan.right) // same as pan[1]
// Mono fold-down inline
output(bus: 0, source: pan[0] + pan[1])
// FreqTracker — no buses required
let tracker = FreqTracker(in: mic)
let osc = OscSin.Audio(freq: tracker.freq * 2.0)
output(bus: 0, source: osc * tracker.confidence)
// Generic subscript on any generator
output(bus: 0, source: PanXY(input: src)[2]) // rear-right channel
// PlayBuffer — route channels independently
let player = PlayBuffer.Audio(buffer: stereoBuffer)
let rev = SomeReverb(input: player[0])
output(bus: 0, source: player[0] * 0.7 + rev * 0.3)
output(bus: 1, source: player[1])
// AmbiEncoder1 — extract individual B-format components
let enc = AmbiEncoder1(input: src)
let W = enc[0] // omni
let X = enc[1] // front-back
// AmbiDecoder1 — per-speaker processing (encoder feeds decoder directly).
// Use AmbiSpeakerLayout for the common symmetric rigs (quad / hexagon /
// octagon / cube / doubleHexagon / doubleOctagon) or stackedRings(...).
let dec = AmbiDecoder1(input: enc, speakers: AmbiSpeakerLayout.quad())
output(bus: 0, source: dec[0] * frontGain)
output(bus: 1, source: dec[1] * frontGain)
output(bus: 2, source: dec[2])
output(bus: 3, source: dec[3])
// PanN — extract individual speakers
let ring = PanN(input: src, channels: 8, position: lfo)
output(bus: 0, source: ring[0]) // speaker 0 only
output(bus: 4, source: ring[4]) // speaker 4 only
// MCE decoupling — GeneratorArray subscript
let oscs = expand([440.0, 880.0, 1320.0]) { OscSin.Audio(freq: $0) }
output(bus: 0, source: oscs[0] + oscs[1]) // mix first two partials only
// Stereo signal → per-channel analysis → four signals inline (no buses)
let stereo = PlayBuffer.Audio(buffer: stereoBuffer) // 2-channel
let trackerL = FreqTracker(in: stereo[0]) // left → [freq, confidence]
let trackerR = FreqTracker(in: stereo[1]) // right → [freq, confidence]
output(bus: 0, source: OscSin.Audio(freq: trackerL.freq) * trackerL.confidence)
output(bus: 1, source: OscSin.Audio(freq: trackerR.freq) * trackerR.confidence)
```
### Fan-out guarantee
`pan.left` and `pan.right` both hold a reference to the same `Pan2` instance. When both
are evaluated in one segment, the segment-serial cache ensures `Pan2._computeSamples`
fires exactly once — both selectors see sample-consistent data at zero extra cost.
### GeneratorArray note
`GeneratorArray` also supports `[n]`, returning `ChannelSelect.Audio` that selects the
Nth channel of the entire array's output. For the raw generator instance, use `.generators[n]`.
---
## Angle convention
Every panning and ambisonic generator that accepts an azimuth, elevation, spread,
or rotation parameter takes the angle in **radians** — never degrees. Affected:
`AmbiEncoder1` (`azimuth`, `elevation`), `AmbiDecoder1` (`speakers: [(az, el)]`),
`AmbiDecoderMono` (`azimuth`, `elevation`), `AmbiEncoderStereo` (`spread`),
`AmbiSpeakerLayout` (`elevation`, `azimuthOffset`), `PanAz` / `PanAzDistance`
(`azimuth`).
Convert at the language-side boundary (UI knobs, OSC messages, score files
authored in degrees) with `degreesToRadians(_:)` / `radiansToDegrees(_:)` from
`LyrebirdMusicMath`. Array overloads and `Collection<Double>.degreesToRadians()` /
`.radiansToDegrees()` are also available for batched layout setup.
```swift
let enc = AmbiEncoder1(input: src, azimuth: degreesToRadians(45.0))
```
The `Pan2` / `PanN` / `PanXY` family is the exception — those take normalised
position in `[-1, 1]` and apply their own internal scaling.
---
## See Also
- `Sources/Lyrebird/Generators/ChannelSelect.swift` — `ChannelSelect.Audio/.Control`, `[n]` subscript
- `Sources/Lyrebird/GeneratorCore/GeneratorArray.swift` — `GeneratorArray` type, operators, `expand()`
- `Sources/Lyrebird/Generators/Pan2.swift` — stereo panner
- `Sources/Lyrebird/Generators/Out.swift` — multi-channel write logic
- `Sources/Lyrebird/Generators/In.swift` — `In.multi(bus:channels:)`
- `docs/engine/bus-system.md` — bus layout and reserved ranges
- `docs/protocols/writing-generators.md` — Pattern 4 (multi-output generators), Pattern 5 (MCE), Pattern 6 (channel selection)
+577
View File
@@ -0,0 +1,577 @@
# Spectral Processing
FFT / IFFT infrastructure using Accelerate/vDSP with a polar-primary buffer. The analysis + processor + IFFT pipeline is consolidated into one `SpectralChain.Audio` Generator. The legacy `FFTAnalysis` + `IFFTSynthesis` generators have been removed entirely; a synthOnly mode drives the IFFT bank from an external `SpectralBufferGenerator` (e.g. `SpectralBufferRead`, `SpectralPlayBuffer`).
## Overview
| Layer | Type | Role |
|---|---|---|
| `SpectralBuffer` | Data container | Polar (magnitude + phase) FFT frame |
| `SpectralChain.Audio` | `AudioGenerator` | Consolidated STFT pipeline: forward FFT → processor chain → optional sidechain → optional fan-out → N × IFFT. Four modes. |
| `SpectralProcessor` | Protocol | In-place polar transform called after each FFT hop |
| `SpectralProcessor2` | Protocol | Two-input processor (cross-synthesis / sidechain) |
| `SpectralFanOutProcessor` | Protocol | Mono → N decorrelation processor (writes per-channel destination buffers) |
| `SpectralBufferGenerator` | Protocol | A `Generator` that owns + populates its own `spectralBuffer` each hop; drives synthOnly mode of `SpectralChain.Audio` |
| `SpectralBufferRead` | `SpectralBufferGenerator` | Random-access frame playback via normalized position |
| `SpectralPlayBuffer` | `SpectralBufferGenerator` | Phase-vocoder playback with time-stretch |
### SpectralChain.Audio — four operating modes
```swift
// 1. Mono resynthesis — audio in, audio out:
let chain = SpectralChain.Audio(
input: signal,
fftSize: 2048,
hopSize: 512,
stages: [.mono(SpectralDiffuse(fftSize: 2048, amount: 0.5))]
)
output(bus: 0, source: chain)
// 2. Mono → N fan-out (stereo decorrelation example):
let diffuser = SpectralStereoDiffuse(amount: 0.8)
let stereoChain = SpectralChain.Audio(
input: monoIn,
fftSize: 2048,
fanOut: diffuser
)
output(bus: 0, source: stereoChain[0])
output(bus: 1, source: stereoChain[1])
// 3. Analyze-only for feature extraction or sidechain:
let analysisOnly = SpectralChain.Audio(
input: signal,
fftSize: 2048,
analyzeOnly: true
)
let centroid = SpectralCentroid.Control(analysis: analysisOnly,
sampleRate: engine.sampleRate)
// 4. SynthOnly — IFFT bank driven by a pre-analysed frame buffer:
let player = SpectralPlayBuffer(frameBuffer: frames, fftSize: 2048, hopSize: 512)
let synth = SpectralChain.Audio(spectralSource: player,
fftSize: 2048, hopSize: 512)
output(bus: 0, source: synth)
```
### Mono → N decorrelation
`SpectralFanOutProcessor` is a processor shape that reads the source spectral buffer (post-`SpectralProcessor` chain) and writes a full polar spectrum into each of N destination buffers. The host `SpectralChain.Audio` then runs N IFFTs to produce N audio output channels.
**`SpectralStereoDiffuse`** is the first conformer. Mono → stereo. Magnitudes pass through unchanged. Phases blend toward independent per-channel uniform random targets via shortest-angular-distance interpolation. Channels 0 and 1 draw from anti-correlated xorshift64 streams (seeded from `seed` and `seed ^ spectralStereoDiffuseAntiSeedMask`).
```swift
let diff = SpectralStereoDiffuse(amount: 0.8, seed: 0xDEADBEEF)
let chain = SpectralChain.Audio(input: monoIn, fftSize: 2048, fanOut: diff)
```
- `amount == 0` is exact bypass; both output channels equal the input.
- `amount == 1` is full per-channel randomisation, producing a wide decorrelated stereo image with magnitude conserved per bin.
- Magnitude conservation guarantees per-channel energy is preserved; summing L + R does **not** reconstruct the input (the random phase realisations interfere).
### Conversion flow per hop (non-synthOnly modes)
```
SpectralChain.Audio._runAnalysisHop()
vDSP_fft_zrip (forward) → private _fftAnalysisRealp/Imagp
_writeFromRectangular → spectralBuffer (polar: mag + phase)
[Processor chain — all in polar]
[Optional fan-out: SpectralFanOutProcessor → per-channel destinations]
SpectralChain.Audio._runIFFTBank() (one IFFT per output channel)
_readToRectangular → per-channel work arrays
vDSP_fft_zrip (inverse) + WOLA overlap-add → per-channel audio output
```
In synthOnly mode, `_runAnalysisHop` skips windowing + forward FFT + polar conversion; the source `SpectralBufferGenerator` has already populated `spectralBuffer` during its own `_computeSamples`. Registered processors and fan-out run as usual on the source's buffer, then the IFFT bank resynthesises.
### vDSP normalization
vDSP forward real FFT multiplies output by 2 (Apple convention). After rect→polar conversion, `dcValue` reflects this:
```
buf.dcValue ≈ 2 × Σ window[n] × input[n]
```
The synthesis-side WOLA normalisation factor `1 / (2N × Σ w²[n] / hopSize)` is pre-multiplied into the synthesis window at init, so a single `vDSP_vmul` in the IFFT path handles windowing + gain correction. Round-trip unity gain holds at any integer overlap ratio with the default sine window.
### Latency
Output is delayed by exactly `hopSize` samples (one hop). Block 0 outputs silence; block 1 outputs the first IFFT result.
### Precision note
Polar conversion uses `vDSP_zvmags + vvsqrtf + vvatan2f`; the inverse path uses `vvcosf + vvsinf + vDSP_vmul`. The round-trip introduces ~1e-7 float error per hop — inaudible in practice. Pass-through with no processors is not bit-exact with raw rectangular processing.
---
## SpectralBuffer
Holds one FFT frame in **polar form**: magnitudes and phases stored as `UnsafeMutablePointer<Float>` — addresses are stable for the object's lifetime, no Swift Array CoW.
DC and Nyquist are purely real (no meaningful phase); they are stored as signed scalars and accessed via properties, not subscripts.
```swift
let buf = SpectralBuffer(fftSize: 2048)
// DC and Nyquist — signed scalars
buf.dcValue // signed DC (may be negative)
buf.dcValue = -3.0 // set directly
buf.nyquistValue // signed Nyquist
buf.nyquistValue = 2.5
// Complex bins k = 1 ..< fftSize/2
buf[magnitude: k] // magnitude of bin k (≥ 0)
buf[magnitude: k] = 5.0 // set magnitude
buf[phase: k] // phase of bin k (radians, in (−π, π])
buf[phase: k] = Float.pi / 4
// Convenience — works for all bins including DC (0) and Nyquist (fftSize/2)
buf.magnitude(at: 0) // abs(dcValue)
buf.magnitude(at: 1024) // abs(nyquistValue) — Nyquist bin for fftSize=2048
buf.magnitude(at: k) // _mag[k] for complex bins
buf.phase(at: k)
buf.setMagnitude(1.0, at: k)
buf.invalidate() // non-RT — signals the chain to output silence
```
### Buffer layout
For `fftSize = N`:
| Accessor | Content |
|---|---|
| `dcValue` | Signed DC component |
| `[magnitude: k]`, `[phase: k]` for k=1..N/2-1 | Complex bin k |
| `nyquistValue` | Signed Nyquist component |
---
## SpectralProcessor protocol
```swift
public protocol SpectralProcessor: AnyObject {
func process(spectral: SpectralBuffer, engine: SynthesisEngine)
}
```
`process` is called on the RT thread from inside `SpectralChain.Audio._runAnalysisHop`. Implementations must not allocate memory or acquire locks. The buffer is in polar form — read magnitudes and phases directly, modify in-place.
`engine` is the host engine. Processors that hold ``RTBufferSlot``-backed parameter buffers (e.g. `SpectralBinDelay`, `SpectralMagnitudeMap`) use it to push displaced retains to `engine.bufferSwapKillQueue` from the RT thread. Processors with no swappable state can ignore the parameter.
For vDSP batch operations on complex bins, use the package-internal helpers:
```swift
// Inside a SpectralProcessor implementation:
spectral.withUnsafeMutableMagnitudePointer { mp in
// mp points to _mag[1] — valid for fftSize/2-1 elements (bins 1..halfSize-1)
vDSP_vsmul(mp, 1, &scale, mp, 1, vDSP_Length(spectral.fftSize / 2 - 1))
}
spectral.withUnsafeMutablePhasePointer { pp in
// pp points to _phase[1] — same element count
}
```
## SpectralFanOutProcessor protocol
```swift
public protocol SpectralFanOutProcessor: AnyObject {
var outputChannelCount: Int { get }
func process(source: SpectralBuffer,
into: SpectralBuffer,
channel: Int)
}
```
Called once per output channel by the host `SpectralChain.Audio` after the `SpectralProcessor` chain has run. The source buffer is read-only from the fan-out's perspective (any single-input processor that needed to mutate it has already done so); the destination buffer is per-channel scratch that the host's IFFT bank then reads.
## SpectralBufferGenerator protocol
```swift
public protocol SpectralBufferGenerator: Generator {
var spectralBuffer: SpectralBuffer { get }
var hopSize: Int { get }
}
```
A `Generator` that owns + populates its own `spectralBuffer` each hop. Built-in conformers: `SpectralBufferRead` (random-access frame playback by normalized position), `SpectralPlayBuffer` (phase-vocoder frame playback with time-stretch). Use as `spectralSource:` arg of `SpectralChain.Audio` to drive synthOnly mode.
Both source and host chain advance internal sample-by-sample hop counters from 0 at construction. Matching `hopSize` keeps them aligned within an audio block. A precondition in `SpectralChain.Audio.init` catches `hopSize` / `fftSize` mismatches at construction time.
---
## Built-in processors
### SpectralMagnitudeScale
Multiplies all bin magnitudes (including DC and Nyquist) by a constant factor.
```swift
let chain = SpectralChain.Audio(input: sig,
stages: [.mono(SpectralMagnitudeScale(scale: 0.5))])
output(bus: 0, source: chain)
```
### SpectralFreeze
Phase-vocoder freeze: captures magnitudes and phases, then advances each bin's phase by its locked instantaneous delta on every frozen hop.
```swift
let freeze = SpectralFreeze(fftSize: 2048)
let chain = SpectralChain.Audio(input: sig, stages: [.mono(freeze)])
output(bus: 0, source: chain)
// To freeze (call from non-RT thread):
freeze.freeze()
// To unfreeze:
freeze.unfreeze()
```
`freeze()` sets an `Atomic<Bool>` flag; the RT thread captures the polar frame (magnitude + phase) on the next hop — no rect→polar conversion needed since the buffer already stores polar data.
### OnsetDetector
Per-hop onset detector. Computes an onset-detection function (ODF) — either half-wave-rectified spectral flux or complex-domain prediction error — on every FFT hop, smooths the ODF with a rolling median to derive an adaptive threshold, and increments an atomic onset counter when the latest ODF exceeds `max(rollingMedian, floor) * threshold`. A configurable refractory window (`minHopsBetweenOnsets`) suppresses double-triggering on the tail of an attack.
`OnsetDetector` itself is a `SpectralProcessor`; pair it with an `OnsetDetector.Control` generator to surface the detected onsets as a trigger signal. `OnsetDetector.Control` emits a single-sample pulse at sample `0` of any audio block during which one or more onsets fired (zero otherwise) — guaranteeing a clean ≤0 → >0 edge for downstream `SendTrigger.Control` even on back-to-back onset blocks.
```swift
let detector = OnsetDetector(
fftSize: 2048,
hopSize: 512,
method: .spectralFlux, // .complexDomain for soft / pitched onsets
threshold: 1.5,
medianWindowFrames: 7,
minHopsBetweenOnsets: 3
)
let chain = SpectralChain.Audio(
input: micIn, fftSize: 2048, hopSize: 512,
stages: [.mono(detector)], analyzeOnly: true
)
let trig = OnsetDetector.Control(detector: detector, analysis: chain)
addOutputGenerator(SendTrigger.Control(trig: trig, id: 1))
```
`threshold` and `minHopsBetweenOnsets` are backed by `Atomic` storage and may be tuned from a non-RT thread at any time. `lastODF` and `lastMedian` expose the most recent RT-side telemetry for visualisation. Reference: Bello et al., "A Tutorial on Onset Detection in Music Signals", IEEE TSAP 2005.
---
## Spectral Filtering & Phase
A family of bin-domain processors for filtering, EQ, phase manipulation, and magnitude smearing. All operate directly on `SpectralBuffer` polar storage — no rectangular conversion — and are RT-safe. All scalar parameters that may be retuned at runtime are backed by `Atomic<…>`; updates take effect on the next FFT hop.
### SpectralBrickwall
Hard brick-wall filter with `.lp` / `.hp` / `.bp` / `.br` modes. Cutoffs in Hz are converted to nearest bin indices and magnitudes outside the pass band are zeroed via `vDSP_vclr`. Phase is untouched.
```swift
let lp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .lp, highHz: 4000)
let bp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .bp, lowHz: 200, highHz: 2000)
lp.lowHz = 100 // live retune
```
### SpectralPhaseShift
Adds a constant offset to every complex bin's phase, leaving magnitude untouched. `.deg90` is equivalent to a Hilbert transform (analytic-signal imaginary part); `.deg180` flips DC + Nyquist sign; `.radians(_:)` allows arbitrary fixed shifts. The `radians` property accepts live updates of the complex-bin offset; the DC/Nyquist sign-flip behaviour is fixed at init by the chosen `PhaseShiftAmount`.
```swift
let hilbert = SpectralPhaseShift(fftSize: 2048, shift: .deg90)
let custom = SpectralPhaseShift(fftSize: 2048, shift: .radians(0.3))
custom.radians = 1.0
```
### SpectralGate
Per-bin spectral gate. Bins whose magnitude is below `threshold` are scaled by `floor` (∈ `[0, 1]`); bins above pass through. `floor = 0` is a hard gate; `floor = 1` is bypass. DC and Nyquist gate on `abs(value)` and preserve sign. A `thresholdDB:` convenience initialiser converts dB to linear magnitude.
```swift
let gate = SpectralGate(fftSize: 2048, thresholdDB: -40, floor: 0.1)
gate.threshold = 0.05 // live retune (linear)
```
### SpectralTilt
Tilt EQ in the spectral domain: applies a constant dB/octave slope around a pivot frequency. The per-bin gain table is pre-computed at init from `slopeDBPerOctave` and `pivotHz`, so `process` is pure `vDSP_vmul`. `slope = 0` produces unity gain everywhere. `slope` and `pivot` are init-only.
```swift
let darken = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: -3, pivotHz: 1000)
let sparkle = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: +6, pivotHz: 1000)
```
### SpectralBlur
Magnitude moving-average ("box blur") across complex bins. Smears spectral peaks into plateaus of width `2 · radius + 1`. Edge bins shrink the window rather than wrap. Computation uses a running sum, so cost is O(halfSize) per hop regardless of `radius`. Phase is untouched.
```swift
let blur = SpectralBlur(fftSize: 2048, radius: 4)
blur.radius = 12 // wider smear
```
### SpectralDiffuse
Continuous phase-randomisation. Each hop, every complex bin's phase is blended by `amount ∈ [0, 1]` toward a freshly drawn uniform random target. `0` is bypass; `1` is full randomisation; intermediate values produce continuous spectral smearing — useful for transient softening, reverb-like washes, and "frozen cloud" effects when combined with `SpectralFreeze`.
```swift
let diffuse = SpectralDiffuse(fftSize: 2048, amount: 0.5)
diffuse.amount = 1.0 // full smear
```
### SpectralConvolve
Frequency-domain convolution: per-bin complex multiply between the live spectrum and a second `SpectralBuffer` (`other`). Equivalent to time-domain circular convolution of the two underlying signals. `other` is typically populated by either a parallel `SpectralChain.Audio` chain (cross-synthesis or matched filtering) or a static impulse response prepared once at startup. Either buffer being invalid causes the live buffer to be cleared.
```swift
let irBuf = SpectralBuffer(fftSize: 2048)
// ... populate irBuf from a precomputed impulse-response FFT frame ...
let conv = SpectralConvolve(spectralBuffer: liveBuf, other: irBuf)
let chain = SpectralChain.Audio(input: dryIn, fftSize: 2048, hopSize: 512,
stages: [.mono(conv)])
output(bus: 0, source: chain)
```
### SpectralFormantShift
Magnitude-envelope-preserving formant shifter. Estimates the smooth spectral envelope of the current frame, whitens the spectrum by dividing it out, resamples the envelope along the bin axis by `shiftRatio`, and reapplies the shifted envelope to the whitened residual. Phase is untouched. Pairs with `SpectralPitchShift` to decouple pitch from formant motion.
Two envelope-estimation methods:
- `.cepstral` (default) — real cepstrum with a low-quefrency lifter. Accurate; uses a second `FFTSetup` allocated at init.
- `.magnitudeSmoothing(radiusBins:)` — box moving-average of magnitudes. Cheaper; coarser envelope.
`shiftRatio` is `Atomic<Float>` and clamped to `[0.25, 4.0]`. `1.0` is bypass; `< 1.0` lowers formants; `> 1.0` raises them and fades bins whose source position falls above Nyquist to 0. DC and Nyquist participate in envelope estimation as unsigned magnitudes; their signs are preserved when the reshaped magnitude is written back.
```swift
// Pitch down an octave, keep formants in place:
let pitch = SpectralPitchShift(fftSize: 2048, hopSize: 512, pitchRatio: 0.5)
let formant = SpectralFormantShift(fftSize: 2048, shiftRatio: 2.0)
let chain = SpectralChain.Audio(input: voice, fftSize: 2048, hopSize: 512,
stages: [.mono(pitch), .mono(formant)])
output(bus: 0, source: chain)
formant.shiftRatio = 1.5 // live retune
```
---
## Complete example
```swift
final class SpectralPatch: SynthesizerBase {
let mic = In.Audio(bus: 0)
let freeze = SpectralFreeze(fftSize: 2048)
lazy var chain = SpectralChain.Audio(
input: mic, fftSize: 2048, hopSize: 512, stages: [.mono(freeze)]
)
override func build() {
output(bus: 0, source: chain)
}
}
// Freeze on button press (main thread):
freeze.freeze()
```
---
## Closure-driven spectral processors
`SpectralPolarClosure` and `SpectralComplexClosure` are `SpectralProcessor` conformers that
wrap an arbitrary user function. They provide the same role for spectral DSP that
`Closure` plays for time-domain DSP — rapid prototyping of spectral transforms
inline inside a `Synthesizer.build()` body, without writing a separate class.
### SpectralPolarClosure
Provides direct zero-copy access to the `SpectralBuffer`'s polar storage
(magnitudes and phases) on each FFT hop. No coordinate conversion — the buffer already
stores polar data. This is the cheapest spectral closure variant.
```swift
// 6 dB magnitude attenuation across all complex bins + DC + Nyquist:
let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5
}
ctx.dcValue.pointee *= 0.5
ctx.nyquistValue.pointee *= 0.5
}
let chain = SpectralChain.Audio(input: sig, fftSize: 2048, stages: [.mono(halver)])
output(bus: 0, source: chain)
```
**Context layout** (`SpectralPolarContext`):
| Property | Type | Content |
|---|---|---|
| `magnitudes` | `UnsafeMutableBufferPointer<Float>` | Complex bin magnitudes, length `fftSize/2 - 1` (bins 1 ..< `fftSize/2`) |
| `phases` | `UnsafeMutableBufferPointer<Float>` | Complex bin phases (radians), same length |
| `dcValue` | `UnsafeMutablePointer<Float>` | Signed DC component (bin 0) |
| `nyquistValue` | `UnsafeMutablePointer<Float>` | Signed Nyquist component (bin `fftSize/2`) |
| `binCount` | `Int` | Number of complex bins = `fftSize/2 - 1` |
| `sampleRate` | `Double` | Engine sample rate in Hz |
| `fftSize` | `Int` | FFT frame size |
| `hopSize` | `Int` | Samples between hops |
| `frameIndex` | `Int` | Zero-based hop counter since processor creation |
Addressing spectral bin `k` (where `k ≥ 1`): `ctx.magnitudes[k - 1]`, `ctx.phases[k - 1]`.
### SpectralComplexClosure
Provides Cartesian (split-complex real + imaginary) access to the spectral frame.
The framework performs a polar→Cartesian conversion before the closure and a
Cartesian→polar conversion after it, so the buffer is always up to date for downstream
processors. Use this when your transform is naturally expressed in rectangular form
(complex multiplication, comb filtering, phase rotation).
**Round-trip cost:** one vectorised `vvcosf + vvsinf + vDSP_vmul` pass (polar→Cartesian)
and one `vDSP_zvmags + vvsqrtf + vvatan2f` pass (Cartesian→polar) per hop. Negligible
at typical FFT sizes but non-zero. Prefer `SpectralPolarClosure` for magnitude-only
or phase-only transforms.
```swift
// Simple 6 dB magnitude scale in Cartesian space (less efficient than polar but illustrative):
let halver = SpectralComplexClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.real[i] *= 0.5
ctx.imag[i] *= 0.5
}
}
```
**Context layout** (`SpectralComplexContext`):
| Property | Type | Content |
|---|---|---|
| `real` | `UnsafeMutableBufferPointer<Float>` | Split-complex real parts, length `fftSize/2` |
| `imag` | `UnsafeMutableBufferPointer<Float>` | Split-complex imaginary parts, length `fftSize/2` |
| `binCount` | `Int` | = `fftSize/2` (includes packed DC/Nyquist at index 0) |
| `sampleRate` | `Double` | Engine sample rate in Hz |
| `fftSize` | `Int` | FFT frame size |
| `hopSize` | `Int` | Samples between hops |
| `frameIndex` | `Int` | Zero-based hop counter since processor creation |
Split-complex packing convention (matches vDSP):
- `real[0]` = DC value; `imag[0]` = Nyquist value.
- `real[k]` = real part of complex bin `k`; `imag[k]` = imaginary part (for `k = 1..<binCount`).
### RT-safety contract
Both closure variants execute on the RT audio thread. The closure body must:
- Not allocate heap memory (no `Array(...)`, no `class` instantiation).
- Not acquire locks.
- Not call `print`, `NSLog`, or any `String`-constructing API.
- Not `throw`.
These constraints are identical to `Closure` and are architecturally
unenforceable. Violations cause audio dropouts. Pre-allocate any scratch storage
before audio starts (e.g. via `UnsafeMutablePointer.allocate` at `build()` time)
and capture the pointer in the closure's capture list.
---
## RT safety summary
| Component | RT-safe | How |
|---|---|---|
| `SpectralChain.Audio._runAnalysisHop` | ✓ | FFT into private work arrays; vectorized rect→polar into spectralBuffer raw pointers |
| `SpectralChain.Audio._runIFFTBank` | ✓ | Vectorized polar→rect into per-channel work arrays; raw pointer IFFT; OLA via `vDSP_vadd` |
| `SpectralMagnitudeScale.process` | ✓ | `vDSP_vsmul` in-place on `_mag` pointer; scalar DC/Nyquist multiply |
| `SpectralFreeze.process` | ✓ | Reads polar directly from buffer (no atan2f); writes polar back; no allocation |
| `SpectralFreeze.freeze()` | non-RT only | Sets `Atomic<Bool>` flag; RT thread captures polar on next hop |
| `OnsetDetector.process` | ✓ | Pre-allocated per-bin and ring buffers; `Atomic<Float>` params; manual selection-sort median (no Swift `sort`) |
| `SpectralBufferRead._runHop` | ✓ | Pre-allocated interpolation scratch; vDSP interpolation; `floatValue` for position read |
| `SpectralPlayBuffer._runHop` | ✓ | Pre-allocated phase-vocoder scratch; `Atomic<Double>` rate; no allocation |
| `SpectralPolarClosure.process` | ✓ (body is user's responsibility) | Zero-copy direct pointer into `_mag[1]`/`_phase[1]`; DC/Nyquist via pre-allocated single-element pointers |
| `SpectralComplexClosure.process` | ✓ (body is user's responsibility) | Polar→rect via `_readToRectangular`; user closure on pre-allocated scratch; rect→polar via `_writeFromRectangular` |
---
## Live parameter-buffer swap
Two built-in processors hold per-bin parameter buffers that can be replaced on a
running engine without rebuilding the synth graph. Both use ``RTBufferSlot``
internally — see ``BufferGuide`` § "Live Buffer Swap" for the full pattern.
### SpectralBinDelay
```swift
let delays = LyrebirdBuffer(count: halfSize)
let feedbacks = LyrebirdBuffer(count: halfSize)
delays.fill { i, n in Double(i) / Double(n) * 0.5 }
feedbacks.fill(with: 0.6)
let bd = SpectralBinDelay(fftSize: 2048, hopSize: 512,
maxDelaySeconds: 1.0, sampleRate: 44_100,
delayTimes: delays, feedbacks: feedbacks)
// Later, mid-piece:
let newDelays = LyrebirdBuffer(count: halfSize)
newDelays.fill { i, n in Double(i) / Double(n) * 0.25 } // halve the spread
bd.setDelayTimes(newDelays, engine: engine)
// Or silence the processor:
bd.setFeedbacks(nil, engine: engine)
```
Preconditions: both buffers must be mono and have `count >= fftSize/2`. When
either slot is empty or its loaded buffer is invalid, the hop is skipped
(no spectral mutation — output passes through unchanged).
### SpectralMagnitudeMap
```swift
let curve = LyrebirdBuffer(count: 256)
curve.fill { i, n in pow(Double(i) / Double(n - 1), 2.0) } // squared compression
let map = SpectralMagnitudeMap(buffer: curve)
// Swap to a steeper curve:
let steep = LyrebirdBuffer(count: 256)
steep.fill { i, n in pow(Double(i) / Double(n - 1), 4.0) }
map.setBuffer(steep, engine: engine)
// Or bypass (input magnitudes pass through unchanged):
map.setBuffer(nil, engine: engine)
```
Precondition: buffer must be mono with `count >= 2`.
### Authoring a swap-aware SpectralProcessor
The protocol's `engine: SynthesisEngine` argument is the host engine for the
chain — pass it to `RTBufferSlot.load(engine:)` inside your `process` body.
If your processor has no swappable state, ignore it.
```swift
public final class MyEnvelopeMask: SpectralProcessor {
private let _slot: RTBufferSlot
private let _halfSize: Int
public init(fftSize: Int, mask: LyrebirdBuffer) {
precondition(mask.count >= fftSize / 2 && mask.channelCount == 1)
self._slot = RTBufferSlot(initial: mask)
self._halfSize = fftSize / 2
}
public func setMask(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
if let buffer {
precondition(buffer.count >= _halfSize && buffer.channelCount == 1)
}
_slot.swap(buffer, engine: engine)
}
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
guard let mask = _slot.load(engine: engine), mask.isValid else { return }
spectral.withUnsafeMutableMagnitudePointer { mp in
for i in 0..<(_halfSize - 1) {
mp[i] *= Float(mask[i + 1])
}
}
}
}
```