// StereoGranulator.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation // `cos`/`sin` for the init-time Hann table and per-grain pan gains @_spi(LyrebirdExtensions) import LyrebirdSynth /// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. private let stereoGranulatorZeroBlock: [Double] = makeSampleBuffer() /// Stereo input granulator (straight-through): windows and pans the **live** input directly, /// without a delay/look-back buffer, so there is no latency. /// /// 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: The grain voice pool is pre-allocated at `init` — the RT path never allocates. public final class StereoGranulator: GeneratorBase, AudioGenerator { // MARK: - Inputs let _input: any ValidGeneratorInput let _inputIsGenerator: Bool let _grainSize: any ValidGeneratorInput let _overlap: any ValidGeneratorInput let _spread: any ValidGeneratorInput // 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 _vPhase: [Int] private var _vLen: [Int] private var _vGainL: [Double] private var _vGainR: [Double] private var _spawnCountdown: Int = 0 private var _rng: UInt64 // MARK: - Constants private let minGrainSeconds: Double = 0.003 /// Equal-power pan: `angle = (pan + 1) · π/4`, `gainL = cos`, `gainR = sin`. private let panAngleScale: Double = Double.pi / 4.0 /// Non-zero fallback PRNG seed (golden-ratio constant). private static let defaultSeed: UInt64 = 0x9E37_79B9_7F4A_7C15 public override var outputChannelCount: Int { 2 } // MARK: - Init /// Creates a stereo granulator. /// /// - Parameters: /// - input: Audio-rate mono signal to granulate. /// - 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 convert grain seconds → frames. /// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to a constant. public init( input: any ValidGeneratorInput, maxGrainSize: Double, grainSize: any ValidGeneratorInput, overlap: any ValidGeneratorInput, spread: any ValidGeneratorInput, sampleRate: Double, seed: UInt64? = nil ) { let resolvedInput: any ValidGeneratorInput = input._resolvedInput() _input = resolvedInput _inputIsGenerator = resolvedInput is any Generator _grainSize = grainSize._resolvedInput() _overlap = overlap._resolvedInput() _spread = spread._resolvedInput() _maxGrainFrames = max(1, Int((maxGrainSize * sampleRate).rounded())) _minGrainFrames = max(1, Int((minGrainSeconds * sampleRate).rounded())) _vActive = [Bool](repeating: false, 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) _vGainR = [Double](repeating: 0.0, count: StereoGranulator.maxVoices) var hann: [Double] = [Double](repeating: 0.0, count: _hannSize) let twoPi: Double = 2.0 * Double.pi for i: Int in 0..<_hannSize { hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(_hannSize)) } _hann = hann let requestedSeed: UInt64 = seed ?? StereoGranulator.defaultSeed _rng = requestedSeed == 0 ? StereoGranulator.defaultSeed : requestedSeed super.init(channels: 2) } // MARK: - Render public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) guard count > 0 else { return _result } let sampleRate: Double = graph.engine.sampleRate let rawGrain: Double = _grainSize.floatValue(graph: graph) let grainSeconds: Double = rawGrain.isFinite ? min(max(rawGrain, minGrainSeconds), Double(_maxGrainFrames) / sampleRate) : minGrainSeconds let grainLen: Int = min(max(Int((grainSeconds * sampleRate).rounded()), _minGrainFrames), _maxGrainFrames) let rawOverlap: Double = _overlap.floatValue(graph: graph) let overlap: Int = rawOverlap.isFinite ? min(max(Int(rawOverlap.rounded()), 1), StereoGranulator.maxVoices) : 1 let rawSpread: Double = _spread.floatValue(graph: graph) 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) : stereoGranulatorZeroBlock let inputCount: Int = inputSamples.count let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) var spawnCountdown: Int = _spawnCountdown var rng: UInt64 = _rng for i: Int in 0..= len { _vActive[v] = false } else { _vPhase[v] = nextPhase } } spawnCountdown -= 1 if spawnCountdown <= 0 { spawnCountdown = spawnPeriod spawnGrain(grainLen: grainLen, spread: spread, rng: &rng) } _result[0][i] = left * norm _result[1][i] = right * norm } _spawnCountdown = spawnCountdown _rng = rng return _result } /// Activates the first free grain voice (no-op if all are busy — overlap saturates gracefully). private func spawnGrain( grainLen: Int, spread: Double, rng: inout UInt64 ) { var voice: Int = -1 for v: Int in 0..= 0 else { return } _vActive[voice] = true _vPhase[voice] = 0 _vLen[voice] = 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) _vGainR[voice] = sin(angle) } } // MARK: - Channel accessors public extension StereoGranulator { /// Left output channel. var left: ChannelSelect.Audio { self[0] } /// Right output channel. var right: ChannelSelect.Audio { self[1] } }