// WhammyPedalTests.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 pitch tests — a known, stable fundamental the shifter can act on so a /// test can measure the output pitch, which the arpeggiated `TestLoopSource` (pitch changing three /// times a second) cannot support. @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)) } } @MainActor @Suite("WhammyPedal") struct WhammyPedalTests { // MARK: - Analysis constants /// Engine sample rate (matches `makeNRTEngine`'s default). private let sampleRate: Double = 44_100.0 /// Render long enough that the analysis window lands well past the shifter's warm-up. private let renderDuration: Double = 0.8 /// Test tone fundamental. Mid-range so ±2 octaves stays inside `[20, Nyquist]`. private let sineHz: Double = 220.0 /// Interleaved-stereo frame offset to start analysis at — clears the shifter's warm-up. private let analysisSkipFrames: Int = 13_230 // ~0.3 s /// Analysis window length in frames. ~0.37 s → ≥10 cycles even at the −3-octave Dive Bomb. private let analysisWindowFrames: Int = 16_384 // MARK: - Render helpers /// Renders the pedal driven by the arpeggiated `TestLoopSource` (for non-pitch checks). private func render( configure: (WhammyPedal) -> Void ) throws -> [Float] { try renderThroughPedal(source: { bus in TestLoopSource(targetBus: bus) }, configure: configure) } /// Renders the pedal driven by a steady sine at `sineHz` (for pitch checks). private func renderSine( configure: (WhammyPedal) -> Void ) throws -> [Float] { try renderThroughPedal( source: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) }, configure: configure ) } /// Renders the steady sine straight to the master with no pedal in the path — a dry reference /// for correlation tests. private func renderSineDry() throws -> [Float] { let numAudioBuses: Int = 64 let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( duration: renderDuration, numAudioBuses: numAudioBuses ) defer { try? FileManager.default.removeItem(at: url) } let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) defer { engine.busAllocator.releaseAudioBus(srcBus) } let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz) let master: TestRouteMaster = TestRouteMaster(inputBusIndex: srcBus.index) try engine.add(source) try engine.add(master, position: NodePosition.after(source)) try engine.start() return readStereoCAF(url: url) } /// Shared body: `source` writes the pedal's input bus, the pedal processes it, the master routes /// the pedal output to the hardware file. private func renderThroughPedal( source makeSource: (Int) -> any Synthesizer, configure: (WhammyPedal) -> Void ) throws -> [Float] { let numAudioBuses: Int = 64 let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( duration: renderDuration, 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: WhammyPedal = WhammyPedal( 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: - Signal analysis /// Estimates the fundamental of the left channel by autocorrelation — robust to the grain-splice /// glitches a zero-crossing count would miscount. Searches lags in `[20 Hz, maxHz]`; a deep /// down-shift carries strong grain-rate HF that a wide search would lock onto instead of the /// intended low fundamental, so callers testing those modes pass a ceiling near the expected Hz. private func fundamentalHz(_ samples: [Float], maxHz: Double = 1_500.0) -> Double { let minHz: Double = 20.0 let needed: Int = analysisSkipFrames + analysisWindowFrames guard samples.count >= 2 * needed else { return 0.0 } var x: [Double] = [] x.reserveCapacity(analysisWindowFrames) for i: Int in analysisSkipFrames ..< needed { x.append(Double(samples[2 * i])) // left channel of the interleaved pair } // Remove DC so the autocorrelation peak reflects periodicity, not offset. let mean: Double = x.reduce(0.0, +) / Double(x.count) for i: Int in x.indices { x[i] -= mean } let minLag: Int = Int(sampleRate / maxHz) let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1) guard maxLag > minLag else { return 0.0 } var bestLag: Int = minLag var bestCorr: Double = -Double.infinity for lag: Int in minLag ... maxLag { var c: Double = 0.0 for i: Int in 0 ..< (x.count - lag) { c += x[i] * x[i + lag] } if c > bestCorr { bestCorr = c bestLag = lag } } return sampleRate / Double(bestLag) } /// Pearson correlation of two renders' left channels over the analysis window. Scale-invariant, /// so gain differences between the two signals don't matter — only shared waveform shape does. private func correlation(_ a: [Float], _ b: [Float]) -> Double { let needed: Int = analysisSkipFrames + analysisWindowFrames guard a.count >= 2 * needed, b.count >= 2 * needed else { return 0.0 } var xa: [Double] = [] var xb: [Double] = [] xa.reserveCapacity(analysisWindowFrames) xb.reserveCapacity(analysisWindowFrames) for i: Int in analysisSkipFrames ..< needed { xa.append(Double(a[2 * i])) xb.append(Double(b[2 * i])) } let n: Double = Double(xa.count) let ma: Double = xa.reduce(0.0, +) / n let mb: Double = xb.reduce(0.0, +) / n var num: Double = 0.0 var da: Double = 0.0 var db: Double = 0.0 for i: Int in 0 ..< xa.count { let u: Double = xa[i] - ma let v: Double = xb[i] - mb num += u * v da += u * u db += v * v } guard da > 0.0, db > 0.0 else { return 0.0 } return num / (da * db).squareRoot() } // MARK: - Pitch behaviour @Test func pitchShiftsUpTwoOctavesAtToe() throws { // 2 Oct Up (mode 0): toe = +24 st = ratio 4. A 220 Hz tone should land near 880 Hz, and well // above the unison it produces at the heel. let heel: [Float] = try renderSine { pedal in pedal.mode = 0.0 pedal.position = 0.0 } let toe: [Float] = try renderSine { pedal in pedal.mode = 0.0 pedal.position = 1.0 } let heelHz: Double = fundamentalHz(heel) let toeHz: Double = fundamentalHz(toe) #expect(hasNonSilentOutput(toe), "2 Oct Up toe render was silent") #expect(abs(heelHz - sineHz) < sineHz * 0.3, "heel should be unison (~220 Hz), got \(heelHz)") #expect(abs(toeHz - sineHz * 4.0) < sineHz * 4.0 * 0.3, "2 Oct Up toe should be ~880 Hz, got \(toeHz)") #expect(toeHz > heelHz * 2.0, "toe pitch should be far above the heel") } @Test func pitchShiftsDownAnOctaveAtToe() throws { // Oct Down (mode 2): toe = −12 st = ratio 0.5. 220 Hz should land near 110 Hz, below unison. let heel: [Float] = try renderSine { pedal in pedal.mode = 2.0 pedal.position = 0.0 } let toe: [Float] = try renderSine { pedal in pedal.mode = 2.0 pedal.position = 1.0 } let heelHz: Double = fundamentalHz(heel) let toeHz: Double = fundamentalHz(toe) #expect(hasNonSilentOutput(toe), "Oct Down toe render was silent") #expect(abs(toeHz - sineHz * 0.5) < sineHz * 0.5 * 0.3, "Oct Down toe should be ~110 Hz, got \(toeHz)") #expect(toeHz < heelHz * 0.7, "toe pitch should be well below the heel") } @Test func diveBombCascadeReachesThreeOctaves() throws { // Dive Bomb (mode 4, cascade) toe = −36 st = ratio 0.125 → ~27.5 Hz. It must drop below the // single-stage 2 Oct Down (mode 3, −24 st = ~55 Hz), proving the second cascade stage engaged. // Cap the search near the expected low fundamentals so the deep-shift grain HF can't win. let deepCeilingHz: Double = 120.0 let twoOctDownHz: Double = fundamentalHz(try renderSine { pedal in pedal.mode = 3.0 pedal.position = 1.0 }, maxHz: deepCeilingHz) let diveBomb: [Float] = try renderSine { pedal in pedal.mode = 4.0 pedal.position = 1.0 } let diveHz: Double = fundamentalHz(diveBomb, maxHz: deepCeilingHz) #expect(hasNonSilentOutput(diveBomb), "Dive Bomb render was silent") #expect(abs(diveHz - sineHz * 0.125) < sineHz * 0.125 * 0.35, "Dive Bomb toe should be ~27.5 Hz, got \(diveHz)") #expect(diveHz < twoOctDownHz * 0.75, "Dive Bomb (\(diveHz) Hz) should dive below 2 Oct Down (\(twoOctDownHz) Hz)") } @Test func harmonyKeepsDryVoiceUnderShifted() throws { // Oct Up/Dn (mode 6) at the toe shifts a voice to −12 st AND keeps the dry note. Its output // must correlate with the dry signal far more than the wet-only Oct Down (mode 2, also −12 st, // no dry) does — the only difference between the two is the summed-in dry voice. let dry: [Float] = try renderSineDry() let harmony: [Float] = try renderSine { pedal in pedal.mode = 6.0 // Oct Up/Dn — toe = −12 st, dry + shifted pedal.position = 1.0 } let wetOnly: [Float] = try renderSine { pedal in pedal.mode = 2.0 // Oct Down — toe = −12 st, shifted only pedal.position = 1.0 } let harmonyCorr: Double = correlation(harmony, dry) let wetCorr: Double = correlation(wetOnly, dry) #expect(hasNonSilentOutput(harmony), "harmony render was silent") #expect(harmonyCorr > wetCorr + 0.2, "harmony should correlate with the dry signal far more than the wet-only shift (harmony \(harmonyCorr) vs wet-only \(wetCorr))") } @Test func renderIsDeterministic() throws { // Every PitchShift stage is seeded, and the sine source is RNG-free, so two identical renders // must be bit-identical. (Guards the seeding that makes the pitch assertions meaningful.) let a: [Float] = try renderSine { pedal in pedal.mode = 4.0 // Dive Bomb — exercises both cascade stages' seeds pedal.position = 0.6 } let b: [Float] = try renderSine { pedal in pedal.mode = 4.0 pedal.position = 0.6 } #expect(a == b, "seeded renders of the same setting should be bit-identical") } // MARK: - Bypass transition /// Renders the Whammy manually block-by-block through a no-op `OfflineDriver`, flipping `bypass` /// from engaged (`0`) to bypassed (`1`) at `flipFrame`, and returns the left hardware-output /// channel. Hand-stepping `processBlock` is the only way to change a live `@UIParam` mid-render — /// `NRTDriver.start()` renders the whole file in one blocking call with no seam to intervene at. private func renderBypassFlip( mode: Double, position: Double, flipFrame: Int, totalFrames: Int, blockSize: Int = 64 ) 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: WhammyPedal = WhammyPedal(inputBus: srcBus.index, outputBus: dstBus.index) pedal.mode = mode pedal.position = position 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)) // OfflineDriver.start() is a no-op, so this allocates buses + builds the node tree without // rendering; the block loop below drives the render by hand. 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 // engage → bypassed, mid-render flipped = true } engine.processBlock(inputSamples: noInput) let bus: [Float] = engine.audioBuses[0] // hardware output, left left.append(contentsOf: bus) frame += blockSize } engine.stop() return left } /// Max absolute first difference (per-sample step) over `[lo, hi)`. An impulsive click shows up /// here as a step far larger than the signal's own slope. 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 } @Test func bypassSwitchIsClickFree() throws { // Clocking a wet-only pitch voice (Oct Up, +12 at the toe) on/off crossfades the dry note // against a fully decorrelated shifted voice. The linear-slew equal-power bypass crossfade // must keep that transition click-free: no impulsive step and no energy dropout at the seam. // (A naive hard gate, or the old front-loaded one-pole lag, spikes the first difference here.) // Use the engine's real 512-sample block: a block-rate bypass smoother takes only a few // coarse steps per short fade at this size, so testing at a small block would hide the click. let blockSize: Int = 512 let totalFrames: Int = 26_460 // 0.6 s at 44.1 kHz let flipFrame: Int = 15_435 // ~0.35 s let left: [Float] = try renderBypassFlip( mode: 1.0, // Oct Up — wet only, +12 st at the toe position: 1.0, flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize ) #expect(hasNonSilentOutput(left), "bypass-flip render was silent") // Steady engaged region, past the shifter warm-up and before the flip. let steadyLo: Int = 9_700 // ~0.22 s let steadyHi: Int = 14_500 // ~0.33 s // Transition region: the flip plus the fade time and a little settle. let fadeFrames: Int = Int(0.03 * sampleRate) let transLo: Int = flipFrame - blockSize let transHi: Int = flipFrame + fadeFrames + 2_000 let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi) let transStep: Double = maxStep(left, lo: transLo, hi: transHi) // No impulsive click: the biggest per-sample step across the seam stays within a small // multiple of the signal's own steady-state slope (grain splices included). This is the real // guard — at the engine's 512-sample block a block-rate smoother (the old one-pole lag, or a // control-rate slew) leaks a coarse step here; the audio-rate slew ramps per sample. // (Energy continuity is not asserted: the Oct Up wet voice's inherent SOLA amplitude warble // swamps any seam-level change, so a short-window RMS is not a usable dropout metric here.) #expect(transStep <= steadyStep * 4.0, "bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through") } // MARK: - Build / wiring @Test func buildsAndProducesNonSilentOutput() throws { let samples: [Float] = try render { pedal in pedal.mode = 0.0 // 2 Oct Up pedal.position = 0.5 } #expect(!samples.isEmpty) #expect(hasNonSilentOutput(samples), "whammy output was silent") } @Test func exposesPedalKnobAndModeSelector() throws { let pedal: WhammyPedal = WhammyPedal() #expect(pedal.effectKnobs.map { $0.label } == ["Pedal"]) let selectors: [PedalSelectorKnob] = pedal.effectSelectors #expect(selectors.map { $0.label } == ["Mode"]) let titles: [String] = selectors.first?.stops.map { $0.title } ?? [] #expect(titles.contains("2 Oct Up")) #expect(titles.contains("Dive Bomb")) #expect(titles.contains("Drop Tune")) #expect(titles.contains("Oct Up/Dn")) #expect(titles.contains("Detune Deep")) } @Test func presetRoundTripPreservesModeAndPosition() throws { let pedal: WhammyPedal = WhammyPedal() pedal.position = 0.75 pedal.mode = 2.0 // Oct Down let state: PedalState = pedal.captureState() #expect(state.selectorValues == [2.0], "mode should round-trip as the sole selector value") #expect(state.knobValues.first == 0.75, "position should be the first knob value") let restored: WhammyPedal = WhammyPedal() restored.applyState(state) #expect(restored.position == 0.75) #expect(restored.mode == 2.0) } @Test func modeSwitchRebuildsBoard() throws { // Each program is a distinct voice topology read at build time, so the Mode selector must // drive a board rebuild — a plain node write would leave the audible program stuck. let pedal: WhammyPedal = WhammyPedal() pedal.mode = 3.0 #expect(pedal.rebuildTopologyValues == [3.0], "Mode must be a rebuildsOnChange selector so switching programs re-enters effect(_:)") } @Test func registeredInBuiltInRegistry() throws { let pedal: Pedal? = PedalRegistry.makePedal(type: "Whammy") #expect(pedal is WhammyPedal) } }