Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/Generators/GranularSynthesis.md
T
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

11 KiB
Raw Blame History

Granular Synthesis

@Metadata { @PageKind(article) }

Lyrebird's granular family covers six time-domain grain-based generators plus one formant-grain (FOF) synthesiser. Each produces output by overlapping short windowed grains; they differ in what the grain plays back (a wavetable, a buffer, a sine, an FM pair, a live input stream, or an exponentially-decaying formant pulse).

Granular vs. spectral: Granular generators operate entirely in the time domain — no FFT, low CPU, sample-accurate response. The spectral pitch shifter (SpectralPitchShift) and SpectralChain.Audio-chain processors operate in the frequency domain and have hop-size latency. See doc:PitchShifting for the pitch-shift family overview.


Overview

Source material Output Density driver Pre-allocated pool
BufferGrain Static LyrebirdBuffer Stereo (panned) density Hz, default 1/duration lyrebirdGrainPoolSize (64)
SineGrain Internal sine Stereo (panned) density Hz 64
FMGrain Internal FM pair Stereo (panned) density Hz 64
InputGrain Live audio (circular capture buffer) Stereo (panned) density Hz 64
PitchShift Live audio (circular capture buffer) Mono Auto: windowSize / overlap 64
TimeStretch Static LyrebirdBuffer N channels (matches buffer.channelCount) Auto: windowSize / overlap 64
FormantGrain Internal sine + envelope Mono glottalFreq Hz 64 (steal-oldest on overflow)

All seven share a fixed grain pool (lyrebirdGrainPoolSize = 64). All inputs that accept any ValidGeneratorInput may be driven by other generators, scalars, or @LiveParam properties.


Density-Driven vs. Hop-Driven Triggering

Granular generators in Lyrebird divide into two scheduling families:

Density-driven (BufferGrain, SineGrain, FMGrain, InputGrain)

A density parameter (Hz) sets the grain trigger rate. Pass nil (the default) to auto-derive density from duration so adjacent grains tile end-to-end without overlap. Triggers beyond pool capacity are dropped.

// Default: one grain at a time, ~10 grains/sec
let g = SineGrain(freq: 440.0, duration: 0.1)

// Dense overlapping cloud (50 grains/sec, each 100 ms long → ~5× overlap)
let cloud = SineGrain(freq: 440.0, duration: 0.1, density: 50.0)

Hop-driven (PitchShift, TimeStretch)

These generators always maintain overlap simultaneous grains (default 4) and trigger new grains every windowSize / overlap seconds. There is no density parameter — pitch and time are decoupled by the grain mechanism itself.

Glottal-pulse-driven (FormantGrain)

Triggers exactly one grain per glottal pulse at glottalFreq Hz. Pool overflow triggers the steal-oldest policy (kills the longest-running grain to make room) — this is unique to FormantGrain; the density-driven and hop-driven generators silently drop overflow triggers.


BufferGrain — Buffer-Reading Granular

Reads short overlapping windowed grains from any pre-loaded LyrebirdBuffer. Each grain reads at its own pitchRatio and is panned to its own random or assigned position.

Quick start

let buf = try LyrebirdBuffer.load(url: someAudioFileURL)
let g = BufferGrain(
    buffer: buf,
    position: 0.5,            // normalized buffer position [0, 1]
    positionSpread: 0.05,     // ±5% random offset per grain
    duration: 0.1,            // grain length in seconds
    amp: 0.4,
    pan: 0.0,                 // centre, ±0 spread
    pitchRatio: 1.0,          // playback rate (×)
    pitchDispersion: 0.05,    // ±5% random pitch per grain
    density: 30.0             // grains/sec
)
output(bus: 0, source: g)     // 2-channel; Out fans to bus 0 + bus 1

Parameters

Parameter Default Notes
buffer required Source LyrebirdBuffer
position 0.5 Normalized read position [0, 1]; multi-channel buffers read all channels
positionSpread 0.0 Random offset added per grain
duration 0.1 s Grain length
amp 1.0 Per-grain amplitude
pan 0.0 Stereo position [−1, 1]
pitchRatio 1.0 Playback rate; > 1 = faster, < 1 = slower
pitchDispersion 0.0 Random pitch added per grain
density nil (auto) Triggers/sec; nil = 1 / duration
window nil (Hanning) Optional custom window buffer
loop true Wrap when grain reads past end
interpolation .linear .none / .linear / .cubic
seed nil (time-based) PRNG seed for deterministic dispersion
mul / add 1.0 / 0.0 Post-synthesis gain/offset

Legacy alias: GrainBuf is @available(deprecated) typealias for BufferGrain.


SineGrain — Pure-Sine Grains

Every grain is an internally-generated sine at freq, windowed by Hanning (or a custom window). Use for shimmer, bell-like clouds, granular drone textures.

let bell = SineGrain(
    freq: 880.0,
    amp: 0.3,
    duration: 0.08,
    pan: 0.0,
    density: 40.0
)

Inputs: freq, amp, duration, pan, density, window, seed, mul/add. Output is always 2 channels (panned).


FMGrain — FM Synthesis Per Grain

Each grain is a self-contained two-operator FM voice with carrierFreq, modFreq, modIndex. Useful for percussive, metallic, or evolving textures where each grain has its own timbre.

let metal = FMGrain(
    carrierFreq: 440.0,
    modFreq: 660.0,
    modIndex: 3.0,
    amp: 0.4,
    duration: 0.05,
    density: 25.0
)

Inputs: carrierFreq, modFreq, modIndex, amp, duration, pan, density, window, seed, mul/add. Stereo output.


InputGrain — Live-Input Granulator

