// 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) } }