// ShimmerReverb.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation // `cos` for the init-time Hann window (not used on the RT path) import LyrebirdSynth /// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. private let shimmerReverbZeroBlock: [Double] = makeSampleBuffer() /// Regenerative shimmer reverb: a damped feedback tank with an octave-up grain reader **inside** /// the feedback path, so the pitched-up tail recirculates and the shimmer builds and sustains /// (rather than the one-shot parallel pitch-into-reverb approximation). /// /// Signal path per sample: /// ``` /// input → 2 series Schroeder allpasses (diffusion) ─┐ /// ▼ /// tank delay (size) → damping one-pole → ┬─────────→ output (wet tail) /// │ /// octave-up grains read from the tank ───┤ (× shimmer) /// ▼ /// feedback = decay·damped + shimmer·pitched → written back into the tank /// ``` /// /// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the most /// recent `grain` samples of the tank (the live wet content), a tape-style pitch raise whose /// pitched output recirculates through the feedback. A per-sample safety clamp + denormal flush /// keep the loop bounded even at high `decay` / `shimmer`. /// /// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono. /// /// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds plus the grain /// length — the RT path never allocates or resizes. /// /// - Parameters: /// - input: Audio-rate signal to reverberate. /// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer. /// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`. /// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`. /// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`. /// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate. /// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine. public final class ShimmerReverb: GeneratorBase, AudioGenerator { // MARK: - Inputs let _input: any ValidGeneratorInput let _inputIsGenerator: Bool let _size: any ValidGeneratorInput let _decay: any ValidGeneratorInput let _shimmer: any ValidGeneratorInput let _damp: any ValidGeneratorInput // MARK: - Buffers + state /// Tank delay/grain buffer (circular), length `_bufLen`. private var _tank: [Double] /// Two Schroeder input-diffusion allpass buffers. private var _allpassA: [Double] private var _allpassB: [Double] /// Precomputed Hann window over one grain, length `_grainFrames`. private var _hann: [Double] private let _bufLen: Int private let _grainFrames: Int private let _maxDelayFrames: Int private let _allpassALen: Int private let _allpassBLen: Int private var _writePos: Int = 0 private var _allpassAPos: Int = 0 private var _allpassBPos: Int = 0 private var _grainCounter: Int = 0 private var _dampState: Double = 0.0 /// DC-blocker state (previous input/output) on the feedback path. private var _dcX1: Double = 0.0 private var _dcY1: Double = 0.0 // MARK: - Constants private let minSizeSeconds: Double = 0.005 private let maxDecay: Double = 0.92 private let maxShimmer: Double = 0.85 private let grainSeconds: Double = 0.05 /// Schroeder allpass coefficient and (prime-ish) lengths in samples for input diffusion. private let allpassGain: Double = 0.7 private let allpassAFrames: Int = 142 private let allpassBFrames: Int = 107 /// Hard safety bound on the recirculated value — prevents runaway / NaN at extreme settings. private let safetyClamp: Double = 8.0 /// Below this magnitude feedback state is flushed to zero (denormal guard). private let denormalFloor: Double = 1.0e-15 /// DC-blocker pole — a one-pole high-pass on the feedback path. Without it the octave-up of DC /// (≈ DC) plus the DC-passing damping filter gives the loop a DC gain near `decay + shimmer`, /// which exceeds 1 at higher settings and accumulates into a DC offset. ~7 Hz cutoff @ 44.1 kHz /// — sub-bass only, so the shimmer wash is unaffected. private let dcBlockCoeff: Double = 0.999 // MARK: - Init /// Creates a shimmer reverb. /// /// - Parameters: /// - input: Audio-rate signal to reverberate. /// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer. /// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`. /// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`. /// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`. /// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate. /// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine. public init( input: any ValidGeneratorInput, maxDelay: Double, size: any ValidGeneratorInput, decay: any ValidGeneratorInput, shimmer: any ValidGeneratorInput, damp: any ValidGeneratorInput, sampleRate: Double ) { let resolvedInput: any ValidGeneratorInput = input._resolvedInput() _input = resolvedInput _inputIsGenerator = resolvedInput is any Generator _size = size._resolvedInput() _decay = decay._resolvedInput() _shimmer = shimmer._resolvedInput() _damp = damp._resolvedInput() let maxFrames: Int = max(1, Int((maxDelay * sampleRate).rounded())) let grain: Int = max(2, Int((grainSeconds * sampleRate).rounded())) _maxDelayFrames = maxFrames _grainFrames = grain // Buffer holds the deepest tank read plus a full grain look-back, with headroom. _bufLen = maxFrames + grain + 2 _allpassALen = allpassAFrames _allpassBLen = allpassBFrames _tank = [Double](repeating: 0.0, count: _bufLen) _allpassA = [Double](repeating: 0.0, count: allpassAFrames) _allpassB = [Double](repeating: 0.0, count: allpassBFrames) // Precompute the Hann window for the grain (off the RT thread). var hann: [Double] = [Double](repeating: 0.0, count: grain) let twoPi: Double = 2.0 * Double.pi for i: Int in 0.. [[Double]] { _checkCount(count) guard count > 0 else { return _result } let sampleRate: Double = graph.engine.sampleRate // Sanitise control reads (finite + clamped) so a NaN/inf/huge value can never reach the // feedback math or trap the seconds→frames `Int` conversion. let maxSizeSeconds: Double = Double(_maxDelayFrames) / sampleRate let sizeSeconds: Double = ShimmerReverb.clamp(_size.floatValue(graph: graph), minSizeSeconds, maxSizeSeconds) let decay: Double = ShimmerReverb.clamp(_decay.floatValue(graph: graph), 0.0, maxDecay) let shimmer: Double = ShimmerReverb.clamp(_shimmer.floatValue(graph: graph), 0.0, maxShimmer) let damp: Double = ShimmerReverb.clamp(_damp.floatValue(graph: graph), 0.0, 1.0) let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded())) // `sizeSeconds` is bounded to `maxSizeSeconds`, so `sizeSeconds · sampleRate <= _maxDelayFrames` // and the `Int` conversion cannot overflow. let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames) let halfGrain: Int = _grainFrames / 2 let inputSamples: [Double] = _inputIsGenerator ? (_input.calculatedSamples(graph: graph, count: count).first ?? shimmerReverbZeroBlock) : shimmerReverbZeroBlock let inputCount: Int = inputSamples.count let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) var writePos: Int = _writePos var grainCounter: Int = _grainCounter var dampState: Double = _dampState var allpassAPos: Int = _allpassAPos var allpassBPos: Int = _allpassBPos var dcX1: Double = _dcX1 var dcY1: Double = _dcY1 _tank.withUnsafeMutableBufferPointer { tankBuffer in _allpassA.withUnsafeMutableBufferPointer { apABuffer in _allpassB.withUnsafeMutableBufferPointer { apBBuffer in _hann.withUnsafeBufferPointer { hannBuffer in _result[0].withUnsafeMutableBufferPointer { outBuffer in guard let tank: UnsafeMutablePointer = tankBuffer.baseAddress, let apA: UnsafeMutablePointer = apABuffer.baseAddress, let apB: UnsafeMutablePointer = apBBuffer.baseAddress, let hann: UnsafePointer = hannBuffer.baseAddress, let out: UnsafeMutablePointer = outBuffer.baseAddress else { return } for i: Int in 0.. safetyClamp { writeVal = safetyClamp } else if writeVal < -safetyClamp { writeVal = -safetyClamp } // Flush denormals so they never recirculate in the tank (RT CPU guard). if abs(writeVal) < denormalFloor { writeVal = 0.0 } tank[writePos] = writeVal out[i] = damped writePos += 1 if writePos >= _bufLen { writePos = 0 } grainCounter += 1 if grainCounter >= _grainFrames { grainCounter = 0 } } if abs(dampState) < denormalFloor { dampState = 0.0 } if abs(dcY1) < denormalFloor { dcY1 = 0.0 } } } } } } _writePos = writePos _grainCounter = grainCounter _dampState = dampState _allpassAPos = allpassAPos _allpassBPos = allpassBPos _dcX1 = dcX1 _dcY1 = dcY1 return _result } /// One Schroeder allpass step over a circular buffer; advances `pos`. `y = -g·x + d; /// buf = x + g·y` where `d` is the delayed sample. private static func allpass( _ x: Double, _ buffer: UnsafeMutablePointer, _ pos: inout Int, _ length: Int, _ gain: Double ) -> Double { let delayed: Double = buffer[pos] let y: Double = -gain * x + delayed buffer[pos] = x + gain * y pos += 1 if pos >= length { pos = 0 } return y } /// Returns `v` clamped to `[lo, hi]`, or `lo` when `v` is not finite — sanitising control reads /// before they reach the feedback math or an `Int` frame conversion. private static func clamp(_ v: Double, _ lo: Double, _ hi: Double) -> Double { guard v.isFinite else { return lo } return min(max(v, lo), hi) } /// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by /// `writePos - offset` with `offset <= length`). private static func wrap(_ index: Int, _ length: Int) -> Int { let m: Int = index % length return m < 0 ? m + length : m } }