89a34016de
The Karplus Resonator root can now be set two ways, via a Tuning selector: - Free: the continuous Tune Hz knob (unchanged behaviour, still the default). - Note: an equal-tempered pitch chosen with Note (C…B) and Octave (1…6) selectors. A4 = 440, so A3 = 220 Hz, etc. noteFrequency() computes the root from scientific-pitch note/octave; the string bank reads whichever root the mode selects. The per-string delay line is widened to 0.08 s so the lowest Note-mode roots (down to a sub-C1 octave string) fit without the KarplusStrong frequency clamp engaging. Tests: equal-temperament mapping, Note-mode A3→220 Hz ring, octave shift, and selector/preset round-trip. Full suite 794 green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
432 lines
18 KiB
Swift
432 lines
18 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 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 exposesKnobsAndSelectors() throws {
|
|
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
|
|
#expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"])
|
|
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
|
#expect(selectors.map { $0.label } == ["Voicing", "Tuning", "Note", "Octave"])
|
|
#expect(selectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"])
|
|
let tuning: PedalSelectorKnob? = selectors.first { $0.label == "Tuning" }
|
|
#expect(tuning?.stops.map { $0.title } == ["Free", "Note"])
|
|
let note: PedalSelectorKnob? = selectors.first { $0.label == "Note" }
|
|
#expect(note?.stops.count == 12)
|
|
#expect(note?.stops.first?.title == "C")
|
|
}
|
|
|
|
@Test func noteFrequencyMapsEqualTemperament() throws {
|
|
// A4 = 440, so A3 = 220 and A4 = 440; C4 (middle C, MIDI 60) ≈ 261.63.
|
|
#expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 3) - 220.0) < 0.01)
|
|
#expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 4) - 440.0) < 0.01)
|
|
#expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 0, octave: 4) - 261.6256) < 0.01)
|
|
}
|
|
|
|
@Test func noteModeTunesTheRootToThePitch() throws {
|
|
// Tuning = Note, A3, 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 Note overrides it
|
|
pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 3.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, "Note A3 should ring near 220 Hz, got \(f)")
|
|
}
|
|
|
|
@Test func noteModeOctaveRaisesThePitch() throws {
|
|
// A3 vs A4 — 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.note = 9.0; pedal.octave = 3.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.note = 9.0; pedal.octave = 4.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 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
|
|
pedal.note = 4.0
|
|
pedal.octave = 5.0
|
|
|
|
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.note == 4.0)
|
|
#expect(restored.octave == 5.0)
|
|
}
|
|
|
|
@Test func registeredInBuiltInRegistry() throws {
|
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Karplus Resonator")
|
|
#expect(pedal is KarplusResonatorPedal)
|
|
}
|
|
}
|