// LimiterPedalTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation import LyrebirdSynth import LyrebirdUI @testable import LyrebirdShoeGaze @MainActor @Suite("LimiterPedal") struct LimiterPedalTests { /// Renders a `LimiterPedal` through an offline engine and returns the interleaved output. private func render( boost: Double, ceiling: Double, sampleRate: Double = 44100.0 ) throws -> [Float] { let renderDuration: Double = 0.1 let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( duration: renderDuration, sampleRate: sampleRate ) 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: TestLoopSource = TestLoopSource(targetBus: srcBus.index) let pedal: LimiterPedal = LimiterPedal( inputBus: srcBus.index, outputBus: dstBus.index ) // Match the engine rate so the look-ahead limiter sizes its ring correctly. pedal.sampleRate = sampleRate pedal.boost = boost pedal.ceiling = ceiling 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, sampleRate: sampleRate) } @Test func buildsAndProducesNonSilentOutput() throws { let samples: [Float] = try render(boost: 2.0, ceiling: 0.95) #expect(!samples.isEmpty) #expect(hasNonSilentOutput(samples), "LimiterPedal produced silence") } @Test func outputNeverExceedsCeiling() throws { // Drive hard into the limiter with a low ceiling; the peak must stay at the ceiling. // Downstream Pan2/gain in the master only attenuates, so the recorded peak is a // conservative upper bound on the limiter output peak. let ceiling: Double = 0.5 let samples: [Float] = try render(boost: 12.0, ceiling: ceiling) #expect(hasNonSilentOutput(samples), "Driven limiter produced silence") // Skip the look-ahead fill window before measuring the peak. The limiter's 5 ms // look-ahead at 44.1 kHz is ~220 frames; 2048 interleaved samples is a comfortable // margin past the window-fill transient. let lookAheadFillSamples: Int = 2048 guard samples.count > lookAheadFillSamples else { return } let window: ArraySlice = samples[lookAheadFillSamples...] let peak: Float = window.reduce(0) { Swift.max($0, abs($1)) } let tolerance: Float = 0.05 #expect(peak <= Float(ceiling) + tolerance, "Limiter overshot ceiling: peak=\(peak)") } }