// GranularReverbPedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import LyrebirdUI /// Granular-cloud reverb — a diffuse, blooming wash built from a cloud of pitch-scattered grains, /// then reverberated. /// /// The dry signal feeds an `InputGrain` cloud: short grains are sprayed from a rolling capture of /// the input at a chosen `density`, each smeared slightly in time and given a random pitch offset /// (`scatter`) around a center `pitch`. That cloud then drives a `GVerb` room tank, folded /// stereo→mono, so the grains bloom into a reverberant pad. /// /// This is deliberately **unlike** the ``ShimmerReverbPedal``: Shimmer is a tuned feedback tank /// regenerating a clean, coherent octave-up tail; this is an incoherent grain cloud whose defining /// control is the **random** per-grain pitch `scatter`. At `pitch = 0, scatter = 0` the cloud /// tracks the input's pitch; raising `scatter` smears it into a broadband haze — a grain cloud, not /// an ascending shimmer. Set `pitch` for a tuned (e.g. octave-up) cloud, or leave it at `0` for an /// untuned ambient bloom. /// /// The base `Pedal` `mix` sets the wet/dry blend. /// /// ## Knobs /// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`. /// - `density`: Grain cloud density in grains per second. Range `[5, 80]`. /// - `grain`: Grain duration in seconds. Range `[0.02, 0.3]`. /// - `pitch`: Cloud center pitch in semitones. Range `[-24, 24]`; `0` = unpitched (tracks input). /// - `scatter`: Random per-grain pitch spread (± ratio around center). Range `[0, 0.5]`. /// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark). public final class GranularReverbPedal: Pedal { /// One-line description shown in the picker and info panel. public override var summary: String { "A cloud of pitch-scattered grains blooming into reverb — a diffuse, incoherent wash." } // MARK: - Parameters /// GVerb reverb time (T60) in seconds. Range [0.2, 12.0]. @UIParam public var decay: Double = 4.0 /// Grain cloud density in grains per second. Range [5, 80]. @UIParam public var density: Double = 25.0 /// Grain duration in seconds. Range [0.02, 0.3]. @UIParam public var grain: Double = 0.12 /// Cloud center pitch in semitones. Range [-24, 24]; 0 = unpitched (tracks input). @UIParam public var pitch: Double = 0.0 /// Random per-grain pitch spread, as a fraction of the center ratio (`0.5` = ±50% of the shifted /// speed), added bipolar per grain. Range [0, 0.5]. Scaling by the center keeps the spread /// proportional, so a down-shifted cloud doesn't send grains to a negative (reverse) ratio. The /// defining control — higher = more smeared and incoherent. @UIParam public var scatter: Double = 0.15 /// High-frequency damping in [0, 1]. Higher = darker tail. @UIParam public var damp: Double = 0.5 // MARK: - Constants /// Default wet/dry blend — the cloud wash sits under the dry note. private static let defaultMix: Double = 0.4 /// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio` to turn /// the `pitch` knob into a `pitchRatio` for the grain cloud. private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12 /// Grain read position in the rolling capture, `[0, 1]` (0 = newest). Slightly into the past so /// each grain has recorded material to read even at the lowest density. private let cloudPosition: Double = 0.1 /// Random spread applied to the read position per grain — a small time smear that keeps the /// cloud diffuse rather than a tight repeat. private let cloudPositionSpread: Double = 0.1 /// Reference output gain on the grain cloud before the tank, applied after density /// normalisation (see ``effect(_:)``). `InputGrain` sums every active grain, so the raw cloud /// level scales with the grain overlap (`density · grain`); without normalisation the extremes /// of those knobs (and correlated grains at low scatter) could sum to several times the input /// and clip. The cloud is divided by `sqrt(overlap)` (power normalisation), so turning density /// up thickens the texture at a roughly constant level instead of raising the peak toward /// clipping. private let cloudGain: Double = 0.5 /// Lower bound on the overlap estimate (`density · grain`) before the `sqrt` normalisation, so a /// sparse cloud (overlap < 1) is not boosted by dividing by a fraction. private let minOverlap: Double = 1.0 /// Fixed PRNG seed for the grain scheduling and pitch scatter, so a given setting renders /// identically every time (reproducible audio and tests). private let cloudSeed: UInt64 = 0x3C6E_F372_FE94_F82B /// GVerb room size in metres (fixed; the grain/reverb controls shape the character instead). private let roomSizeMeters: Double = 40.0 /// GVerb early-reflection level. Low, so the wash favours the diffuse grain tail over discrete /// reflections. private let reverbEarlyLevel: Double = 0.2 /// GVerb late-reverb (tail) level. private let reverbTailLevel: Double = 0.6 /// GVerb dry level — how much of the grain cloud passes through the tank's dry path, keeping the /// grain texture itself present under its reverb. private let reverbDryLevel: Double = 0.3 /// Gain folding a decorrelated stereo pair to mono. A conservative trim leaving output headroom. private let stereoSumGain: Double = 0.5 // MARK: - Ranges private let decayRange: ClosedRange = 0.2 ... 12.0 private let densityRange: ClosedRange = 5.0 ... 80.0 private let grainRange: ClosedRange = 0.02 ... 0.3 private let pitchRange: ClosedRange = -24.0 ... 24.0 private let scatterRange: ClosedRange = 0.0 ... 0.5 private let normalizedRange: ClosedRange = 0.0 ... 1.0 // MARK: - Knobs public override var effectKnobs: [PedalKnob] { [ PedalKnob(label: "Decay", node: $decay, range: decayRange), PedalKnob(label: "Density", node: $density, range: densityRange), PedalKnob(label: "Grain", node: $grain, range: grainRange), PedalKnob(label: "Pitch", node: $pitch, range: pitchRange), PedalKnob(label: "Scatter", node: $scatter, range: scatterRange), PedalKnob(label: "Damp", node: $damp, range: normalizedRange), ] } // MARK: - Init /// Creates a granular-reverb pedal. /// /// - Parameters: /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. public init( inputBus: Int = 0, outputBus: Int = 0 ) { super.init( name: "Granular Reverb", inputBus: inputBus, outputBus: outputBus, initialMix: GranularReverbPedal.defaultMix ) } // MARK: - Effect public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { // Center pitch (semitones → ratio); per-grain scatter is added bipolar around it inside // InputGrain. let centerRatio: Exp.Audio = Exp.Audio($pitch * semitoneToRatioScale) // Density normalisation: divide the cloud by sqrt(grain overlap = density·grain), clamped so // a sparse cloud isn't boosted. Keeps the level roughly constant across the density/grain // knobs and bounds the peak away from clipping even with correlated grains at low scatter. let overlap: any ValidGeneratorInput = Max.Audio($density * $grain, minOverlap) let cloudNormGain: any ValidGeneratorInput = Reciprocal.Audio(Sqrt.Audio(overlap)) * cloudGain // Scatter scaled by the center ratio, so the per-grain spread is proportional (±scatter of // the shifted speed). This keeps a down-shifted cloud off a negative/reverse ratio, which an // absolute offset would reach at low pitch + high scatter. let scaledScatter: any ValidGeneratorInput = centerRatio * $scatter // The grain cloud (native stereo via per-grain pan). let cloud: InputGrain = InputGrain( input: dry, position: cloudPosition, positionSpread: cloudPositionSpread, duration: $grain, pitchRatio: centerRatio, pitchDispersion: scaledScatter, density: $density, seed: cloudSeed, mul: cloudNormGain ) // Fold the cloud to mono for the tank source. let cloudMono: SumChannels.Audio = SumChannels.Audio( input: cloud, mul: stereoSumGain ) // Reverberate the cloud (native stereo); `dryLevel` keeps the grain texture present. let stereoVerb: GVerb.Audio = GVerb.Audio( source: cloudMono, roomSize: roomSizeMeters, reverbTime: $decay, damping: $damp, earlyLevel: reverbEarlyLevel, tailLevel: reverbTailLevel, dryLevel: reverbDryLevel, sampleRate: sampleRate ) // Fold the reverb output stereo → mono. return SumChannels.Audio( input: stereoVerb, mul: stereoSumGain ) } }