From 74227400ad7679beafe1b5191b41865ae0f68d4a Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Tue, 24 Nov 2026 11:23:30 -0800 Subject: [PATCH] feat(granular-reverb): pitch-scattered grain-cloud reverb MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add GranularReverbPedal: a diffuse, blooming wash built from an InputGrain cloud — short grains sprayed from a rolling capture at a chosen density, each smeared in time and given a random pitch offset (scatter) around a center pitch — then reverberated through a GVerb tank, folded stereo→mono. Deliberately unlike Shimmer Reverb: an incoherent random-scatter grain cloud, not a tuned coherent feedback octave tail. At pitch 0 / scatter 0 it tracks the input's pitch; raising scatter smears it into a broadband haze. The cloud is power-normalized by sqrt(grain overlap = density·grain), so turning density up thickens the texture at a roughly constant level and the peak stays bounded below clipping even at max overlap with correlated grains (no downstream limiter). Scatter is scaled by the center ratio so the per-grain spread stays proportional and a down-shifted cloud never reaches a negative (reverse) ratio. Knobs: Decay/Damp (GVerb tail), Density, Grain (duration), Pitch (semitones), Scatter (the defining control). Wire into PedalType, the registry, and the reverb category; add to the README reverb catalog. 10 tests: scatter smears pitch (normalized-autocorrelation tonalness), density normalization bounds the peak at the worst overlap corner (decay 12 s, near-full-scale input), density changes texture, tail persistence, determinism, a click-free bypass flip at the 512-sample block, knob labels, preset round-trip, registry presence. Co-Authored-By: Claude Opus 4.8 --- README.md | 2 +- Sources/LyrebirdShoeGaze/PedalType.swift | 1 + .../Pedals/GranularReverbPedal.swift | 208 ++++++++++ .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGazeUI/PedalCategory.swift | 2 +- .../GranularReverbPedalTests.swift | 382 ++++++++++++++++++ 6 files changed, 594 insertions(+), 2 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Pedals/GranularReverbPedal.swift create mode 100644 Tests/LyrebirdShoeGazeTests/GranularReverbPedalTests.swift diff --git a/README.md b/README.md index 5532797..3a2062e 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ signal (no hardware needed) or on live guitar through an audio input. | Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator | | Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay | -| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb | +| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb | | Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Looper | | Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim | | Cabinet | Cabinet (speaker-voice + microphone modeling) | diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 9ed88df..1f62b15 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -119,6 +119,7 @@ public extension PedalType { static let roomReverb = PedalType("Room Reverb") static let springReverb = PedalType("Spring Reverb") static let reverseReverb = PedalType("Reverse Reverb") + static let granularReverb = PedalType("Granular Reverb") // Pitch & octave static let octaveSplitter = PedalType("Octave Splitter") diff --git a/Sources/LyrebirdShoeGaze/Pedals/GranularReverbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/GranularReverbPedal.swift new file mode 100644 index 0000000..591716e --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/GranularReverbPedal.swift @@ -0,0 +1,208 @@ +// 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 + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index e766032..a1e417c 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -88,6 +88,7 @@ public enum PedalRegistry { "Room Reverb": { RoomReverbPedal() }, "Spring Reverb": { SpringReverbPedal() }, "Reverse Reverb": { ReverseReverbPedal() }, + "Granular Reverb": { GranularReverbPedal() }, "Limiter": { LimiterPedal() }, "Cabinet": { CabinetPedal() }, "Noise Gate": { NoiseGatePedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift index 20d48c8..47cb9cf 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift @@ -59,7 +59,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable { "Reverse Delay": .delay, "Reverb": .reverb, "Shimmer Reverb": .reverb, "Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb, - "Reverse Reverb": .reverb, + "Reverse Reverb": .reverb, "Granular Reverb": .reverb, "Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture, ] } diff --git a/Tests/LyrebirdShoeGazeTests/GranularReverbPedalTests.swift b/Tests/LyrebirdShoeGazeTests/GranularReverbPedalTests.swift new file mode 100644 index 0000000..04c058f --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/GranularReverbPedalTests.swift @@ -0,0 +1,382 @@ +// GranularReverbPedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +/// A steady sine source. +@MainActor +private final class TestSineSource: SynthesizerBase { + private let targetBus: Int + private let freq: Double + private let amp: Double + + init(targetBus: Int, freq: Double, amplitude: Double = 0.5) { + self.targetBus = targetBus + self.freq = freq + self.amp = amplitude + super.init() + } + + override func build() { + output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp)) + } +} + +/// A decaying sine burst (full at t=0, silent after `burstDur`) for tail checks. +@MainActor +private final class TestBurstSource: SynthesizerBase { + private let targetBus: Int + private let freq: Double + private let amp: Double + private let burstDur: Double + + init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) { + self.targetBus = targetBus + self.freq = freq + self.amp = amplitude + self.burstDur = burstDur + super.init() + } + + override func build() { + let envelope: Line.Control = Line.Control(start: 1.0, end: 0.0, dur: burstDur) + output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp) * envelope) + } +} + +@MainActor +@Suite("GranularReverbPedal") +struct GranularReverbPedalTests { + + private let sampleRate: Double = 44_100.0 + private let sineHz: Double = 220.0 + private let analysisSkipFrames: Int = 13_230 // ~0.3 s, clears warm-up + private let analysisWindowFrames: Int = 16_384 + + // MARK: - Render + + private func render( + duration: Double, + makeSource: @escaping (Int) -> any Synthesizer, + configure: (GranularReverbPedal) -> Void + ) throws -> [Float] { + let numAudioBuses: Int = 64 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: duration, + numAudioBuses: numAudioBuses + ) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: any Synthesizer = makeSource(srcBus.index) + let pedal: GranularReverbPedal = GranularReverbPedal( + inputBus: srcBus.index, + outputBus: dstBus.index + ) + configure(pedal) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + + return readStereoCAF(url: url) + } + + // MARK: - Analysis + + /// Normalised peak autocorrelation of the left channel over the analysis window — a "tonalness" + /// score in ~[0, 1]: near 1 for a clean periodic tone, low for a smeared/inharmonic cloud. + private func tonalness(_ samples: [Float]) -> Double { + let needed: Int = analysisSkipFrames + analysisWindowFrames + guard samples.count >= 2 * needed else { return 0.0 } + var x: [Double] = [] + x.reserveCapacity(analysisWindowFrames) + for i: Int in analysisSkipFrames ..< needed { + x.append(Double(samples[2 * i])) + } + let mean: Double = x.reduce(0.0, +) / Double(x.count) + for i: Int in x.indices { x[i] -= mean } + + var zeroLag: Double = 0.0 + for v: Double in x { zeroLag += v * v } + guard zeroLag > 0.0 else { return 0.0 } + + let minLag: Int = Int(sampleRate / 1_000.0) // up to 1 kHz + let maxLag: Int = min(Int(sampleRate / 50.0), x.count - 1) + var best: Double = 0.0 + for lag: Int in minLag ... maxLag { + var c: Double = 0.0 + for i: Int in 0 ..< (x.count - lag) { + c += x[i] * x[i + lag] + } + if c > best { best = c } + } + return best / zeroLag + } + + private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double { + let a: Int = max(0, loFrame) + let b: Int = min(hiFrame, samples.count / 2) + guard b > a else { return 0.0 } + var sum: Double = 0.0 + for i: Int in a ..< b { let v: Double = Double(samples[2 * i]); sum += v * v } + return (sum / Double(b - a)).squareRoot() + } + + /// Peak absolute left-channel sample over an interleaved-frame range `[loFrame, hiFrame)`. + private func peak(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double { + let a: Int = max(0, loFrame) + let b: Int = min(hiFrame, samples.count / 2) + guard b > a else { return 0.0 } + var m: Double = 0.0 + for i: Int in a ..< b { + let v: Double = abs(Double(samples[2 * i])) + if v > m { m = v } + } + return m + } + + private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double { + let a: Int = max(1, lo) + let b: Int = min(hi, x.count) + guard b > a else { return 0.0 } + var m: Double = 0.0 + for i: Int in a ..< b { + let d: Double = abs(Double(x[i]) - Double(x[i - 1])) + if d > m { m = d } + } + return m + } + + // MARK: - Behaviour + + @Test func buildsAndProducesNonSilentOutput() throws { + let out: [Float] = try render( + duration: 0.8, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { _ in } + ) + #expect(!out.isEmpty) + #expect(hasNonSilentOutput(out), "granular-reverb output was silent") + } + + @Test func higherScatterSmearsPitchIntoBroadbandHaze() throws { + // The defining character: at pitch 0 and scatter 0 the cloud tracks the input's pitch + // (fairly tonal); raising scatter sprays grains across random ratios, smearing the output + // into a broadband haze (low tonalness) — a grain cloud, not a coherent shimmer. + let coherent: [Float] = try render( + duration: 1.0, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { pedal in + pedal.mix = 1.0 + pedal.pitch = 0.0 + pedal.scatter = 0.0 + pedal.density = 60.0 + pedal.decay = 0.8 // short tail so cloud tonalness dominates the window + } + ) + let smeared: [Float] = try render( + duration: 1.0, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { pedal in + pedal.mix = 1.0 + pedal.pitch = 0.0 + pedal.scatter = 0.5 + pedal.density = 60.0 + pedal.decay = 0.8 + } + ) + let coherentTonalness: Double = tonalness(coherent) + let smearedTonalness: Double = tonalness(smeared) + #expect(hasNonSilentOutput(smeared), "smeared render was silent") + #expect(coherentTonalness > smearedTonalness * 1.3, + "scatter should smear pitch (coherent \(coherentTonalness) vs smeared \(smearedTonalness))") + } + + @Test func densityNormalizationBoundsThePeak() throws { + // Worst case for clipping: max density × max grain (heaviest overlap), scatter 0 (grains + // correlated), fully wet, driven by a near-full-scale sine. The sqrt power normalisation must + // keep the output peak bounded — nothing downstream limits it. + let out: [Float] = try render( + duration: 1.0, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz, amplitude: 0.9) }, + configure: { pedal in + pedal.mix = 1.0 + pedal.density = 80.0 + pedal.grain = 0.3 + pedal.scatter = 0.0 + pedal.decay = 12.0 // longest tail → most reverb buildup, worst case for peak + } + ) + let peakOut: Double = peak(out, loFrame: Int(0.3 * sampleRate), hiFrame: Int(0.95 * sampleRate)) + #expect(hasNonSilentOutput(out), "max-overlap render was silent") + #expect(peakOut < 1.0, "density normalisation should keep the peak below clipping, got \(peakOut)") + } + + @Test func densityChangesTheTexture() throws { + // Normalisation keeps the LEVEL roughly constant, but density still changes the grain + // texture — a sparse and a dense cloud must not render identically, and both must sound. + let sparse: [Float] = try render( + duration: 1.0, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { pedal in + pedal.mix = 1.0; pedal.density = 8.0; pedal.scatter = 0.1; pedal.decay = 1.0 + } + ) + let dense: [Float] = try render( + duration: 1.0, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { pedal in + pedal.mix = 1.0; pedal.density = 70.0; pedal.scatter = 0.1; pedal.decay = 1.0 + } + ) + #expect(hasNonSilentOutput(sparse) && hasNonSilentOutput(dense), "a density render was silent") + #expect(sparse != dense, "sparse and dense clouds should render differently") + } + + @Test func reverbTailPersistsAfterInput() throws { + let out: [Float] = try render( + duration: 1.4, + makeSource: { bus in + TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.15) + }, + configure: { pedal in + pedal.mix = 1.0 + pedal.decay = 6.0 + pedal.density = 40.0 + } + ) + let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate)) + #expect(lateRMS > 1.0e-4, "granular-reverb tail should still ring late, got \(lateRMS)") + } + + @Test func renderIsDeterministic() throws { + // The grain cloud is seeded and GVerb is RNG-free, so two identical renders are bit-identical. + let make: () throws -> [Float] = { + try self.render( + duration: 0.8, + makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, + configure: { pedal in + pedal.scatter = 0.3 + pedal.density = 30.0 + } + ) + } + let a: [Float] = try make() + let b: [Float] = try make() + #expect(a == b, "seeded granular-reverb renders of the same setting should be bit-identical") + } + + // MARK: - Bypass + + private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] { + let numAudioBuses: Int = 64 + let numControlBuses: Int = 512 + let driver: OfflineDriver = OfflineDriver() + let engine: SynthesisEngine = SynthesisEngine( + blockSize: blockSize, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: numAudioBuses, + numControlBuses: numControlBuses, + driver: driver + ) + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz) + let pedal: GranularReverbPedal = GranularReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + + let noInput: [[Float]] = [] + var left: [Float] = [] + left.reserveCapacity(totalFrames) + var frame: Int = 0 + var flipped: Bool = false + while frame < totalFrames { + if !flipped, frame >= flipFrame { + pedal.bypass = 1.0 + flipped = true + } + engine.processBlock(inputSamples: noInput) + left.append(contentsOf: engine.audioBuses[0]) + frame += blockSize + } + engine.stop() + return left + } + + @Test func bypassSwitchIsClickFree() throws { + let blockSize: Int = 512 + let totalFrames: Int = 26_460 + let flipFrame: Int = 15_435 + let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize) + #expect(hasNonSilentOutput(left), "bypass-flip render was silent") + + let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500) + let fadeFrames: Int = Int(0.03 * sampleRate) + let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000) + #expect(transStep <= steadyStep * 4.0, + "bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through") + } + + // MARK: - Wiring + + @Test func exposesSixKnobs() throws { + let pedal: GranularReverbPedal = GranularReverbPedal() + #expect(pedal.effectKnobs.map { $0.label } + == ["Decay", "Density", "Grain", "Pitch", "Scatter", "Damp"]) + } + + @Test func presetRoundTripPreservesKnobs() throws { + let pedal: GranularReverbPedal = GranularReverbPedal() + pedal.decay = 5.0 + pedal.density = 40.0 + pedal.grain = 0.2 + pedal.pitch = 12.0 + pedal.scatter = 0.3 + pedal.damp = 0.4 + + let state: PedalState = pedal.captureState() + let restored: GranularReverbPedal = GranularReverbPedal() + restored.applyState(state) + + #expect(restored.decay == 5.0) + #expect(restored.density == 40.0) + #expect(restored.grain == 0.2) + #expect(restored.pitch == 12.0) + #expect(restored.scatter == 0.3) + #expect(restored.damp == 0.4) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Granular Reverb") + #expect(pedal is GranularReverbPedal) + } +}