Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/AmpVoicePedalTests.swift
T
josh a2fcd59e1b docs+test(amp): honest Bias X wording + combined-extreme ceiling test
Review follow-ups (no blockers were found):
- Rewrite Bias X docs: it's a power-amp bias-balance CHARACTER control that
  re-shapes the saturation knee, not a literal push-pull even-harmonic model
  (averaging two same-polarity bias-offset stages doesn't replicate push-pull
  imbalance). Document that both halves are always built (2x power-amp cost
  even at biasX=0 — chosen for a smooth live knob over a rebuild-on-change
  fast path). Fix a public->internal DocC symbol link (plain code font).
- Add extremeBiasAndBiasXStayWithinCeiling: Bias hot + Bias X max drives a
  half-stage bias to ±0.6 (tanh-bounded, outputLimit-clamped) — asserts
  finite, ≤ ±1.

651 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 08:26:56 -07:00

419 lines
21 KiB
Swift

// 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<P: AmpVoicePedal>(_ 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<Float> = a[skip..<(skip + window)]
let bw: ArraySlice<Float> = b[skip..<(skip + window)]
func rms(_ x: ArraySlice<Float>) -> 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, bias = 0.5, biasX = 0 (all neutral). Setting them
// explicitly to those values must be bit-for-bit identical to leaving them at their defaults
// — proof the pop-over controls don't perturb any existing amp's voice at their neutral point.
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; $0.biasX = 0.0 }
#expect(windowedSSD(byDefault, explicit) == 0, "\(voice.name) neutral Sag/Bias/Bias X is not identity")
}
}
@Test func biasXChangesWaveshape() throws {
// Bias X spreads the two power-amp half-stages' operating points → 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 balanced: [Float] = try render(voice.make) { $0.gain = 22.0; $0.biasX = 0.0 }
let imbalanced: [Float] = try render(voice.make) { $0.gain = 22.0; $0.biasX = 1.0 }
#expect(hasNonSilentOutput(balanced) && hasNonSilentOutput(imbalanced))
#expect(rmsNormalizedSSD(balanced, imbalanced) > 1.0e-4,
"\(voice.name) Bias X changed level but not waveshape")
}
}
@Test func biasXStaysWithinCeiling() throws {
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; pedal.biasX = 1.0
}
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) Bias X peak \(peak) exceeds ±1")
}
}
@Test func extremeBiasAndBiasXStayWithinCeiling() throws {
// Bias (hot) + Bias X (max) together drive a half-stage bias to ±0.6 (base ±0.25 ± spread
// 0.35). The tanh stays bounded and outputLimit clamps — output must stay finite and ≤ ±1.
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; pedal.bias = 1.0; pedal.biasX = 1.0
}
#expect(hot.allSatisfy { $0.isFinite }, "\(voice.name) bias+biasX produced non-finite output")
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) bias+biasX peak \(peak) exceeds ±1")
}
}
@Test func advancedKnobsExposeSagBiasAndBiasX() throws {
for voice in voices {
let pedal: AmpVoicePedal = voice.make()
#expect(pedal.advancedKnobs.map { $0.label } == ["Sag", "Bias", "Bias X"],
"\(voice.name) advanced knobs")
// These 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") && !faceLabels.contains("Bias X"),
"\(voice.name) leaked an advanced knob onto the pedal face")
}
}
@Test func sagBiasRoundTripThroughState() throws {
let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal()
pedal.sag = 0.7
pedal.bias = 0.2
pedal.biasX = 0.6
let restored: CaliforniaAmpPedal = CaliforniaAmpPedal()
restored.applyState(pedal.captureState())
#expect(restored.sag == 0.7 && restored.bias == 0.2 && restored.biasX == 0.6,
"Sag/Bias/Bias X did not round-trip through state")
}
// MARK: - Cabinet decoupling
@Test func cabNoneBypassesConvolution() throws {
for voice in voices {
let withCab: [Float] = try render(voice.make) { $0.cab = 0.0 }
let none: [Float] = try render(voice.make) { $0.cab = AmpVoicePedal.cabinetBypassValue }
#expect(hasNonSilentOutput(none) && none.allSatisfy { $0.isFinite },
"\(voice.name) None-cab output silent or non-finite")
#expect(windowedSSD(withCab, none) > 0, "\(voice.name) None did not bypass the cabinet")
}
}
@Test func cabNoneStillLimitsToCeiling() throws {
// With the cabinet bypassed the output soft-limit must still run — the ±1 ceiling has to hold.
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
pedal.cab = AmpVoicePedal.cabinetBypassValue
}
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon,
"\(voice.name) None-cab peak \(peak) exceeds ±1 (output limiter lost)")
}
}
@Test func extremeCabValuesDoNotTrap() throws {
// A corrupted/hand-edited rig can restore any Double into `cab`. Neither the bypass check nor
// the voice lookup may trap `Int(_:)` — every value must resolve to a defined, finite render.
let extremes: [Double] = [.infinity, -.infinity, 1.0e20, -1.0e20, .nan, 999.0]
for cabValue: Double in extremes {
let out: [Float] = try render({ CaliforniaAmpPedal() }) { $0.cab = cabValue }
#expect(out.allSatisfy { $0.isFinite }, "cab=\(cabValue) produced non-finite output")
}
}
@Test func cabSelectorExposesNoneStop() throws {
let stops: [PedalSelectorKnob.Stop] = CaliforniaAmpPedal().effectSelectors
.first { $0.label == "Cab" }?.stops ?? []
#expect(stops.last?.title == "None (direct)", "Cab selector missing the None stop")
#expect(stops.last?.value == AmpVoicePedal.cabinetBypassValue, "None stop has the wrong value")
}
@Test func ampWithNoneCabIntoStandaloneCabinetWorks() throws {
// Decoupled chain: amp (Cab = None) → standalone Cabinet pedal. The amp emits its limited,
// cab-less signal; the separate Cabinet block does the speaker convolution downstream.
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 midBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(midBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let amp: CaliforniaAmpPedal = CaliforniaAmpPedal(inputBus: srcBus.index, outputBus: midBus.index)
amp.sampleRate = sampleRate
amp.cab = AmpVoicePedal.cabinetBypassValue
let cabinet: CabinetPedal = CabinetPedal(inputBus: midBus.index, outputBus: dstBus.index)
cabinet.sampleRate = sampleRate
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(amp, position: NodePosition.after(source))
try engine.add(cabinet, position: NodePosition.after(amp))
try engine.add(master, position: NodePosition.after(cabinet))
try engine.start()
let out: [Float] = readStereoCAF(url: url, sampleRate: sampleRate)
#expect(hasNonSilentOutput(out) && out.allSatisfy { $0.isFinite }, "decoupled amp+cabinet silent/non-finite")
// Note: the amp guarantees its OWN output ≤ ±1 (see `cabNoneStillLimitsToCeiling`), but a
// downstream standalone Cabinet convolves that signal and — like any post-amp pedal — may
// overshoot ±1. The board's final output stage, not the amp, owns end-of-chain level. So this
// asserts the decoupled chain works (non-silent, finite), not a ±1 ceiling it never promised.
}
// 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)
}
}