# 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: Double // fractional buffer frame var phaseInc: Double // playback rate (frames/sample) // Common var remaining: Int // samples left in grain var amp: Double // amplitude at trigger time var pan: Double // [-1, 1]; 0 = centre var windowPhase: Double // window table position (index units) var windowInc: Double // window advance per sample // Synthesis (SineGrain, FMGrain) var synthPhase: Double // carrier oscillator phase (index units) var synthPhaseInc: Double // carrier phase increment var modPhase: Double // FM modulator phase (index units) var modPhaseInc: Double // FM modulator increment var modIndex: Double // 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: Double = 10.0 // grains/sec @LiveParam public var duration: Double = 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: Double = 10.0 @LiveParam public var duration: Double = 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: Double = 10.0 @LiveParam public var duration: Double = 0.1 @LiveParam public var position: Double = 0.0 // 0=recent, 1=oldest @LiveParam public var positionSpread: Double = 0.0 @LiveParam public var rate: Double = 1.0 @LiveParam public var rateSpread: Double = 0.0 @LiveParam public var amp: Double = 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` |