Remove granulator latency: window+pan the live input (no delay buffer)

The granulators read grains from behind the write head, so each grain
replayed the last grainSize of audio — an audible delay. Rework
StereoGranulator to the straight-through approach (matching Lyrebird's
InputGrain at position 0): grains apply their Hann window and random pan to
the LIVE input sample with no look-back buffer, so there is zero added
latency. Output is normalised by overlap so density doesn't change level.
Drops the circular buffer entirely.

GranulatorPedal / AutoGranulatorPedal are unchanged (same generator API).
Generator tests (seeded determinism, zero-spread centering, full-spread
L/R separation) still hold. Suite 271.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-28 15:49:50 -07:00
parent bc6e6286df
commit a21121e120
3 changed files with 26 additions and 62 deletions
@@ -10,30 +10,20 @@ import Foundation // `cos`/`sin` for the init-time Hann table and per-grain pa
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
private let stereoGranulatorZeroBlock: [Double] = makeSampleBuffer()
/// Stereo input granulator: records the mono input into a circular buffer and replays it as a
/// cloud of overlapping Hann-windowed grains, each randomly panned across the stereo field by
/// `spread`.
/// Stereo input granulator (straight-through): windows and pans the **live** input directly,
/// without a delay/look-back buffer, so there is no latency.
///
/// Each grain is a unity-speed windowed copy of the most recent `grainSize` of audio (so the cloud
/// thickens and smears the input without changing pitch). Grains are spawned every
/// `grainSize / overlap` samples from a fixed voice pool; each grain's pan is a fresh random value
/// in `[-1, 1] × spread` turned into equal-power L/R gains. `spread = 0` collapses every grain to
/// centre (mono); `spread = 1` scatters grains across the full field.
/// A pool of overlapping grain voices each apply a Hann envelope to the incoming sample and pan it
/// to a fresh random position in `[-1, 1] × spread`; the windowed, panned copies sum to the stereo
/// output. Because every active grain reads the current input sample (not buffered history), the
/// effect adds stereo width and a shimmering amplitude texture with **no time delay**. `spread = 0`
/// collapses every grain to centre (mono); `spread = 1` scatters grains across the full field.
/// Output is normalised by `overlap` so density doesn't change the level.
///
/// `grainSize`, `overlap`, and `spread` are read at control rate (once per block). Output is two
/// channels (`[0]` = left, `[1]` = right) — use the ``left`` / ``right`` accessors.
///
/// - Important: All buffers and the grain voice pool are pre-allocated at `init` for `maxGrainSize`
/// seconds — the RT path never allocates or resizes.
///
/// - Parameters:
/// - input: Audio-rate mono signal to granulate.
/// - maxGrainSize: Largest grain length in seconds; sizes the pre-allocated buffer.
/// - grainSize: Grain length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
/// - overlap: Number of overlapping grains (spawn density). Control rate; clamped to `[1, 24]`.
/// - spread: Stereo spread `[0, 1]` — scales each grain's random pan. Control rate.
/// - sampleRate: Sample rate used to size the buffer and convert seconds → frames.
/// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to time-based.
/// - Important: The grain voice pool is pre-allocated at `init` — the RT path never allocates.
public final class StereoGranulator: GeneratorBase, AudioGenerator {
// MARK: - Inputs
@@ -44,23 +34,18 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
let _overlap: any ValidGeneratorInput
let _spread: any ValidGeneratorInput
// MARK: - Buffers + state
private var _buffer: [Double]
private let _mask: Int
private var _writeHead: Int = 0
private let _maxGrainFrames: Int
private let _minGrainFrames: Int
// MARK: - State
/// Precomputed unit Hann window, indexed by `phase · hannSize / grainLen`.
private var _hann: [Double]
private let _hannSize: Int = 2048
private let _maxGrainFrames: Int
private let _minGrainFrames: Int
// Grain voice pool (fixed size; a grain that can't find a free voice is skipped).
private static let maxVoices: Int = 24
private var _vActive: [Bool]
private var _vReadHead: [Int]
private var _vPhase: [Int]
private var _vLen: [Int]
private var _vGainL: [Double]
@@ -85,11 +70,12 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
///
/// - Parameters:
/// - input: Audio-rate mono signal to granulate.
/// - maxGrainSize: Largest grain length in seconds; sizes the pre-allocated buffer.
/// - grainSize: Grain length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
/// - overlap: Number of overlapping grains (spawn density). Control rate; clamped to `[1, 24]`.
/// - maxGrainSize: Largest grain length in seconds; bounds the grain-length clamp.
/// - grainSize: Grain (window) length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
/// - overlap: Number of overlapping grains (density); also the level normaliser. Control rate;
/// clamped to `[1, 24]`.
/// - spread: Stereo spread `[0, 1]` — scales each grain's random pan. Control rate.
/// - sampleRate: Sample rate used to size the buffer and convert seconds → frames.
/// - sampleRate: Sample rate used to convert grain seconds → frames.
/// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to a constant.
public init(
input: any ValidGeneratorInput,
@@ -107,21 +93,10 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
_overlap = overlap._resolvedInput()
_spread = spread._resolvedInput()
let maxFrames: Int = max(1, Int((maxGrainSize * sampleRate).rounded()))
_maxGrainFrames = maxFrames
_maxGrainFrames = max(1, Int((maxGrainSize * sampleRate).rounded()))
_minGrainFrames = max(1, Int((minGrainSeconds * sampleRate).rounded()))
// A grain reads the `grainLen` samples behind the write head while the head writes
// `grainLen` ahead during the grain's life — disjoint spans needing ≥ 2·maxGrainFrames.
// Round up to a power of two for branchless `& _mask` wrapping.
let needed: Int = 2 * maxFrames + 2
var size: Int = 1
while size < needed { size <<= 1 }
_buffer = [Double](repeating: 0.0, count: size)
_mask = size - 1
_vActive = [Bool](repeating: false, count: StereoGranulator.maxVoices)
_vReadHead = [Int](repeating: 0, count: StereoGranulator.maxVoices)
_vPhase = [Int](repeating: 0, count: StereoGranulator.maxVoices)
_vLen = [Int](repeating: 1, count: StereoGranulator.maxVoices)
_vGainL = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
@@ -166,6 +141,8 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
let spread: Double = rawSpread.isFinite ? min(max(rawSpread, 0.0), 1.0) : 0.0
let spawnPeriod: Int = max(1, grainLen / overlap)
// Normalise so denser overlap doesn't raise the level (≈ sum of overlapping Hann windows).
let norm: Double = 1.0 / Double(overlap)
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? stereoGranulatorZeroBlock)
@@ -173,7 +150,6 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var writeHead: Int = _writeHead
var spawnCountdown: Int = _spawnCountdown
var rng: UInt64 = _rng
@@ -181,7 +157,6 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
_buffer[writeHead & _mask] = x
var left: Double = 0.0
var right: Double = 0.0
@@ -189,10 +164,10 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
let phase: Int = _vPhase[v]
let len: Int = _vLen[v]
let windowIndex: Int = phase * _hannSize / len
let windowed: Double = _buffer[_vReadHead[v] & _mask] * _hann[windowIndex]
// Straight-through: window + pan the LIVE sample (no delay buffer).
let windowed: Double = x * _hann[windowIndex]
left += windowed * _vGainL[v]
right += windowed * _vGainR[v]
_vReadHead[v] = _vReadHead[v] + 1
let nextPhase: Int = phase + 1
if nextPhase >= len {
_vActive[v] = false
@@ -204,15 +179,13 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
spawnCountdown -= 1
if spawnCountdown <= 0 {
spawnCountdown = spawnPeriod
spawnGrain(grainLen: grainLen, spread: spread, writeHead: writeHead, rng: &rng)
spawnGrain(grainLen: grainLen, spread: spread, rng: &rng)
}
writeHead = writeHead + 1
_result[0][i] = left
_result[1][i] = right
_result[0][i] = left * norm
_result[1][i] = right * norm
}
_writeHead = writeHead
_spawnCountdown = spawnCountdown
_rng = rng
return _result
@@ -222,7 +195,6 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
private func spawnGrain(
grainLen: Int,
spread: Double,
writeHead: Int,
rng: inout UInt64
) {
var voice: Int = -1
@@ -235,8 +207,6 @@ public final class StereoGranulator: GeneratorBase, AudioGenerator {
_vActive[voice] = true
_vPhase[voice] = 0
_vLen[voice] = grainLen
// Read the grainLen samples just before the write head.
_vReadHead[voice] = writeHead - grainLen
let pan: Double = xorshift64Next(&rng) * spread // shared RT-safe PRNG, [-1, 1) × spread
let angle: Double = (pan + 1.0) * panAngleScale
_vGainL[voice] = cos(angle)
@@ -52,9 +52,6 @@ struct AutoGranulatorPedalTests {
}
}
// Small min/max grains so audible output (which trails the write head by one grain) fills the
// reader's 4096-frame window.
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { pedal in pedal.minGrain = 0.01; pedal.maxGrain = 0.03 }
#expect(!samples.isEmpty)
@@ -52,9 +52,6 @@ struct GranulatorPedalTests {
}
}
// Small grains so audible output (which trails the write head by one grain) fills the reader's
// 4096-frame window rather than starting after a long grain's worth of silence.
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { pedal in pedal.grain = 0.02 }
#expect(!samples.isEmpty)