diff --git a/README.md b/README.md index 184e22a..5532797 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 | +| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse 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 548de6f..9ed88df 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -118,6 +118,7 @@ public extension PedalType { static let plateReverb = PedalType("Plate Reverb") static let roomReverb = PedalType("Room Reverb") static let springReverb = PedalType("Spring Reverb") + static let reverseReverb = PedalType("Reverse Reverb") // Pitch & octave static let octaveSplitter = PedalType("Octave Splitter") diff --git a/Sources/LyrebirdShoeGaze/Pedals/ReverseReverbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ReverseReverbPedal.swift new file mode 100644 index 0000000..ecbc723 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/ReverseReverbPedal.swift @@ -0,0 +1,156 @@ +// ReverseReverbPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Reverse reverb — a backwards-swelling ambience, the "sucked-in" pre-verb of ambient and +/// shoegaze records. +/// +/// The dry signal is first run through a segmented ``ReverseDelay``: it is captured in fixed-length +/// segments and each is played back reversed, so a note's natural decay becomes a swell that rises +/// *into* the note. That reversed signal then feeds a `GVerb` room tank, so the backwards swell +/// arrives wrapped in a diffuse reverberant wash rather than as a dry backwards note. The result is +/// distinct from the plain ``ReverseDelayPedal`` (no reverb) and from a forward ``RoomReverbPedal`` +/// (energy that follows the note instead of swelling up to it). +/// +/// `Time` sets the reverse segment length (and so the pre-delay before each swell); `Decay`, `Size`, +/// and `Damp` shape the GVerb tail. The tank runs natively in stereo and is folded to mono. The +/// base `Pedal` `mix` sets the wet/dry blend, so your live note stays up front while the reversed +/// wash sits under it. Latency is one segment — a note's reversed swell appears up to `Time` seconds +/// after you play it. +/// +/// ## Knobs +/// - `time`: Reverse segment length in seconds. Range `[0.1, 2.0]`. Also the swell pre-delay. +/// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`. +/// - `size`: GVerb room size in metres. Range `[1, 100]`. +/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark). +public final class ReverseReverbPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Backwards-swelling reverb — notes bloom in reverse, wrapped in a diffuse wash." + } + + // MARK: - Parameters + + /// Reverse segment length in seconds (also the swell pre-delay). Range [0.1, 2.0]. + @UIParam public var time: Double = 0.5 + + /// GVerb reverb time (T60) in seconds. Range [0.2, 12.0]. + @UIParam public var decay: Double = 3.0 + + /// GVerb room size in metres. Range [1, 100]. + @UIParam public var size: Double = 30.0 + + /// High-frequency damping in [0, 1]. Higher = darker tail. + @UIParam public var damp: Double = 0.5 + + // MARK: - Constants + + /// Default wet/dry blend — the reversed wash sits under the dry note. + private static let defaultMix: Double = 0.4 + + /// Maximum reverse segment length the `ReverseDelay` buffers are allocated for, in seconds. + /// Matches the top of the `time` range so a full-length segment never clamps. + private let maxReverseTime: Double = 2.0 + + /// Reverse-trail feedback. Kept at `0` so each swell is a single clean pass (the GVerb tail, + /// not recirculated reverse segments, provides the sustain). + private let reverseFeedback: Double = 0.0 + + /// GVerb dry level — how much of the GVerb *source* passes through the tank's dry path. The + /// source here is the already-reversed signal (not the raw input), so this keeps the backwards + /// swell itself audible under its reverb rather than being fully smeared. The pedal's own `mix` + /// then blends this whole wet result against the true dry note. Kept at `0.5` (with the tail and + /// early levels below) so the summed wet path keeps headroom below clipping on a loud input. + private let reverseSwellLevel: Double = 0.5 + + /// GVerb late-reverb (tail) level. + private let reverbTailLevel: Double = 0.5 + + /// GVerb early-reflection level. Lowered from the generator's `0.4` default: early reflections + /// fire forward (not reversed), so a high level would fight the backwards-swell character; a + /// smaller amount keeps some room sense while favouring the reversed tail, and trims the sum. + private let reverbEarlyLevel: Double = 0.3 + + /// Gain folding GVerb's two decorrelated reverb channels to mono. A conservative trim (not a + /// strict doubling correction — the channels are not identical), leaving output headroom. + private let stereoSumGain: Double = 0.5 + + // MARK: - Ranges + + private let timeRange: ClosedRange = 0.1 ... 2.0 + private let decayRange: ClosedRange = 0.2 ... 12.0 + private let sizeRange: ClosedRange = 1.0 ... 100.0 + private let normalizedRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Knobs + + public override var tempoSyncableParams: [TempoSyncableParam] { + [ + TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange), + ] + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Time", node: $time, range: timeRange), + PedalKnob(label: "Decay", node: $decay, range: decayRange), + PedalKnob(label: "Size", node: $size, range: sizeRange), + PedalKnob(label: "Damp", node: $damp, range: normalizedRange), + ] + } + + // MARK: - Init + + /// Creates a reverse-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: "Reverse Reverb", + inputBus: inputBus, + outputBus: outputBus, + initialMix: ReverseReverbPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Reverse the dry in fixed segments: a note's decay becomes a swell rising into it. + let reversed: ReverseDelay = ReverseDelay( + input: dry, + maxDelay: maxReverseTime, + delay: $time, + feedback: reverseFeedback, + sampleRate: sampleRate + ) + // Wrap the reversed swell in a GVerb room tank (native stereo). `dryLevel` keeps the swell + // itself present under the reverb. + let stereoVerb: GVerb.Audio = GVerb.Audio( + source: reversed, + roomSize: $size, + reverbTime: $decay, + damping: $damp, + earlyLevel: reverbEarlyLevel, + tailLevel: reverbTailLevel, + dryLevel: reverseSwellLevel, + sampleRate: sampleRate + ) + // Sum stereo → mono with ×0.5 to avoid level doubling. + return SumChannels.Audio( + input: stereoVerb, + mul: stereoSumGain + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 0194fa1..e766032 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -87,6 +87,7 @@ public enum PedalRegistry { "Plate Reverb": { PlateReverbPedal() }, "Room Reverb": { RoomReverbPedal() }, "Spring Reverb": { SpringReverbPedal() }, + "Reverse Reverb": { ReverseReverbPedal() }, "Limiter": { LimiterPedal() }, "Cabinet": { CabinetPedal() }, "Noise Gate": { NoiseGatePedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift index b9433c1..20d48c8 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift @@ -59,6 +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, "Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture, ] } diff --git a/Tests/LyrebirdShoeGazeTests/ReverseReverbPedalTests.swift b/Tests/LyrebirdShoeGazeTests/ReverseReverbPedalTests.swift new file mode 100644 index 0000000..5f5ac98 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ReverseReverbPedalTests.swift @@ -0,0 +1,338 @@ +// ReverseReverbPedalTests.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 (for non-silent / bypass checks). +@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 the start, linearly fading to silence over `burstDur`, then +/// silent. Its amplitude envelope peaks at `t = 0`, so after the reverse delay the swell appears +/// *later* — the signature a forward effect would not show. +@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("ReverseReverbPedal") +struct ReverseReverbPedalTests { + + private let sampleRate: Double = 44_100.0 + private let sineHz: Double = 220.0 + + // MARK: - Render helpers + + /// Renders a source through the pedal to a stereo CAF, returning interleaved samples. + private func render( + duration: Double, + makeSource: @escaping (Int) -> any Synthesizer, + configure: (ReverseReverbPedal) -> 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: ReverseReverbPedal = ReverseReverbPedal( + 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 + + /// RMS of the left channel over an interleaved-frame range `[loFrame, hiFrame)`. + 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() + } + + /// Max absolute first difference (per-sample step) over `[lo, hi)`. + 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), "reverse-reverb output was silent") + } + + @Test func reverseSwellDelaysEnergyPastOneSegment() throws { + // A burst peaking at t=0, rendered fully wet. The reverse delay plays nothing until its first + // segment completes (~`time` seconds), then releases the burst reversed — so the wet energy + // lands AFTER one segment, not at the input's early peak. A forward reverb would put its + // loudest energy during the burst instead. Assert the mid window dominates the early window. + let segmentTime: Double = 0.4 + let out: [Float] = try render( + duration: 1.2, + makeSource: { bus in + TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12) + }, + configure: { pedal in + pedal.mix = 1.0 // isolate the wet path (no dry passthrough) + pedal.time = segmentTime + pedal.decay = 2.0 + } + ) + #expect(hasNonSilentOutput(out), "reverse-reverb burst render was silent") + + // Early: during/just after the input burst, before the first reversed segment plays. + let earlyRMS: Double = rms(out, loFrame: 0, hiFrame: Int(0.3 * sampleRate)) + // Mid: the reversed swell has been released and reverberates. + let midRMS: Double = rms(out, loFrame: Int(0.42 * sampleRate), hiFrame: Int(0.8 * sampleRate)) + + // The reversed signal is genuinely silent before one segment, so earlyRMS ≈ 0; assert the mid + // window is both non-trivially loud and far above the early window (a forward reverb would put + // its energy in the early window and fail this). + #expect(midRMS > 1.0e-3, "reversed swell should be clearly audible in the mid window, got \(midRMS)") + #expect(midRMS > earlyRMS * 3.0, + "reversed energy should arrive after one segment (mid RMS \(midRMS) vs early \(earlyRMS))") + } + + @Test func energyRisesAcrossTheReversedSegment() throws { + // The reverse signature: a burst decaying from t=0 is recorded over segment [0, time) and + // played back end-to-start over [time, 2·time). The recorded END (late, silent) plays first + // and the recorded START (t=0, loudest) plays last, so within the reversed playback the + // energy RISES toward the segment's end. A plain delay→reverb would not — it would preserve + // the burst's decaying shape. Assert the late-segment window is louder than the mid-segment + // window. mix=1.0 isolates the wet path. + let segmentTime: Double = 0.4 + let out: [Float] = try render( + duration: 1.2, + makeSource: { bus in + TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12) + }, + configure: { pedal in + pedal.mix = 1.0 + pedal.time = segmentTime + pedal.decay = 1.5 // modest tail so the rising dry swell dominates the window + } + ) + // Reversed playback spans [0.4, 0.8) s. Early-in-playback (reads the silent recorded tail) + // vs late-in-playback (reads the loud recorded onset). + let midSegRMS: Double = rms(out, loFrame: Int(0.48 * sampleRate), hiFrame: Int(0.60 * sampleRate)) + let lateSegRMS: Double = rms(out, loFrame: Int(0.68 * sampleRate), hiFrame: Int(0.80 * sampleRate)) + #expect(lateSegRMS > midSegRMS * 1.5, + "energy should rise into the segment end (late \(lateSegRMS) vs mid \(midSegRMS))") + } + + @Test func reverbTailPersistsAfterInput() throws { + // After the burst and its reversed playback, the GVerb tail should still ring. + let out: [Float] = try render( + duration: 1.4, + makeSource: { bus in + TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12) + }, + configure: { pedal in + pedal.mix = 1.0 + pedal.time = 0.4 + pedal.decay = 6.0 // long tail so late energy is unambiguous + } + ) + let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate)) + #expect(lateRMS > 1.0e-4, "reverb tail should still ring late in the render, got \(lateRMS)") + } + + @Test func renderIsDeterministic() throws { + // ReverseDelay and GVerb are RNG-free, so two identical renders must be bit-identical. + let make: () throws -> [Float] = { + try self.render( + duration: 0.8, + makeSource: { bus in + TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12) + }, + configure: { pedal in + pedal.time = 0.3 + pedal.decay = 2.0 + } + ) + } + let a: [Float] = try make() + let b: [Float] = try make() + #expect(a == b, "reverse-reverb renders of the same setting should be bit-identical") + } + + // MARK: - Bypass transition + + 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: ReverseReverbPedal = ReverseReverbPedal(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 { + // The audio-rate equal-power bypass crossfade must stay click-free at the engine's real + // 512-sample block. + let blockSize: Int = 512 + let totalFrames: Int = 26_460 // 0.6 s + let flipFrame: Int = 15_435 // ~0.35 s + 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 exposesFourKnobs() throws { + let pedal: ReverseReverbPedal = ReverseReverbPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Time", "Decay", "Size", "Damp"]) + } + + @Test func presetRoundTripPreservesKnobs() throws { + let pedal: ReverseReverbPedal = ReverseReverbPedal() + pedal.time = 0.8 + pedal.decay = 5.0 + pedal.size = 50.0 + pedal.damp = 0.3 + + let state: PedalState = pedal.captureState() + let restored: ReverseReverbPedal = ReverseReverbPedal() + restored.applyState(state) + + #expect(restored.time == 0.8) + #expect(restored.decay == 5.0) + #expect(restored.size == 50.0) + #expect(restored.damp == 0.3) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Reverb") + #expect(pedal is ReverseReverbPedal) + } +}