Captures incoming audio into a circular buffer (captureSize, default lyrebirdInputGrainSize) and reads grains from that history. The grain position is normalized [0, 1] over the capture buffer; 0.0 reads the most-recent sample, 1.0 reads the oldest.

let mic = In.Audio(bus: 0)
let granulated = InputGrain(
    input: mic,
    position: 0.0,
    positionSpread: 0.5,    // ±half the capture buffer
    duration: 0.15,
    pitchRatio: 1.0,
    pitchDispersion: 0.1,
    density: 30.0
)

Inputs include position, positionSpread, pitchRatio, pitchDispersion, density, plus captureSize (init-time, fixed) and interpolation. Stereo output.


PitchShift — Granular Pitch Shifter

A specialised hop-driven InputGrain whose overlap = 4 always-active grains tile to produce continuous pitch-shifted output of a live input. Time is preserved (the grain triggering rate is independent of pitchRatio). See doc:PitchShifting for the full pitch-shifter comparison and detailed reference.

let mic = In.Audio(bus: 0)
let octaveUp = PitchShift.Audio(input: mic, pitchRatio: 2.0)
output(bus: 0, source: octaveUp)

pitchRatio is clamped to [0.25, 4.0] (two octaves down to two octaves up) at the RT thread.


TimeStretch — Buffer Time Stretching

Hop-driven grain reader over a static buffer with a generator-driven read position (pos, normalized [0, 1] frames). Grains play back at pitchRatio; advancing pos in time at any rate (faster or slower than realtime) drives time stretch without affecting pitch.

let buf = try LyrebirdBuffer.load(url: someAudioFileURL)

// Half-speed playback (no pitch change) — stream pos at 0.5× normal rate
let posLfo = LinLin.Audio(
    OscSin.Control(freq: 0.5),
    inLo: -1.0, inHi: 1.0,
    outLo: 0.0, outHi: 1.0
)
let ts = TimeStretch.Audio(
    buffer: buf,
    pos: posLfo,
    pitchRatio: 1.0,
    windowSize: 0.1,
    overlap: 4
)
output(bus: 0, source: ts)

Output channel count matches buffer.channelCount. No pan parameter — channels are passed through, not collapsed.

Inputs: pos, pitchRatio, posDispersion, pitchDispersion, timeDispersion, plus init-time windowSize, overlap, loop, interpolation, seed, mul/add.


FormantGrain — FOF Formant Synthesis

Implements the IRCAM CHANT FOF (Fonction d'Onde Formantique) algorithm. Each glottal pulse spawns one grain with a sine² rise (half a period of formantFreq) followed by an exponential decay controlled by bandwidth. Stack 3–5 instances at different formant frequencies to synthesise vowel sounds.

Quick start

// One vowel formant (centred on F1 ≈ 700 Hz for /a/)
let f1 = FormantGrain.Audio(
    glottalFreq: 110.0,    // pitch
    formantFreq: 700.0,    // F1 of /a/
    bandwidth:   80.0,     // formant width
    octaviation: 0.0,
    amplitude:   0.3
)

// Stacked formants → /a/ vowel
let f1a = FormantGrain.Audio(glottalFreq: 110.0, formantFreq:  700.0, bandwidth:  80.0, amplitude: 0.30)
let f2a = FormantGrain.Audio(glottalFreq: 110.0, formantFreq: 1100.0, bandwidth:  90.0, amplitude: 0.20)
let f3a = FormantGrain.Audio(glottalFreq: 110.0, formantFreq: 2400.0, bandwidth: 120.0, amplitude: 0.10)
let f4a = FormantGrain.Audio(glottalFreq: 110.0, formantFreq: 3000.0, bandwidth: 130.0, amplitude: 0.05)
let voweA = f1a + f2a + f3a + f4a
output(bus: 0, source: voweA)

Parameters

Parameter Default Clamping Notes
glottalFreq 100.0 Hz [fofGlottalFreqMin, sampleRate] Fundamental pitch; clamp keeps hopSize ≥ 1
formantFreq 700.0 Hz ≥ fofFormantFreqMin Formant centre frequency
bandwidth 200.0 Hz ≥ fofBandwidthMin Larger = faster decay = wider formant
octaviation 0.0 — ≥ 1 alternates grain sign (suboctave)
amplitude 0.5 — Per-grain peak amplitude
mul / add 1.0 / 0.0 — Post-synthesis gain/offset

Octaviation

When octaviation ≥ 1, every other grain is sign-flipped, adding a suboctave at half the glottal rate. Useful for "creaky voice" or octave-down doubling without changing glottalFreq.

Block-rate inputs

All inputs are sampled once per audio block (block-rate). Generator-driven inputs collapse to a single value per block — useful for control-rate modulation (LFO formant sweeps, pitch glides) but does not perform per-sample modulation of the formant carrier.

Pool-overflow steal-oldest

When all 64 grain slots are active and a new glottal pulse arrives, FormantGrain steals the oldest active grain (lowest spawn tick). This keeps audio output continuous under sustained high glottalFreq × low bandwidth (long-tail) input combinations. The other granular generators silently drop overflow triggers; FormantGrain is unique in this respect because its glottal-pulse model relies on audible continuity rather than statistical density.

RT-allocation model

Pool array ([FOFGrainState], 64 entries) and _result buffer are pre-allocated in init. _computeSamples modifies pool slots in-place (struct copy). No heap allocation, no locking on the RT thread.


Topics

Buffer-Reading

  • BufferGrain
  • TimeStretch

Synthesised Per-Grain

  • SineGrain
  • FMGrain
  • FormantGrain

Live Input

  • InputGrain
  • PitchShift