From 4a5d4009f6319d5b5e2b9c376e5da7e187ac1118 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 1 Aug 2026 16:56:08 -0700 Subject: [PATCH] feat(pedals): Cabinet IR pedal (S1) with synthesized cab voices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit First amp-modeling increment (ShoeGaze 2.0, plan S1). No Lyrebird change — reuses ConvolutionReverb + LyrebirdBuffer. - CabinetPedal: builds one ConvolutionReverb per built-in voice at build() time and picks the active one with a `Select` driven by the persisted `cabinet` selector — live cab switching that round-trips through the rig save format. - CabinetVoice + CabinetIRFactory: three built-in voicings synthesized in code (impulse through an RBJ biquad cascade — HP, true 4th-order Butterworth LP, body + presence peaks), so the bundled cab set is our own MIT content (no third-party IR licensing). Filter centre frequencies are Nyquist-clamped. - Registered in PedalRegistry / PedalType / PedalCategory (.filter) / palette; README pedal count + catalog updated. User-supplied captured .wav cab IRs are a planned follow-up (needs a persisted file-path field PedalState doesn't yet carry). Tests: IR is finite, peak-normalized, mono; rolls off lows and highs; voices differ; selector exposed; selection changes output and round-trips through PedalState; pedal builds, non-silent, resolves from the registry. Suite 486. Co-Authored-By: Claude Opus 4.8 --- README.md | 4 +- .../Cabinet/CabinetIRFactory.swift | 157 ++++++++++++++++++ .../Cabinet/CabinetVoice.swift | 84 ++++++++++ Sources/LyrebirdShoeGaze/PedalType.swift | 1 + .../Pedals/CabinetPedal.swift | 112 +++++++++++++ .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGazeUI/PedalCategory.swift | 1 + .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 2 +- Sources/LyrebirdShoeGazeUI/PedalView.swift | 1 + .../CabinetIRFactoryTests.swift | 69 ++++++++ .../CabinetPedalTests.swift | 85 ++++++++++ 11 files changed, 514 insertions(+), 3 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Cabinet/CabinetIRFactory.swift create mode 100644 Sources/LyrebirdShoeGaze/Cabinet/CabinetVoice.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/CabinetPedal.swift create mode 100644 Tests/LyrebirdShoeGazeTests/CabinetIRFactoryTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/CabinetPedalTests.swift diff --git a/README.md b/README.md index 775a1cf..5da6952 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ signal (no hardware needed) or on live guitar through an audio input. ## Features -- **35 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and +- **36 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and texture — see the catalog below. - **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a @@ -39,7 +39,7 @@ signal (no hardware needed) or on live guitar through an audio input. |---|---| | Gain | Overdrive, Distortion, Fuzz | | Dynamics | Compressor, Sustainer, Limiter, Noise Gate | -| EQ & filter | Graphic EQ, Auto-Wah, Mutant | +| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Cabinet | | Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator | | Pitch | Bass Octaver, Octave Splitter, Harmonizer | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay | diff --git a/Sources/LyrebirdShoeGaze/Cabinet/CabinetIRFactory.swift b/Sources/LyrebirdShoeGaze/Cabinet/CabinetIRFactory.swift new file mode 100644 index 0000000..e4d11fe --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Cabinet/CabinetIRFactory.swift @@ -0,0 +1,157 @@ +// CabinetIRFactory.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import Darwin + +/// Fraction of the sample rate above which a filter centre frequency is clamped, so the RBJ +/// coefficients stay well-behaved below Nyquist even at low sample rates. +private let cabinetBiquadNyquistFraction: Double = 0.49 +/// RBJ-cookbook divisor converting a peaking-filter gain in dB to its `A` amplitude term. +private let cabinetPeakingGainDivisor: Double = 40.0 + +/// Synthesizes a short cabinet impulse response for a ``CabinetVoice`` by running a unit +/// impulse through a cascade of RBJ biquads (high-pass → two-stage low-pass → low-mid body +/// peak → presence peak) and capturing the result into a mono ``LyrebirdBuffer``. +/// +/// This runs **off the RT thread** (at pedal build time), so it uses plain `Double` math with +/// no allocation constraints. The produced buffer is a normal IR consumed by `ConvolutionReverb`. +public enum CabinetIRFactory { + + /// Default IR length in frames. 1024 taps (~21 ms at 48 kHz) is ample for a speaker-cab + /// magnitude curve, which has no long tail. + public static let defaultFrames: Int = 1024 + + /// Butterworth Q for the high-pass (low rolloff) stage. + private static let highPassQ: Double = 0.707 + /// Per-stage Q values for a true 4th-order Butterworth low-pass built as two cascaded + /// biquads (maximally flat passband). Q ≈ 0.5412 and 1.3066. + private static let lowPassCascadeQ: [Double] = [0.541_196_100_146_197, 1.306_562_964_876_377] + /// Q for the resonant body / presence peaks. + private static let peakQ: Double = 1.2 + + /// Builds the impulse response for `voice` at `sampleRate`. + /// + /// - Parameters: + /// - voice: The cabinet voicing to synthesize. + /// - sampleRate: Engine sample rate in Hz. + /// - frames: IR length in frames. Defaults to ``defaultFrames``. + /// - Returns: A mono `LyrebirdBuffer` holding the normalized IR, tagged with `sampleRate`. + public static func makeIR( + voice: CabinetVoice, + sampleRate: Double, + frames: Int = CabinetIRFactory.defaultFrames + ) -> LyrebirdBuffer { + var chain: [OfflineBiquad] = [ + OfflineBiquad.highPass(freq: voice.highPassHz, q: highPassQ, sampleRate: sampleRate), + OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[0], sampleRate: sampleRate), + OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[1], sampleRate: sampleRate), + OfflineBiquad.peaking(freq: voice.bodyHz, q: peakQ, gainDb: voice.bodyGainDb, sampleRate: sampleRate), + OfflineBiquad.peaking(freq: voice.presenceHz, q: peakQ, gainDb: voice.presenceGainDb, sampleRate: sampleRate), + ] + + var ir: [Double] = [Double](repeating: 0.0, count: frames) + for n: Int in 0.. 0.0 { + let inv: Double = 1.0 / peak + for i: Int in ir.indices { ir[i] *= inv } + } + + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: 1) + buffer.fill(using: { (frame: Int, _: Int) -> Double in ir[frame] }) + buffer.setSampleRate(sampleRate) + return buffer + } +} + +/// A minimal off-RT RBJ biquad (transposed Direct Form II) used only to render cabinet IRs. +private struct OfflineBiquad { + private let b0: Double + private let b1: Double + private let b2: Double + private let a1: Double + private let a2: Double + private var z1: Double = 0.0 + private var z2: Double = 0.0 + + private init( + b0: Double, + b1: Double, + b2: Double, + a1: Double, + a2: Double + ) { + self.b0 = b0 + self.b1 = b1 + self.b2 = b2 + self.a1 = a1 + self.a2 = a2 + } + + /// Centre frequency clamped below Nyquist for the given sample rate. + private static func clampedFreq(_ freq: Double, sampleRate: Double) -> Double { + Swift.min(freq, sampleRate * cabinetBiquadNyquistFraction) + } + + mutating func process(_ x: Double) -> Double { + let y: Double = b0 * x + z1 + z1 = b1 * x - a1 * y + z2 + z2 = b2 * x - a2 * y + return y + } + + static func highPass(freq: Double, q: Double, sampleRate: Double) -> OfflineBiquad { + let f: Double = clampedFreq(freq, sampleRate: sampleRate) + let w0: Double = 2.0 * Double.pi * f / sampleRate + let cosW0: Double = cos(w0) + let alpha: Double = sin(w0) / (2.0 * q) + let a0: Double = 1.0 + alpha + let b0: Double = (1.0 + cosW0) / 2.0 + let b1: Double = -(1.0 + cosW0) + let b2: Double = (1.0 + cosW0) / 2.0 + let a1: Double = -2.0 * cosW0 + let a2: Double = 1.0 - alpha + return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0) + } + + static func lowPass(freq: Double, q: Double, sampleRate: Double) -> OfflineBiquad { + let f: Double = clampedFreq(freq, sampleRate: sampleRate) + let w0: Double = 2.0 * Double.pi * f / sampleRate + let cosW0: Double = cos(w0) + let alpha: Double = sin(w0) / (2.0 * q) + let a0: Double = 1.0 + alpha + let b0: Double = (1.0 - cosW0) / 2.0 + let b1: Double = 1.0 - cosW0 + let b2: Double = (1.0 - cosW0) / 2.0 + let a1: Double = -2.0 * cosW0 + let a2: Double = 1.0 - alpha + return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0) + } + + static func peaking(freq: Double, q: Double, gainDb: Double, sampleRate: Double) -> OfflineBiquad { + let f: Double = clampedFreq(freq, sampleRate: sampleRate) + let amplitude: Double = pow(10.0, gainDb / cabinetPeakingGainDivisor) + let w0: Double = 2.0 * Double.pi * f / sampleRate + let cosW0: Double = cos(w0) + let alpha: Double = sin(w0) / (2.0 * q) + let a0: Double = 1.0 + alpha / amplitude + let b0: Double = 1.0 + alpha * amplitude + let b1: Double = -2.0 * cosW0 + let b2: Double = 1.0 - alpha * amplitude + let a1: Double = -2.0 * cosW0 + let a2: Double = 1.0 - alpha / amplitude + return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0) + } +} diff --git a/Sources/LyrebirdShoeGaze/Cabinet/CabinetVoice.swift b/Sources/LyrebirdShoeGaze/Cabinet/CabinetVoice.swift new file mode 100644 index 0000000..d68c432 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Cabinet/CabinetVoice.swift @@ -0,0 +1,84 @@ +// CabinetVoice.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// A built-in guitar-speaker-cabinet voicing. +/// +/// Each voice is a compact set of target-response parameters (low/high rolloff, a low-mid +/// "body" bump, and a presence peak) from which ``CabinetIRFactory`` synthesizes a short +/// impulse response entirely in code. These IRs are **our own content** (MIT, generated, no +/// third-party capture), so they ship with the pedal without licensing concerns. (Loading a +/// user-supplied captured `.wav` cab IR is a planned follow-up.) +/// +/// The values are deliberately broad-strokes voicings, not measurements of specific hardware. +public enum CabinetVoice: String, CaseIterable, Sendable { + case americanCombo + case britishStack + case vintageDark + + /// Human-readable name for pickers. + public var displayName: String { + switch self { + case .americanCombo: return "American 1×12" + case .britishStack: return "British 4×12" + case .vintageDark: return "Vintage Dark" + } + } + + /// Low-frequency rolloff (high-pass cutoff) in Hz — the speaker's bass limit. + var highPassHz: Double { + switch self { + case .americanCombo: return 80.0 + case .britishStack: return 95.0 + case .vintageDark: return 90.0 + } + } + + /// High-frequency rolloff (low-pass cutoff) in Hz — the speaker's top-end limit. Applied as a + /// two-stage cascade for a steeper, more speaker-like slope. + var lowPassHz: Double { + switch self { + case .americanCombo: return 5500.0 + case .britishStack: return 4500.0 + case .vintageDark: return 3800.0 + } + } + + /// Low-mid "body" peak centre in Hz. + var bodyHz: Double { + switch self { + case .americanCombo: return 420.0 + case .britishStack: return 700.0 + case .vintageDark: return 500.0 + } + } + + /// Low-mid body peak gain in dB (may be negative for a scoop). + var bodyGainDb: Double { + switch self { + case .americanCombo: return 1.5 + case .britishStack: return -2.0 + case .vintageDark: return 2.0 + } + } + + /// Presence peak centre in Hz — the upper-mid "bite". + var presenceHz: Double { + switch self { + case .americanCombo: return 3000.0 + case .britishStack: return 2500.0 + case .vintageDark: return 2200.0 + } + } + + /// Presence peak gain in dB. + var presenceGainDb: Double { + switch self { + case .americanCombo: return 3.0 + case .britishStack: return 4.0 + case .vintageDark: return 2.0 + } + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 65db3eb..79d38d3 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -50,6 +50,7 @@ public extension PedalType { static let compressor = PedalType("Compressor") static let limiter = PedalType("Limiter") static let noiseGate = PedalType("Noise Gate") + static let cabinet = PedalType("Cabinet") // EQ & filter static let graphicEQ = PedalType("Graphic EQ") diff --git a/Sources/LyrebirdShoeGaze/Pedals/CabinetPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/CabinetPedal.swift new file mode 100644 index 0000000..ba3ba71 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/CabinetPedal.swift @@ -0,0 +1,112 @@ +// CabinetPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Speaker-cabinet simulation via impulse-response convolution. +/// +/// Convolves the input against a cabinet impulse response using Lyrebird's partitioned FFT +/// convolver (`ConvolutionReverb`). One convolver per built-in ``CabinetVoice`` is built at +/// `build()` time (each voicing's IR is synthesized in code — our own MIT content, see +/// ``CabinetIRFactory``); a `Select` driven by the ``cabinet`` knob picks the active one, so +/// switching cabs is live and round-trips through the rig save format like every other pedal. +/// +/// Signal path (inside `effect(_:)`): +/// ``` +/// dry → [ConvolutionReverb(ir: voice0), …] → Select(which: cabinet) → mono out +/// ``` +/// +/// The wet/dry mix and bypass are handled by the `Pedal` base class. +/// +/// > Note: Loading a user-supplied captured `.wav` cab IR is a planned follow-up (it needs a +/// > persisted file-path field the current `PedalState` doesn't carry); this first version ships +/// > the built-in voicings only. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - `cabinet`: Selects the built-in cabinet voicing (stepped selector over ``CabinetVoice``). +public final class CabinetPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Speaker-cabinet impulse-response convolution with selectable built-in voicings." + } + + // MARK: - Parameters + + /// Selected cabinet voicing as an index into ``CabinetVoice/allCases``. Snaps to integer + /// stops via the ``cabinet`` selector; read live by the `Select` in `effect(_:)`. + @UIParam public var cabinet: Double = 0.0 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet; the cabinet sits in-line. + private static let defaultMix: Double = 1.0 + + /// Convolution is taken fully wet here; the `Pedal` base class provides the user wet/dry mix. + private let convolutionMix: Double = 1.0 + + /// Selector stops, one per ``CabinetVoice`` in `allCases` order (value == index). + private static let voiceStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases + .enumerated() + .map { (index: Int, voice: CabinetVoice) in + PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index)) + } + + // MARK: - Init + + /// Creates a cabinet 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: "Cabinet", + inputBus: inputBus, + outputBus: outputBus, + initialMix: CabinetPedal.defaultMix + ) + } + + // MARK: - UI + + public override var effectSelectors: [PedalSelectorKnob] { + [ + PedalSelectorKnob(label: "Cab", node: $cabinet, stops: CabinetPedal.voiceStops), + ] + } + + // MARK: - Effect + + /// Convolves the dry signal against every built-in cabinet IR and selects the active one. + /// + /// All voices' convolvers are built at `build()` time; `Select` picks per the live `cabinet` + /// index each block. Every convolver keeps running (SC `Select` semantics), so their internal + /// state stays in sync across a switch — but the output changes on the switch sample, so a + /// hard cab change can click; cabs are normally set-and-forget, and a smooth crossfade is a + /// possible later refinement. Synthesizing the short IRs happens off the RT thread in `build()`. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: The cabinet-convolved mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let sr: Double = sampleRate + let convolvers: [any ValidGeneratorInput] = CabinetVoice.allCases.map { (voice: CabinetVoice) in + ConvolutionReverb.Audio( + input: dry, + ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr), + mix: convolutionMix + ) + } + return Select.Audio(which: $cabinet, inputs: convolvers) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 6eb2ffd..b94690b 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -56,6 +56,7 @@ public enum PedalRegistry { "Room Reverb": { RoomReverbPedal() }, "Spring Reverb": { SpringReverbPedal() }, "Limiter": { LimiterPedal() }, + "Cabinet": { CabinetPedal() }, "Noise Gate": { NoiseGatePedal() }, "Graphic EQ": { GraphicEQPedal() }, "Chorus": { ChorusPedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift index 4d970ca..9cfbb18 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift @@ -45,6 +45,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable { "Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain, "Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics, "Graphic EQ": .filter, "Auto-Wah": .filter, "Wah": .filter, "Mutant": .filter, + "Cabinet": .filter, "Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation, "Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation, "Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index c4415fb..595707c 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -57,7 +57,7 @@ public struct PedalPaletteView: View { "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Volume", "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", - "Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", + "Auto-Wah", "Wah", "Mutant", "Cabinet", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", "Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", "Shimmer Reverb", "Plate Reverb", "Room Reverb", "Spring Reverb", diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 524b6b2..cc6661f 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -39,6 +39,7 @@ private func enclosureColor(for displayName: String) -> Color { case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal + case "Cabinet": return Color(red: 0.50, green: 0.36, blue: 0.18) // tweed / cabinet tan case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue diff --git a/Tests/LyrebirdShoeGazeTests/CabinetIRFactoryTests.swift b/Tests/LyrebirdShoeGazeTests/CabinetIRFactoryTests.swift new file mode 100644 index 0000000..6ef6e8e --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/CabinetIRFactoryTests.swift @@ -0,0 +1,69 @@ +// CabinetIRFactoryTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("CabinetIRFactory") +struct CabinetIRFactoryTests { + + private let sampleRate: Double = 48000.0 + + /// Goertzel magnitude of the IR's frequency response at `hz`. + private func responseMagnitude(_ ir: LyrebirdBuffer, hz: Double) -> Double { + let omega: Double = 2.0 * Double.pi * hz / sampleRate + let cosine: Double = cos(omega) + let sine: Double = sin(omega) + let coeff: Double = 2.0 * cosine + var s1: Double = 0.0 + var s2: Double = 0.0 + for i: Int in 0.. 0.9 && peak <= 1.0001, "\(voice) IR not peak-normalized: \(peak)") + } + } + + @Test func rollsOffLowAndHighFrequencies() { + // A speaker cab attenuates sub-bass and high treble relative to the midrange. + let ir: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .americanCombo, sampleRate: sampleRate) + let low: Double = responseMagnitude(ir, hz: 40.0) // below the ~80 Hz high-pass + let mid: Double = responseMagnitude(ir, hz: 800.0) // passband + let high: Double = responseMagnitude(ir, hz: 12000.0) // above the ~5.5 kHz low-pass + #expect(mid > low * 2.0, "low end not attenuated (mid=\(mid) low=\(low))") + #expect(mid > high * 2.0, "high end not attenuated (mid=\(mid) high=\(high))") + } + + @Test func voicesDifferInResponse() { + let american: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .americanCombo, sampleRate: sampleRate) + let dark: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .vintageDark, sampleRate: sampleRate) + // The darker voice rolls off earlier, so it has less 5 kHz energy than the American voice. + let americanHigh: Double = responseMagnitude(american, hz: 5000.0) + let darkHigh: Double = responseMagnitude(dark, hz: 5000.0) + #expect(americanHigh > darkHigh, "vintageDark should be darker at 5 kHz") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/CabinetPedalTests.swift b/Tests/LyrebirdShoeGazeTests/CabinetPedalTests.swift new file mode 100644 index 0000000..807b046 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/CabinetPedalTests.swift @@ -0,0 +1,85 @@ +// CabinetPedalTests.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("CabinetPedal") +struct CabinetPedalTests { + + private func render(configure: (CabinetPedal) -> Void = { _ in }) throws -> [Float] { + let sampleRate: Double = 48000.0 + 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: CabinetPedal = CabinetPedal(inputBus: srcBus.index, 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) + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render() + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "CabinetPedal produced silence") + } + + @Test func cabinetSelectionChangesOutput() throws { + // Index 0 = American 1×12, index 2 = Vintage Dark — different voicings, different output. + let american: [Float] = try render { $0.cabinet = 0.0 } + let dark: [Float] = try render { $0.cabinet = 2.0 } + #expect(hasNonSilentOutput(american) && hasNonSilentOutput(dark)) + + let skip: Int = 4096 + let window: Int = 4096 + guard american.count >= skip + window, dark.count >= skip + window else { return } + let ssd: Double = zip(american[skip..<(skip + window)], dark[skip..<(skip + window)]).reduce(0.0) { acc, pair in + let d: Double = Double(pair.0 - pair.1); return acc + d * d + } + #expect(ssd > 0, "cabinet selection had no effect on output") + } + + @Test func exposesCabinetSelector() throws { + let pedal: CabinetPedal = CabinetPedal() + let labels: [String] = pedal.effectSelectors.map { $0.label } + #expect(labels == ["Cab"]) + // One stop per voice, in allCases order. + let stops: [String] = pedal.effectSelectors.first?.stops.map { $0.title } ?? [] + #expect(stops == CabinetVoice.allCases.map { $0.displayName }) + } + + @Test func cabinetSelectionRoundTripsThroughState() throws { + // The selector value must survive capture/apply (preset round-trip). + let pedal: CabinetPedal = CabinetPedal() + pedal.cabinet = 2.0 + let state: PedalState = pedal.captureState() + let restored: CabinetPedal = CabinetPedal() + restored.applyState(state) + #expect(restored.cabinet == 2.0, "cabinet selection did not round-trip through PedalState") + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Cabinet") + #expect(pedal is CabinetPedal) + } +}