// AmpVoicePedalTests.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("AmpVoicePedal") struct AmpVoicePedalTests { private let sampleRate: Double = 48000.0 private func render(_ make: () -> P, configure: (P) -> Void = { _ in }) throws -> [Float] { let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( duration: 0.2, sampleRate: sampleRate, numAudioBuses: 64) 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: P = make() pedal.inputBus = srcBus.index pedal.outputBus = dstBus.index pedal.sampleRate = sampleRate 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, sampleRate: sampleRate) } private func windowedSSD(_ a: [Float], _ b: [Float], skip: Int = 4096, window: Int = 4096) -> Double { guard a.count >= skip + window, b.count >= skip + window else { return 0.0 } return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in let d: Double = Double(pair.0 - pair.1); return acc + d * d } } /// Sum-of-squared-differences after RMS-normalizing each window, so a pure level difference /// collapses to ~0 and only a genuine waveshape (saturation) change registers. private func rmsNormalizedSSD(_ a: [Float], _ b: [Float], skip: Int = 4096, window: Int = 4096) -> Double { guard a.count >= skip + window, b.count >= skip + window else { return 0.0 } let aw: ArraySlice = a[skip..<(skip + window)] let bw: ArraySlice = b[skip..<(skip + window)] func rms(_ x: ArraySlice) -> Double { let sumSq: Double = x.reduce(0.0) { $0 + Double($1) * Double($1) } return (sumSq / Double(x.count)).squareRoot() } let ra: Double = rms(aw) let rb: Double = rms(bw) guard ra > 0.0, rb > 0.0 else { return 0.0 } return zip(aw, bw).reduce(0.0) { acc, pair in let d: Double = Double(pair.0) / ra - Double(pair.1) / rb return acc + d * d } } /// The three concrete voices under test, keyed by their display name / registry key. private let voices: [(name: String, make: () -> AmpVoicePedal)] = [ ("California", { CaliforniaAmpPedal() }), ("British", { BritishAmpPedal() }), ("Chime", { ChimeAmpPedal() }), ] @Test func allVoicesBuildNonSilentFiniteOutput() throws { for voice in voices { let samples: [Float] = try render(voice.make) #expect(!samples.isEmpty) #expect(hasNonSilentOutput(samples), "\(voice.name) produced silence") #expect(samples.allSatisfy { $0.isFinite }, "\(voice.name) produced non-finite output") } } @Test func gainChangesOutput() throws { for voice in voices { let clean: [Float] = try render(voice.make) { $0.gain = 2.0 } let hot: [Float] = try render(voice.make) { $0.gain = 25.0 } #expect(windowedSSD(clean, hot) > 0, "\(voice.name) gain had no effect") } } @Test func toneControlsChangeOutput() throws { for voice in voices { let dark: [Float] = try render(voice.make) { $0.treble = 0.0; $0.bass = 1.0 } let bright: [Float] = try render(voice.make) { $0.treble = 1.0; $0.bass = 0.0 } #expect(windowedSSD(dark, bright) > 0, "\(voice.name) tone controls had no effect") } } @Test func midChangesOutput() throws { for voice in voices { let scooped: [Float] = try render(voice.make) { $0.mid = 0.0 } let full: [Float] = try render(voice.make) { $0.mid = 1.0 } #expect(windowedSSD(scooped, full) > 0, "\(voice.name) mid control had no effect") } } @Test func cabChangesOutput() throws { for voice in voices { let cabA: [Float] = try render(voice.make) { $0.cab = 0.0 } let cabB: [Float] = try render(voice.make) { $0.cab = 2.0 } #expect(windowedSSD(cabA, cabB) > 0, "\(voice.name) cab selection had no effect") } } @Test func outputStaysWithinDigitalCeiling() throws { // The tanh soft-limits and the trailing Clip(±1) hard-clamps, so no sample may exceed ±1 // (a tiny epsilon covers float round-trip through the CAF). Drive every voice hard. let ceilingEpsilon: Double = 1.0e-4 for voice in voices { let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in pedal.gain = 30.0 pedal.bass = 1.0 pedal.treble = 1.0 } let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) } #expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) peak \(peak) exceeds the ±1 ceiling") #expect(peak > 0.3, "\(voice.name) unexpectedly quiet at max gain: \(peak)") } } // MARK: - Signature controls @Test func californiaBrightChangesOutput() throws { let flat: [Float] = try render({ CaliforniaAmpPedal() }) { $0.bright = 0.0 } let sparkle: [Float] = try render({ CaliforniaAmpPedal() }) { $0.bright = 1.0 } #expect(windowedSSD(flat, sparkle) > 0, "California Bright had no effect") } @Test func britishPresenceChangesOutput() throws { let flat: [Float] = try render({ BritishAmpPedal() }) { $0.presence = 0.0 } let lifted: [Float] = try render({ BritishAmpPedal() }) { $0.presence = 1.0 } #expect(windowedSSD(flat, lifted) > 0, "British Presence had no effect") } @Test func britishMasterDrivesPowerAmp() throws { // Master drives the power-amp stage into saturation — so it must change the *waveshape*, not // just the level (which is what `level` would do). RMS-normalize each window before diffing: // a pure level change collapses to ~0, so a clearly-positive normalized SSD proves genuine // power-amp saturation. let low: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 12.0; $0.master = 0.1 } let high: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 12.0; $0.master = 1.0 } #expect(hasNonSilentOutput(low) && hasNonSilentOutput(high)) #expect(rmsNormalizedSSD(low, high) > 1.0e-3, "Master changed level but not tone (no power-amp saturation)") } @Test func britishStaysWithinCeilingAtMaxMaster() throws { let ceilingEpsilon: Double = 1.0e-4 let hot: [Float] = try render({ BritishAmpPedal() }) { (pedal: BritishAmpPedal) in pedal.gain = 30.0 pedal.bass = 1.0 pedal.treble = 1.0 pedal.master = 1.0 } let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) } #expect(peak <= 1.0 + ceilingEpsilon, "British peak \(peak) exceeds the ±1 ceiling at max Master") } @Test func britishMasterRoundTripsThroughState() throws { let pedal: BritishAmpPedal = BritishAmpPedal() pedal.master = 0.8 let restored: BritishAmpPedal = BritishAmpPedal() restored.applyState(pedal.captureState()) #expect(restored.master == 0.8, "Master did not round-trip") } @Test func chimeCutChangesOutput() throws { let open: [Float] = try render({ ChimeAmpPedal() }) { $0.cut = 0.0 } let dark: [Float] = try render({ ChimeAmpPedal() }) { $0.cut = 1.0 } #expect(windowedSSD(open, dark) > 0, "Chime Cut had no effect") } // MARK: - Power-amp Sag / Bias (shared) @Test func sagChangesOutput() throws { for voice in voices { let stiff: [Float] = try render(voice.make) { $0.gain = 20.0; $0.sag = 0.0 } let saggy: [Float] = try render(voice.make) { $0.gain = 20.0; $0.sag = 1.0 } #expect(windowedSSD(stiff, saggy) > 0, "\(voice.name) Sag had no effect") } } @Test func sagStaysWithinCeilingWithoutPhaseInversion() throws { // Sag is a gain droop; it must attenuate loud content, never phase-invert it. The envelope // tracks a post-power-amp signal that can exceed 1, so the droop gain is clamped positive. // Assert the sagged output correlates positively with the stiff one (not an inverted copy) // and never breaches the ±1 ceiling. let ceilingEpsilon: Double = 1.0e-4 for voice in voices { let cfg: (AmpVoicePedal) -> Void = { (p: AmpVoicePedal) in p.gain = 25.0; p.bass = 1.0; p.treble = 1.0 } let stiff: [Float] = try render(voice.make) { cfg($0); $0.sag = 0.0 } let saggy: [Float] = try render(voice.make) { cfg($0); $0.sag = 1.0 } let peak: Double = saggy.reduce(0.0) { Swift.max($0, abs(Double($1))) } #expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) sagged peak \(peak) exceeds ±1") let skip: Int = 4096, window: Int = 4096 guard stiff.count >= skip + window, saggy.count >= skip + window else { Issue.record("\(voice.name) render too short"); continue } let dotProduct: Double = zip(stiff[skip..<(skip + window)], saggy[skip..<(skip + window)]) .reduce(0.0) { acc, pair in acc + Double(pair.0) * Double(pair.1) } #expect(dotProduct > 0, "\(voice.name) Sag phase-inverted the signal (dot \(dotProduct) < 0)") } } @Test func biasChangesWaveshape() throws { // Bias shifts the power-amp tanh operating point → changes the even/odd harmonic mix (a // waveshape change), not merely the level. RMS-normalize so a pure level difference collapses. for voice in voices { let cold: [Float] = try render(voice.make) { $0.gain = 22.0; $0.bias = 0.0 } let hot: [Float] = try render(voice.make) { $0.gain = 22.0; $0.bias = 1.0 } #expect(hasNonSilentOutput(cold) && hasNonSilentOutput(hot)) #expect(rmsNormalizedSSD(cold, hot) > 1.0e-4, "\(voice.name) Bias changed level but not waveshape") } } @Test func neutralBiasAndZeroSagAreIdentityDefault() throws { // The shipped defaults are sag = 0 and bias = 0.5 (neutral). Setting them explicitly to those // values must be bit-for-bit identical to leaving them at their defaults — proof the new // controls don't perturb any existing amp's voice at their neutral position. for voice in voices { let byDefault: [Float] = try render(voice.make) let explicit: [Float] = try render(voice.make) { $0.sag = 0.0; $0.bias = 0.5 } #expect(windowedSSD(byDefault, explicit) == 0, "\(voice.name) neutral Sag/Bias is not identity") } } @Test func advancedKnobsExposeSagAndBias() throws { for voice in voices { let pedal: AmpVoicePedal = voice.make() #expect(pedal.advancedKnobs.map { $0.label } == ["Sag", "Bias"], "\(voice.name) advanced knobs") // Sag/Bias are pop-over-only — they must NOT also appear on the pedal face. let faceLabels: [String] = pedal.effectKnobs.map { $0.label } #expect(!faceLabels.contains("Sag") && !faceLabels.contains("Bias"), "\(voice.name) leaked Sag/Bias onto the pedal face") } } @Test func sagBiasRoundTripThroughState() throws { let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal() pedal.sag = 0.7 pedal.bias = 0.2 let restored: CaliforniaAmpPedal = CaliforniaAmpPedal() restored.applyState(pedal.captureState()) #expect(restored.sag == 0.7 && restored.bias == 0.2, "Sag/Bias did not round-trip through state") } // MARK: - Chrome / config @Test func exposesControls() throws { #expect(CaliforniaAmpPedal().effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Bright"]) #expect(BritishAmpPedal().effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence", "Master"]) #expect(ChimeAmpPedal().effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Cut"]) for voice in voices { let pedal: AmpVoicePedal = voice.make() #expect(pedal.effectSelectors.map { $0.label } == ["Cab"], "\(voice.name) selectors") #expect(pedal.effectSelectors.first?.rebuildsOnChange == true, "\(voice.name) cab selector should rebuild on change") #expect(pedal.widthUnits == 2, "\(voice.name) amp head should use a double-width card") #expect(pedal.showsMixControl == false, "\(voice.name) should be fully wet") } } @Test func distinctToneStackModels() throws { #expect(CaliforniaAmpPedal().toneStackModel == .fender) #expect(BritishAmpPedal().toneStackModel == .marshall) #expect(ChimeAmpPedal().toneStackModel == .vox) } @Test func selectionsRoundTripThroughState() throws { let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal() pedal.gain = 12.0 pedal.cab = 2.0 pedal.bright = 0.8 let restored: CaliforniaAmpPedal = CaliforniaAmpPedal() restored.applyState(pedal.captureState()) #expect(restored.gain == 12.0 && restored.cab == 2.0 && restored.bright == 0.8, "California controls did not round-trip") } @Test func registeredInBuiltInRegistry() throws { #expect(PedalRegistry.makePedal(type: "California") is CaliforniaAmpPedal) #expect(PedalRegistry.makePedal(type: "British") is BritishAmpPedal) #expect(PedalRegistry.makePedal(type: "Chime") is ChimeAmpPedal) } }