feat(pedals): add Karplus Resonator, Tape Looper, and DL4 delay
Three new pedals, each wired at all four points (PedalType, PedalRegistry, PedalCategory, README) and covered by a dedicated test suite. Karplus Resonator (texture): a bank of four tuned KarplusStrong strings plucked by an amplitude-envelope → Schmitt-trigger gate off the note onset, ringing sympathetically in the tail. Tune / Sustain / Tone / Sensitivity knobs plus a Voicing selector (Drone / Octaves / Shimmer). Bank summed at 1/stringCount so a full-scale pluck stays at or below unity. Tape Looper (texture): a simple single-track looper (RecordBuffer / PlayBuffer) with record / overdub / play and the two classic tape tricks — half-speed (octave down) and reverse — as live playback-rate controls. Overdub is gated to forward-normal speed both at engage time and in the graph, so flipping Reverse/Half-Speed mid-overdub can't misalign layers. DL4 (delay): an umbrella multi-model delay with a Model selector dispatching to eight per-model builders — Tube, Tape, Analog, Analog Mod, Multi-Head, Sweep, Lo-Res, Reverse — over shared Time / Repeats / Tone / Mod controls, Time tempo-syncable. Multi-Head tap sum gain-staged to 1.0. Passed /lyrebird_external_review (RT-safety + caveman sweep); all blocking findings fixed. Full suite 791 tests green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
// DL4PedalTests.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 so a test can hear the delay repeats in the silence after the note.
|
||||
@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() {
|
||||
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 for the bypass click test.
|
||||
@MainActor
|
||||
private final class TestSineSource: SynthesizerBase {
|
||||
private let targetBus: Int
|
||||
private let freq: Double
|
||||
init(targetBus: Int, freq: Double) {
|
||||
self.targetBus = targetBus
|
||||
self.freq = freq
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite("DL4Pedal")
|
||||
struct DL4PedalTests {
|
||||
|
||||
private let sampleRate: Double = 44_100.0
|
||||
private let pluckHz: Double = 180.0
|
||||
private let burstDur: Double = 0.08
|
||||
private let renderDiffEpsilon: Double = 1.0e-3
|
||||
|
||||
private let modelCount: Int = 8
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
private func render(
|
||||
duration: Double = 1.2,
|
||||
pluck: Bool = true,
|
||||
amplitude: Double = 0.7,
|
||||
configure: (DL4Pedal) -> 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: DL4Pedal = DL4Pedal(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
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
private func rmsDiff(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let n: Int = min(a.count, b.count) / 2
|
||||
guard n > 0 else { return 0.0 }
|
||||
var sum: Double = 0.0
|
||||
for i: Int in 0 ..< n {
|
||||
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
|
||||
sum += d * d
|
||||
}
|
||||
return (sum / Double(n)).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
|
||||
}
|
||||
|
||||
/// Tail window (after the pluck has decayed), in interleaved frames.
|
||||
private var tailSkip: Int { Int(0.5 * sampleRate) }
|
||||
private var tailWindow: Int { 16_384 }
|
||||
|
||||
// MARK: - Behaviour
|
||||
|
||||
@Test func everyModelProducesEchoesAfterTheNote() throws {
|
||||
// The pluck decays by burstDur (0.08 s). Every model must still produce audible repeats well
|
||||
// into the tail at a long Time / Repeats.
|
||||
for index: Int in 0 ..< modelCount {
|
||||
let out: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = Double(index)
|
||||
pedal.time = 0.25; pedal.repeats = 4.0; pedal.mod = 0.5
|
||||
}
|
||||
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
#expect(tail > 1.0e-3, "model index \(index) produced no echo tail, RMS \(tail)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func modelsRenderDifferently() throws {
|
||||
// Two different models at the same settings should produce substantially different output.
|
||||
let tube: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.25; pedal.repeats = 3.0
|
||||
}
|
||||
let reverse: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 7.0; pedal.time = 0.25; pedal.repeats = 3.0
|
||||
}
|
||||
#expect(rmsDiff(tube, reverse) > renderDiffEpsilon,
|
||||
"Tube and Reverse models should differ substantially, diff \(rmsDiff(tube, reverse))")
|
||||
}
|
||||
|
||||
@Test func timeChangesTheEcho() throws {
|
||||
let short: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.1; pedal.repeats = 3.0
|
||||
}
|
||||
let long: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.5; pedal.repeats = 3.0
|
||||
}
|
||||
#expect(rmsDiff(short, long) > renderDiffEpsilon,
|
||||
"different delay times should render differently, diff \(rmsDiff(short, long))")
|
||||
}
|
||||
|
||||
@Test func repeatsChangesTheTailLength() throws {
|
||||
// More feedback (longer decay time) = a louder tail at the same point.
|
||||
let few: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 0.3
|
||||
}
|
||||
let many: [Float] = try render { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 6.0
|
||||
}
|
||||
let tailFew: Double = rms(few, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
let tailMany: Double = rms(many, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
#expect(tailMany > tailFew,
|
||||
"more repeats should ring louder in the tail: many \(tailMany) vs few \(tailFew)")
|
||||
}
|
||||
|
||||
@Test func multiHeadStaysBelowClipping() throws {
|
||||
// The Multi-Head tap sum (3 taps + a feedback repeat) is gain-staged to total 1.0, so a
|
||||
// full-scale input, fully wet, must not clip even where the taps align.
|
||||
let out: [Float] = try render(amplitude: 1.0) { pedal in
|
||||
pedal.mix = 1.0; pedal.model = 4.0; pedal.time = 0.15; pedal.repeats = 4.0
|
||||
}
|
||||
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 <= 1.05, "Multi-Head peaked at \(peak), above the 1.05 ceiling")
|
||||
}
|
||||
|
||||
@Test func renderIsDeterministic() throws {
|
||||
// Every model's node graph is deterministic (no RNG), so two identical renders are identical.
|
||||
for index: Int in 0 ..< modelCount {
|
||||
let a: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
|
||||
let b: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
|
||||
#expect(a == b, "model index \(index) should render bit-identically")
|
||||
}
|
||||
}
|
||||
|
||||
// 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: DL4Pedal = DL4Pedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
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 exposesKnobsAndModelSelector() throws {
|
||||
let pedal: DL4Pedal = DL4Pedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Repeats", "Tone", "Mod"])
|
||||
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||
#expect(selectors.map { $0.label } == ["Model"])
|
||||
#expect(selectors.first?.stops.count == modelCount)
|
||||
#expect(selectors.first?.stops.map { $0.title } ==
|
||||
["Tube", "Tape", "Analog", "Analog Mod", "Multi-Head", "Sweep", "Lo-Res", "Reverse"])
|
||||
}
|
||||
|
||||
@Test func timeIsTempoSyncable() throws {
|
||||
let pedal: DL4Pedal = DL4Pedal()
|
||||
#expect(pedal.tempoSyncableParams.map { $0.key } == ["time"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesControls() throws {
|
||||
let pedal: DL4Pedal = DL4Pedal()
|
||||
pedal.time = 0.33
|
||||
pedal.repeats = 2.2
|
||||
pedal.tone = 4000.0
|
||||
pedal.mod = 0.7
|
||||
pedal.model = 5.0
|
||||
|
||||
let state: PedalState = pedal.captureState()
|
||||
let restored: DL4Pedal = DL4Pedal()
|
||||
restored.applyState(state)
|
||||
|
||||
#expect(restored.time == 0.33)
|
||||
#expect(restored.repeats == 2.2)
|
||||
#expect(restored.tone == 4000.0)
|
||||
#expect(restored.mod == 0.7)
|
||||
#expect(restored.model == 5.0)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "DL4")
|
||||
#expect(pedal is DL4Pedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
// 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 exposesKnobsAndVoicingSelector() 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"])
|
||||
#expect(selectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"])
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Karplus Resonator")
|
||||
#expect(pedal is KarplusResonatorPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// TapeLooperPedalTests.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("TapeLooperPedal")
|
||||
struct TapeLooperPedalTests {
|
||||
|
||||
private let sampleRate: Double = 44_100.0
|
||||
private let toneHz: Double = 220.0
|
||||
|
||||
// MARK: - Fixtures
|
||||
|
||||
/// A constant-frequency sine with a live-settable amplitude, so a test can silence the live input
|
||||
/// at an exact time and attribute any remaining output to the loop.
|
||||
private final class ToneSource: SynthesizerBase {
|
||||
let ampNode: ParameterNode = ParameterNode(0.4)
|
||||
var amplitude: Double {
|
||||
get { ampNode.value }
|
||||
set { ampNode.value = newValue }
|
||||
}
|
||||
private let targetBus: Int
|
||||
private let toneFreq: Double
|
||||
|
||||
init(targetBus: Int, freq: Double) {
|
||||
self.targetBus = targetBus
|
||||
self.toneFreq = freq
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts a `TriggerEvent` at an exact time within a single NRT render, so a test can flip a
|
||||
/// transport action mid-render.
|
||||
private final class TimedTrigger: SynthesizerBase {
|
||||
private let fireTime: Double
|
||||
private let triggerID: Int32
|
||||
private static let minRampDuration: Double = 0.001
|
||||
|
||||
init(fireTime: Double, id: Int32) {
|
||||
self.fireTime = fireTime
|
||||
self.triggerID = id
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0
|
||||
let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration)
|
||||
_ = SendTrigger.Control(trig: ramp, id: triggerID)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
private func render(
|
||||
totalDuration: Double,
|
||||
toneFreq: Double = 220.0,
|
||||
configure: (
|
||||
_ engine: SynthesisEngine,
|
||||
_ source: ToneSource,
|
||||
_ pedal: TapeLooperPedal,
|
||||
_ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void
|
||||
) throws -> Void
|
||||
) throws -> [Float] {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 64,
|
||||
numControlBuses: 512,
|
||||
driver: driver
|
||||
)
|
||||
let listener: TriggerListener = TriggerListener(engine: engine)
|
||||
driver.triggerListener = listener
|
||||
|
||||
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: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
|
||||
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
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))
|
||||
|
||||
var nextTriggerID: Int32 = 0
|
||||
let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in
|
||||
nextTriggerID += 1
|
||||
let id: Int32 = nextTriggerID
|
||||
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
|
||||
try engine.add(trigger)
|
||||
listener.addHandler(id: id) { _, _ in
|
||||
MainActor.assumeIsolated { action() }
|
||||
}
|
||||
}
|
||||
|
||||
try configure(engine, source, pedal, scheduleAction)
|
||||
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
// MARK: - Analysis
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// Record a loop from 0 → recordDur, then close + play; the caller may tweak the pedal at play.
|
||||
private let recordDur: Double = 0.15
|
||||
private let totalDur: Double = 0.7
|
||||
/// Tail window (loop-only, after the live input is silenced), in interleaved frames.
|
||||
private var tailSkip: Int { Int(0.45 * sampleRate) }
|
||||
private var tailWindow: Int { 8_192 }
|
||||
|
||||
/// Builds an offline engine driving a steady tone into the looper, records a real loop (so
|
||||
/// `masterLength > 0`), closes it, and leaves the pedal in the playing state. Returns the engine
|
||||
/// (kept alive by the caller) and the pedal for state-machine assertions.
|
||||
private func makePlayingLooper(recordBlocks: Int = 8) throws -> (SynthesisEngine, TapeLooperPedal) {
|
||||
let blockSize: Int = 512
|
||||
let driver: OfflineDriver = OfflineDriver()
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 64,
|
||||
numControlBuses: 512,
|
||||
driver: driver
|
||||
)
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz)
|
||||
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
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]] = []
|
||||
pedal.pressRecord() // begin recording
|
||||
for _: Int in 0 ..< recordBlocks { engine.processBlock(inputSamples: noInput) }
|
||||
pedal.pressRecord() // close + play (frames recorded)
|
||||
engine.processBlock(inputSamples: noInput)
|
||||
return (engine, pedal)
|
||||
}
|
||||
|
||||
// MARK: - Controls
|
||||
|
||||
@Test func exposesTapeLooperControls() throws {
|
||||
let pedal: TapeLooperPedal = TapeLooperPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Playback", "Feedback"])
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Direction", "Speed"])
|
||||
#expect(pedal.effectTransportButtons.map { $0.label } == ["Record", "Stop", "Clear"])
|
||||
}
|
||||
|
||||
@Test func isDoubleWidthAndHidesMix() throws {
|
||||
#expect(TapeLooperPedal().widthUnits == 2)
|
||||
#expect(TapeLooperPedal().showsMixControl == false)
|
||||
}
|
||||
|
||||
@Test func rebuildWipesTheRecordedLoop() throws {
|
||||
// effect() runs from build(), re-invoked on every add (a board edit re-adds this instance).
|
||||
// A rebuild must start clean — a previously recorded loop must not survive it.
|
||||
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||
#expect(pedal.hasLoop, "fixture should have recorded a loop")
|
||||
_ = pedal.effect(OscSin.Audio(freq: 100.0)) // simulate a second build()
|
||||
#expect(pedal.hasLoop == false, "a rebuild must wipe the recorded loop")
|
||||
#expect(pedal.loopFrameCount == 0)
|
||||
}
|
||||
|
||||
// MARK: - Audio behaviour
|
||||
|
||||
@Test func clearStatePassesDryThrough() throws {
|
||||
let out: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
|
||||
#expect(hasNonSilentOutput(out), "an empty looper should pass the dry signal through")
|
||||
}
|
||||
|
||||
@Test func recordedLoopPlaysBackAfterInputSilenced() throws {
|
||||
// Record a tone, close + play, then silence the live input. The loop must keep sounding.
|
||||
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||
pedal.pressRecord() // begin recording at t = 0
|
||||
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
|
||||
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||
}
|
||||
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
#expect(tail > 1.0e-3, "recorded loop should keep playing after the input is silenced, tail RMS \(tail)")
|
||||
}
|
||||
|
||||
@Test func clearSilencesTheLoop() throws {
|
||||
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||
pedal.pressRecord()
|
||||
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
|
||||
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||
try scheduleAction(0.35) { pedal.clearLoop() } // wipe the loop
|
||||
}
|
||||
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
#expect(tail < 1.0e-3, "after Clear with the input silenced the output should be silent, tail RMS \(tail)")
|
||||
}
|
||||
|
||||
@Test func halfSpeedLowersLoopPitch() throws {
|
||||
// Record a 220 Hz loop, then play it at half speed: the loop-only tail should drop an octave.
|
||||
let normal: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
|
||||
pedal.pressRecord()
|
||||
try scheduleAction(recordDur) { pedal.pressRecord() }
|
||||
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||
}
|
||||
let half: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
|
||||
pedal.pressRecord()
|
||||
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.halfSpeed = 1.0 }
|
||||
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||
}
|
||||
let fNormal: Double = fundamentalHz(normal, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
|
||||
let fHalf: Double = fundamentalHz(half, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
|
||||
#expect(abs(fNormal - toneHz) / toneHz < 0.1, "normal loop should sound at the recorded pitch, got \(fNormal) Hz")
|
||||
#expect(abs(fHalf - toneHz * 0.5) / (toneHz * 0.5) < 0.12,
|
||||
"half-speed loop should sound an octave down (~\(toneHz * 0.5) Hz), got \(fHalf) Hz")
|
||||
}
|
||||
|
||||
@Test func reversePlaybackStillRunsTheLoop() throws {
|
||||
// A reversed loop still plays (non-silent after the input is silenced).
|
||||
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||
pedal.pressRecord()
|
||||
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.reverse = 1.0 }
|
||||
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||
}
|
||||
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||
#expect(tail > 1.0e-3, "reversed loop should keep playing, tail RMS \(tail)")
|
||||
}
|
||||
|
||||
@Test func overdubBlockedWhileReversedOrHalfSpeed() throws {
|
||||
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||
#expect(pedal.hasLoop)
|
||||
#expect(pedal.isOverdubbing == false)
|
||||
|
||||
// Forward normal speed: overdub engages.
|
||||
pedal.pressRecord()
|
||||
#expect(pedal.isOverdubbing == true)
|
||||
pedal.pressRecord() // toggle it back off
|
||||
#expect(pedal.isOverdubbing == false)
|
||||
|
||||
// Reversed: overdub is blocked at engage time.
|
||||
pedal.reverse = 1.0
|
||||
pedal.pressRecord()
|
||||
#expect(pedal.isOverdubbing == false, "overdub must be blocked while reversed")
|
||||
|
||||
// Half speed: overdub is blocked at engage time.
|
||||
pedal.reverse = 0.0
|
||||
pedal.halfSpeed = 1.0
|
||||
pedal.pressRecord()
|
||||
#expect(pedal.isOverdubbing == false, "overdub must be blocked at half speed")
|
||||
}
|
||||
|
||||
@Test func recordLedTracksTransportState() throws {
|
||||
// Regression: closing a loop must not leave the Record LED stuck lit for the whole playback.
|
||||
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||
#expect(pedal.recordIndicator == 0.0, "Record LED should be off while just playing")
|
||||
#expect(pedal.stoppedIndicator == 0.0)
|
||||
|
||||
pedal.pressRecord() // engage overdub
|
||||
#expect(pedal.recordIndicator == 1.0, "Record LED should light while overdubbing")
|
||||
pedal.pressRecord() // disengage
|
||||
#expect(pedal.recordIndicator == 0.0, "Record LED should clear when overdub ends")
|
||||
|
||||
pedal.stopPlayback()
|
||||
#expect(pedal.stoppedIndicator == 1.0, "Stop LED should light when stopped")
|
||||
#expect(pedal.recordIndicator == 0.0)
|
||||
}
|
||||
|
||||
// MARK: - Bypass
|
||||
|
||||
private final class TestSineSource: SynthesizerBase {
|
||||
private let targetBus: Int
|
||||
private let freq: Double
|
||||
init(targetBus: Int, freq: Double) {
|
||||
self.targetBus = targetBus
|
||||
self.freq = freq
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func bypassSwitchIsClickFree() throws {
|
||||
let blockSize: Int = 512
|
||||
let totalFrames: Int = 26_460
|
||||
let flipFrame: Int = 15_435
|
||||
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: toneHz)
|
||||
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
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()
|
||||
|
||||
#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 presetRoundTripPreservesControls() throws {
|
||||
let pedal: TapeLooperPedal = TapeLooperPedal()
|
||||
pedal.playbackLevel = -6.0
|
||||
pedal.feedback = 0.75
|
||||
pedal.reverse = 1.0
|
||||
pedal.halfSpeed = 1.0
|
||||
|
||||
let state: PedalState = pedal.captureState()
|
||||
let restored: TapeLooperPedal = TapeLooperPedal()
|
||||
restored.applyState(state)
|
||||
|
||||
#expect(restored.playbackLevel == -6.0)
|
||||
#expect(restored.feedback == 0.75)
|
||||
#expect(restored.reverse == 1.0)
|
||||
#expect(restored.halfSpeed == 1.0)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Tape Looper")
|
||||
#expect(pedal is TapeLooperPedal)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user