// 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 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: 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`. /// /// 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. /// /// `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. 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: - Buffers + state private var _buffer: [Double] private let _mask: Int private var _writeHead: Int = 0 private let _maxGrainFrames: Int private let _minGrainFrames: Int /// Precomputed unit Hann window, indexed by `phase · hannSize / grainLen`. private var _hann: [Double] private let _hannSize: Int = 2048 // 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] 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 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() let maxFrames: Int = max(1, Int((maxGrainSize * sampleRate).rounded())) _maxGrainFrames = maxFrames _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) _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) 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 writeHead: Int = _writeHead 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, writeHead: writeHead, rng: &rng) } writeHead = writeHead + 1 _result[0][i] = left _result[1][i] = right } _writeHead = writeHead _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, writeHead: Int, rng: inout UInt64 ) { var voice: Int = -1 for v: Int in 0..= 0 else { return } _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 = StereoGranulator.nextBipolar(&rng) * spread let angle: Double = (pan + 1.0) * panAngleScale _vGainL[voice] = cos(angle) _vGainR[voice] = sin(angle) } /// xorshift64 step → uniform Double in `[-1, 1)`. RT-safe (no allocation, no locks). @inline(__always) private static func nextBipolar(_ state: inout UInt64) -> Double { state ^= state << 13 state ^= state >> 7 state ^= state << 17 return Double(state) / Double(UInt64.max) * 2.0 - 1.0 } } // MARK: - Channel accessors public extension StereoGranulator { /// Left output channel. var left: ChannelSelect.Audio { self[0] } /// Right output channel. var right: ChannelSelect.Audio { self[1] } }