Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift
josh 3e3f86b737 feat(karplus): collapse tuning UI to a Free/Pitched switch + one Root knob
Replace the four-control tuning surface (continuous Tune Hz knob + Tuning
selector + separate Note and Octave selectors) with a single Free/Pitched
switch and one chromatic Root selector that steps every semitone from E1
(MIDI 28) to E5 (MIDI 76), captioned by note name ("E1", "A3", "E5"). The
Root selector is shown only in Pitched mode; in Free mode the continuous
Tune Hz knob drives the root as before.

- Drop the `note`/`octave` @UIParams and `noteFrequency(pitchClass:octave:)`;
  add a `pitchedNote` @UIParam (MIDI note number, A3=57=220 Hz default) and
  `frequency(forMidiNote:)` / `caption(forMidiNote:)` helpers.
- Knob positions are unchanged (Tune always present), so positional presets
  stay aligned; only the trailing selector set varies by mode, with Voicing
  pinned at index 0.
- Document the switch-before-selector pass order in Pedal.applyState as
  contractual: a mode-dependent selector set (like this one) relies on it.

798 tests pass; lyrebird_external_review clean (no blocking findings).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 17:29:15 -08:00

496 lines
22 KiB
Swift

// KarplusResonatorPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A single decaying pluck: a sine whose amplitude ramps from full to zero over `burstDur`, then
/// holds silent. Lets a test see the resonator bank ring on in the silence after the note has gone.
@MainActor
private final class TestPluckSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
private let amp: Double
private let burstDur: Double
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
self.targetBus = targetBus
self.freq = freq
self.amp = amplitude
self.burstDur = burstDur
super.init()
}
override func build() {
// Line 1→0 over burstDur, holding 0 after — a pluck that decays to silence, so the pedal's
// gate opens during the note and closes once it has faded, letting the strings ring.
let env: Line.Control = Line.Control(start: amp, end: 0.0, dur: burstDur)
output(bus: targetBus, source: OscSin.Audio(freq: freq) * env)
}
}
/// A steady sine source for the bypass click test — a stable tone with no silence, so the transition
/// step can be compared against a real steady-state slope.
@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("KarplusResonatorPedal")
struct KarplusResonatorPedalTests {
private let sampleRate: Double = 44_100.0
private let pluckHz: Double = 110.0
private let burstDur: Double = 0.4
/// Minimum RMS to count a tail as an audible, sustained ring.
private let tailRmsFloor: Double = 1.0e-3
// MARK: - Render
private func renderPluck(
duration: Double = 2.0,
amplitude: Double = 0.7,
configure: (KarplusResonatorPedal) -> Void
) throws -> [Float] {
try render(duration: duration, pluck: true, amplitude: amplitude, configure: configure)
}
private func render(
duration: Double,
pluck: Bool,
amplitude: Double = 0.7,
configure: (KarplusResonatorPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
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: SynthesizerBase = pluck
? TestPluckSource(targetBus: srcBus.index, freq: pluckHz, amplitude: amplitude, burstDur: burstDur)
: TestSineSource(targetBus: srcBus.index, freq: pluckHz)
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(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: - Analysis
/// RMS of the left channel over an interleaved-frame range `[loFrame, hiFrame)`.
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
let a: Int = max(0, loFrame)
let b: Int = min(hiFrame, samples.count / 2)
guard b > a else { return 0.0 }
var sum: Double = 0.0
for i: Int in a ..< b {
let v: Double = Double(samples[2 * i])
sum += v * v
}
return (sum / Double(b - a)).squareRoot()
}
/// Autocorrelation fundamental of the left channel over `[skip, skip + window)`, searching
/// `[minHz, maxHz]`.
private func fundamentalHz(
_ samples: [Float],
skip: Int,
window: Int,
minHz: Double,
maxHz: Double
) -> Double {
let needed: Int = skip + window
guard samples.count >= 2 * needed else { return 0.0 }
var x: [Double] = []
x.reserveCapacity(window)
for i: Int in skip ..< needed {
x.append(Double(samples[2 * i]))
}
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)
}
/// RMS of the sample-by-sample difference between two renders' left channels over `[loFrame, hiFrame)`.
private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double {
let lo: Int = max(0, loFrame)
let hi: Int = min(hiFrame, min(a.count, b.count) / 2)
guard hi > lo else { return 0.0 }
var sum: Double = 0.0
for i: Int in lo ..< hi {
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
sum += d * d
}
return (sum / Double(hi - lo)).squareRoot()
}
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
}
/// Start of the tail-analysis window, in frames — well past the pluck's decay to silence, so only
/// the ringing resonator bank remains.
private var tailSkipFrames: Int { Int(0.7 * sampleRate) }
/// Tail-analysis window length in frames (~0.37 s).
private var tailWindowFrames: Int { 16_384 }
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try renderPluck { _ in }
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "resonator output was silent")
}
@Test func ringsAfterNoteDecays() throws {
// The pluck decays to silence by burstDur (0.4 s). A plain effect would then be silent; the
// sympathetic strings keep ringing, so the tail well past the note is non-trivial.
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
}
let tail: Double = rms(out, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
#expect(tail > tailRmsFloor, "expected a sustained sympathetic ring after the note, tail RMS \(tail)")
}
@Test func tailIsPitchedToTuneRoot() throws {
// Drone voicing tunes the strings to root/5th/oct/oct+5th, which all share the root's period,
// so the ringing tail's fundamental sits at the Tune root (not the 110 Hz pluck pitch).
let tune: Double = 82.41
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 0.0
}
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 40.0, maxHz: 400.0)
let tolerance: Double = 0.1
#expect(abs(f - tune) / tune < tolerance,
"tail fundamental \(f) Hz should sit near the Tune root \(tune) Hz")
}
@Test func sustainLengthensTheTail() throws {
// More sustain = higher string feedback = a louder ring at the same point in the tail.
let low: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.1; pedal.sensitivity = 0.6
}
let high: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.95; pedal.sensitivity = 0.6
}
let tailLow: Double = rms(low, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
let tailHigh: Double = rms(high, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
#expect(tailHigh > tailLow,
"higher sustain should ring louder in the tail: high \(tailHigh) vs low \(tailLow)")
}
@Test func voicingRetunesTheRing() throws {
// Each voicing tunes the strings to a different chord, so the ringing tail differs
// substantially between two voicings at the same Tune root.
let tune: Double = 82.41
let drone: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 0.0
}
let octaves: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = tune; pedal.voicing = 1.0
}
let diff: Double = rmsDiff(drone, octaves, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
let droneTail: Double = rms(drone, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
// The difference should be a real fraction of the ring, not analysis noise.
#expect(diff > droneTail * 0.25,
"two voicings should ring differently: tail diff \(diff) vs drone tail \(droneTail)")
}
@Test func freeModeReachesTrebleStaffTop() throws {
// Free-mode Tune now reaches E5 (≈ 659 Hz, top of the treble staff). Drone voicing shares the
// root period, so the ring's fundamental sits at the set root.
let e5: Double = 659.25
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tuning = 0.0; pedal.tune = e5; pedal.voicing = 0.0
}
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 300.0, maxHz: 900.0)
#expect(abs(f - e5) / e5 < 0.1, "Free Tune at E5 should ring near \(e5) Hz, got \(f)")
}
@Test func renderIsDeterministic() throws {
// Every node in the bank is deterministic (no RNG), so two identical renders are bit-identical.
let a: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
let b: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
#expect(a == b, "deterministic resonator renders of the same setting should be bit-identical")
}
@Test func fullScaleBankStaysBelowClipping() throws {
// A full-scale pluck at max sustain, fully wet. The bank is scaled by 1/stringCount, so even
// when a voicing's strings align (shared periods) the summed output must stay near unity —
// no clipping without a limiter. Checked across all three voicings.
let ceiling: Double = 1.05
for voicingIndex: Int in 0 ..< 3 {
let out: [Float] = try renderPluck(amplitude: 1.0) { pedal in
pedal.mix = 1.0; pedal.sustain = 1.0; pedal.sensitivity = 0.8
pedal.voicing = Double(voicingIndex)
}
var peak: Double = 0.0
for i: Int in 0 ..< (out.count / 2) {
let v: Double = abs(Double(out[2 * i]))
if v > peak { peak = v }
}
#expect(peak <= ceiling, "voicing \(voicingIndex) peaked at \(peak), above the \(ceiling) ceiling")
}
}
// MARK: - Bypass
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) 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: pluckHz)
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.sustain = 0.7
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()
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
flipped = true
}
engine.processBlock(inputSamples: noInput)
left.append(contentsOf: engine.audioBuses[0])
frame += blockSize
}
engine.stop()
return left
}
@Test func bypassSwitchIsClickFree() throws {
let blockSize: Int = 512
let totalFrames: Int = 26_460
let flipFrame: Int = 15_435
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
let fadeFrames: Int = Int(0.03 * sampleRate)
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Wiring
@Test func exposesControls() throws {
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"])
// One Tuning switch, Free/Pitched.
#expect(pedal.effectSwitches.map { $0.label } == ["Tuning"])
let tuning: PedalSwitch? = pedal.effectSwitches.first { $0.label == "Tuning" }
#expect(tuning?.options.map { $0.title } == ["Free", "Pitched"])
#expect(tuning?.rebuildsOnChange == true)
// Default (Free) shows only the Voicing selector — the Root note knob is hidden.
#expect(pedal.effectSelectors.map { $0.label } == ["Voicing"])
#expect(pedal.effectSelectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"])
// Pitched reveals the Root chromatic selector at index 1, spanning E1 … E5.
pedal.tuning = 1.0
#expect(pedal.effectSelectors.map { $0.label } == ["Voicing", "Root"])
let root: PedalSelectorKnob? = pedal.effectSelectors.first { $0.label == "Root" }
#expect(root?.stops.count == 49) // MIDI 28 … 76 inclusive
#expect(root?.stops.first?.title == "E1")
#expect(root?.stops.last?.title == "E5")
}
@Test func frequencyMapsEqualTemperament() throws {
// A4 = 440 (MIDI 69), so A3 (MIDI 57) = 220; C4 (middle C, MIDI 60) ≈ 261.63.
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 57) - 220.0) < 0.01)
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 69) - 440.0) < 0.01)
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 60) - 261.6256) < 0.01)
#expect(KarplusResonatorPedal.caption(forMidiNote: 28) == "E1")
#expect(KarplusResonatorPedal.caption(forMidiNote: 57) == "A3")
#expect(KarplusResonatorPedal.caption(forMidiNote: 76) == "E5")
#expect(KarplusResonatorPedal.caption(forMidiNote: 61) == "C♯4") // sharp pitch class
}
@Test func pitchedModeTunesTheRootToThePitch() throws {
// Tuning = Pitched, A3 (MIDI 57), Drone voicing → the ring's fundamental sits at 220 Hz
// regardless of the 110 Hz pluck or the Tune Hz knob.
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tune = 60.0 // deliberately off, to prove Pitched overrides it
pedal.tuning = 1.0; pedal.pitchedNote = 57.0
}
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 400.0)
#expect(abs(f - 220.0) / 220.0 < 0.1, "Pitched A3 should ring near 220 Hz, got \(f)")
}
@Test func pitchedModeOctaveRaisesThePitch() throws {
// A3 (MIDI 57) vs A4 (MIDI 69) — one octave up should roughly double the ring fundamental.
let a3: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tuning = 1.0; pedal.pitchedNote = 57.0
}
let a4: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tuning = 1.0; pedal.pitchedNote = 69.0
}
let f3: Double = fundamentalHz(a3, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0)
let f4: Double = fundamentalHz(a4, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0)
#expect(f4 > f3 * 1.5, "A4 should ring well above A3: a4 \(f4) vs a3 \(f3)")
}
@Test func pitchedModeReachesTrebleStaffTop() throws {
// The Root selector's top stop is E5 (MIDI 76 ≈ 659 Hz). Drone voicing shares the root period.
let e5: Double = 659.25
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tuning = 1.0; pedal.pitchedNote = 76.0; pedal.voicing = 0.0
}
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 300.0, maxHz: 900.0)
#expect(abs(f - e5) / e5 < 0.1, "Pitched E5 should ring near \(e5) Hz, got \(f)")
}
@Test func presetRoundTripPreservesControls() throws {
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
pedal.tune = 123.4
pedal.sustain = 0.85
pedal.tone = 0.6
pedal.sensitivity = 0.3
pedal.voicing = 2.0
pedal.tuning = 1.0 // Pitched, so the Root selector is captured
pedal.pitchedNote = 64.0 // E4
let state: PedalState = pedal.captureState()
let restored: KarplusResonatorPedal = KarplusResonatorPedal()
restored.applyState(state)
#expect(restored.tune == 123.4)
#expect(restored.sustain == 0.85)
#expect(restored.tone == 0.6)
#expect(restored.sensitivity == 0.3)
#expect(restored.voicing == 2.0)
#expect(restored.tuning == 1.0)
#expect(restored.pitchedNote == 64.0)
}
@Test func freeStateRestoresOntoAPitchedPedal() throws {
// A Free preset applied to an instance already in Pitched mode: the switch pass writes
// tuning = 0 before effectSelectors is re-read, so the selector list collapses to [Voicing]
// and the stale Root value is dropped — no positional corruption.
let saved: KarplusResonatorPedal = KarplusResonatorPedal() // defaults to Free
saved.voicing = 1.0
saved.tune = 200.0
let state: PedalState = saved.captureState()
#expect(state.selectorValues.count == 1, "a Free preset should carry only the Voicing selector")
let target: KarplusResonatorPedal = KarplusResonatorPedal()
target.tuning = 1.0 // put it in Pitched first
target.pitchedNote = 76.0
target.applyState(state)
#expect(target.tuning == 0.0, "restoring a Free preset should return the switch to Free")
#expect(target.voicing == 1.0)
#expect(target.tune == 200.0)
#expect(target.effectSelectors.map { $0.label } == ["Voicing"])
}
@Test func pitchedNoteClampsOutOfRange() throws {
// A pitchedNote past the Root selector's E1…E5 window still rings (clamped at build time),
// never crashing or going silent.
let out: [Float] = try renderPluck { pedal in
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
pedal.tuning = 1.0; pedal.pitchedNote = 200.0 // far above E5
}
#expect(hasNonSilentOutput(out), "out-of-range pitchedNote should clamp and still ring")
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Karplus Resonator")
#expect(pedal is KarplusResonatorPedal)
}
}