Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal: - Beat-quantized transport: record start and loop close both snap to the next beat via a LyrebirdRoutine waiting on the shared clock; loop length is an exact whole-beat span. Falls back to immediate/unquantized when no clock is present. - Loop-length read-outs (frames/seconds/beats), transport state, and a sample-clock-derived play-head position for the UI timeline. - Overdub undo (pre-dub snapshot + restore), reverse playback (live rate flip), and feedback-decay overdub (overdub preLevel via a Feedback knob). - Inject the shared LyrebirdClock + SynthesisEngine into Pedal via PedalBoard/ChainRouter so tempo-aware pedals can reach them. - New double-width LooperTimelineView (state badge, length read-out, sweeping play-head) wired into PedalView via Pedal.widthUnits. Concurrency hardening from RT-safety review: a transportGeneration counter drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop() cannot recall once enqueued; the undo restore is deferred past the RT overdub gate-close; transport routines use non-blocking stop(). Note: this commit also snapshots pre-existing uncommitted work-in-progress already in the tree (MIDI control refactor, Tuner, Tempo, preset changes), which is interleaved with the looper changes through shared files and could not be split into a separately-building commit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,492 @@
|
||||
// LooperPedalTests.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("LooperPedal")
|
||||
struct LooperPedalTests {
|
||||
|
||||
// MARK: - Test fixtures
|
||||
|
||||
/// A constant-frequency sine source with a live-settable amplitude, so tests can
|
||||
/// silence the live input at an exact scheduled time and attribute any remaining
|
||||
/// output unambiguously to the looper's own playback.
|
||||
private final class ToneSource: SynthesizerBase {
|
||||
let ampNode: ParameterNode = ParameterNode(0.3)
|
||||
var amplitude: Double {
|
||||
get { ampNode.value }
|
||||
set { ampNode.value = newValue }
|
||||
}
|
||||
private let targetBus: Int
|
||||
private let toneFreq: Double
|
||||
|
||||
init(targetBus: Int, freq: Double = 220.0) {
|
||||
self.targetBus = targetBus
|
||||
self.toneFreq = freq
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
|
||||
}
|
||||
}
|
||||
|
||||
/// A no-audio synth that posts a `TriggerEvent` (via `SendTrigger.Control`) at an exact
|
||||
/// sample-accurate time within a single continuous NRT render. `build()` runs eagerly at
|
||||
/// `engine.add(_:)` time, but the *trigger* it wires only fires once its own `Line.Control`
|
||||
/// ramp crosses zero at `fireTime` seconds — so combined with a `TriggerListener` handler,
|
||||
/// this is how tests schedule an exact-time side effect (e.g. flipping a looper 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)
|
||||
}
|
||||
}
|
||||
|
||||
private func rms(_ samples: [Float]) -> Double {
|
||||
guard !samples.isEmpty else { return 0 }
|
||||
let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) }
|
||||
return (sumSquares / Double(samples.count)).squareRoot()
|
||||
}
|
||||
|
||||
/// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register
|
||||
/// exact-time actions via `scheduleAction`, then renders and returns the stereo samples.
|
||||
private func render(
|
||||
totalDuration: Double,
|
||||
toneAmplitude: Double = 0.3,
|
||||
sampleRate: Double = 44100.0,
|
||||
configure: (
|
||||
_ engine: SynthesisEngine,
|
||||
_ source: ToneSource,
|
||||
_ pedal: LooperPedal,
|
||||
_ 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 numAudioBuses: Int = 64
|
||||
let numControlBuses: Int = 512
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: numAudioBuses,
|
||||
numControlBuses: numControlBuses,
|
||||
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)
|
||||
source.amplitude = toneAmplitude
|
||||
let pedal: LooperPedal = LooperPedal(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
|
||||
// `_drainSync` calls this inline, synchronously, on the same thread that
|
||||
// called `engine.start()` in NRT mode — which is this MainActor test method.
|
||||
MainActor.assumeIsolated { action() }
|
||||
}
|
||||
}
|
||||
|
||||
try configure(engine, source, pedal, scheduleAction)
|
||||
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Test func emptyPhasePassesDryThrough() throws {
|
||||
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
|
||||
#expect(hasNonSilentOutput(samples), "Looper in .empty phase should pass the dry signal through")
|
||||
}
|
||||
|
||||
@Test func recordThenPlayReproducesLoopContentAfterInputGoesSilent() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let totalDuration: Double = 0.6
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
// Begin recording immediately (post-build, pre-start): sample 0 of the render.
|
||||
pedal.toggleRecordStop()
|
||||
// Stop recording and start looping at `recordDuration`; silence the live input
|
||||
// at the same instant so anything heard afterward can only be the looped take.
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
// Look well past the crossfade convergence window so only loop content remains.
|
||||
let tailStart: Int = Int(Double(samples.count) * 0.75)
|
||||
let tail: [Float] = Array(samples[tailStart...])
|
||||
#expect(hasNonSilentOutput(tail), "Loop should keep playing after the live input is silenced")
|
||||
}
|
||||
|
||||
@Test func loopLengthBoundsPlaybackToRecordedTakeNotFullBuffer() throws {
|
||||
// Record a very short take, then render well beyond it with the input silenced.
|
||||
// Continuous non-silence over that long tail proves playback wraps at the
|
||||
// narrow recorded length, not the full 60 s allocation.
|
||||
let recordDuration: Double = 0.05
|
||||
let totalDuration: Double = 1.0
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
let lateWindowStart: Int = Int(Double(samples.count) * 0.9)
|
||||
let lateWindow: [Float] = Array(samples[lateWindowStart...])
|
||||
#expect(hasNonSilentOutput(lateWindow), "Loop should still be wrapping near the end of a 1 s render from a 0.05 s take")
|
||||
}
|
||||
|
||||
@Test func overdubAddsEnergyToTheLoop() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let overdubStart: Double = 0.2
|
||||
let overdubDuration: Double = 0.1
|
||||
let totalDuration: Double = 0.9
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 }
|
||||
try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 }
|
||||
// Silence the live input once overdubbing is done so the measurement window
|
||||
// reflects only what is now baked into the loop.
|
||||
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
let stride: Int = 2 // interleaved stereo
|
||||
let measureStart: Double = 0.6
|
||||
let measureStartIndex: Int = Int(measureStart * 44100.0) * stride
|
||||
guard measureStartIndex < samples.count else {
|
||||
Issue.record("Render too short to measure post-overdub loop content")
|
||||
return
|
||||
}
|
||||
let measured: [Float] = Array(samples[measureStartIndex...])
|
||||
#expect(hasNonSilentOutput(measured), "Loop should contain audible content after an overdub pass")
|
||||
}
|
||||
|
||||
@Test func resetLoopClearsContentAndReturnsToPassthrough() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let resetAt: Double = 0.2
|
||||
let totalDuration: Double = 0.5
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(resetAt) { pedal.resetLoop() }
|
||||
// Silence the input after reset — the loop is gone, so output should be silent.
|
||||
try scheduleAction(resetAt) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
let tailStart: Int = Int(Double(samples.count) * 0.85)
|
||||
let tail: [Float] = Array(samples[tailStart...])
|
||||
#expect(!hasNonSilentOutput(tail), "After reset + silenced input, no leftover loop content should remain")
|
||||
}
|
||||
|
||||
@Test func loopOffMutesLoopButKeepsLivePassthrough() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let loopOffAt: Double = 0.2
|
||||
let totalDuration: Double = 0.5
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(loopOffAt) { pedal.loopOn = 0.0 }
|
||||
// Keep the live tone audible (do not silence it) — loopOn muting the loop
|
||||
// should not also silence the live passthrough.
|
||||
}
|
||||
|
||||
let tailStart: Int = Int(Double(samples.count) * 0.9)
|
||||
let tail: [Float] = Array(samples[tailStart...])
|
||||
#expect(hasNonSilentOutput(tail), "Muting the loop should not silence the live passthrough")
|
||||
}
|
||||
|
||||
@Test func playbackLevelAttenuatesLoopOutput() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let totalDuration: Double = 0.5
|
||||
|
||||
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
|
||||
try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.playbackLevel = playbackLevelDb
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0))
|
||||
let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0))
|
||||
#expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB")
|
||||
let expectedRatio: Double = dbToAmp(-6.0)
|
||||
let tolerance: Double = 0.15
|
||||
let actualRatio: Double = attenuatedRMS / unityRMS
|
||||
#expect(
|
||||
abs(actualRatio - expectedRatio) < tolerance,
|
||||
"Expected ~\(expectedRatio) amplitude ratio at -6 dB, got \(actualRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func overdubLevelScalesOnlyTheNewMaterial() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let overdubStart: Double = 0.2
|
||||
let overdubDuration: Double = 0.1
|
||||
let totalDuration: Double = 0.5
|
||||
|
||||
func renderOverdub(overdubLevelDb: Double) throws -> [Float] {
|
||||
try render(totalDuration: totalDuration, toneAmplitude: 0.0) { engine, source, pedal, scheduleAction in
|
||||
// Record silence for the initial take so the loop starts at zero content —
|
||||
// isolates the overdub pass's own level.
|
||||
pedal.overdubLevel = overdubLevelDb
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(overdubStart) { source.amplitude = 0.3 }
|
||||
try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 }
|
||||
try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 }
|
||||
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
let unityRMS: Double = rms(try renderOverdub(overdubLevelDb: 0.0))
|
||||
let attenuatedRMS: Double = rms(try renderOverdub(overdubLevelDb: -6.0))
|
||||
#expect(attenuatedRMS < unityRMS, "-6 dB overdub level should bake in less energy than 0 dB")
|
||||
}
|
||||
|
||||
@Test func exposesLooperControls() throws {
|
||||
let pedal: LooperPedal = LooperPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
|
||||
#expect(pedal.effectSwitches.isEmpty)
|
||||
#expect(pedal.effectButtons.map { $0.label } ==
|
||||
["Record / Stop", "Overdub", "Undo", "Loop", "Reverse", "Reset"])
|
||||
}
|
||||
|
||||
@Test func looperIsDoubleWidth() throws {
|
||||
#expect(LooperPedal().widthUnits == 2)
|
||||
}
|
||||
|
||||
@Test func readoutsReflectRecordedTakeLength() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let sampleRate: Double = 44100.0
|
||||
var captured: LooperPedal?
|
||||
|
||||
_ = try render(totalDuration: 0.4, sampleRate: sampleRate) { engine, source, pedal, scheduleAction in
|
||||
captured = pedal
|
||||
// Surface the engine clock so the play-head anchor and read-outs are live.
|
||||
pedal.hostEngine = engine
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(recordDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
let pedal: LooperPedal = try #require(captured)
|
||||
#expect(pedal.transportState == .playing)
|
||||
// No clock injected → un-quantized fallback trims to the recorder's frame count.
|
||||
let expectedFrames: Double = recordDuration * sampleRate
|
||||
// Recorder stop is snapshot at block rate, so allow one block of slop.
|
||||
let renderBlockSize: Double = 512.0
|
||||
let tolerance: Double = renderBlockSize
|
||||
#expect(abs(Double(pedal.loopFrameCount) - expectedFrames) < tolerance,
|
||||
"loopFrameCount \(pedal.loopFrameCount) should be ~\(expectedFrames)")
|
||||
#expect(abs(pedal.loopLengthSeconds - recordDuration) < 0.02)
|
||||
#expect(pedal.loopLengthBeats == 0.0, "No clock → no beat-length read-out")
|
||||
let position: Double? = pedal.playbackPosition01()
|
||||
#expect(position != nil && position! >= 0.0 && position! < 1.0)
|
||||
}
|
||||
|
||||
@Test func transportStartsEmptyAndReturnsEmptyAfterReset() throws {
|
||||
let pedal: LooperPedal = LooperPedal()
|
||||
#expect(pedal.transportState == .empty)
|
||||
#expect(pedal.playbackPosition01() == nil)
|
||||
pedal.resetLoop()
|
||||
#expect(pedal.transportState == .empty)
|
||||
}
|
||||
|
||||
@Test func undoOverdubRestoresPreDubLoopEnergy() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let overdubStart: Double = 0.2
|
||||
let overdubDuration: Double = 0.1
|
||||
let totalDuration: Double = 0.9
|
||||
let measureStart: Double = 0.6
|
||||
|
||||
func tailRMS(undo: Bool) throws -> Double {
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
// Engage overdub via the transport action so a pre-dub snapshot is captured.
|
||||
try scheduleAction(overdubStart) { pedal.toggleOverdub() }
|
||||
try scheduleAction(overdubStart + overdubDuration) { pedal.toggleOverdub() }
|
||||
if undo {
|
||||
try scheduleAction(overdubStart + overdubDuration) { pedal.undoOverdub() }
|
||||
}
|
||||
try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 }
|
||||
}
|
||||
let startIndex: Int = Int(measureStart * 44100.0) * 2
|
||||
guard startIndex < samples.count else { return 0 }
|
||||
return rms(Array(samples[startIndex...]))
|
||||
}
|
||||
|
||||
let dubbedRMS: Double = try tailRMS(undo: false)
|
||||
let undoneRMS: Double = try tailRMS(undo: true)
|
||||
#expect(undoneRMS < dubbedRMS,
|
||||
"Undo should remove the overdubbed layer's energy (undone \(undoneRMS) < dubbed \(dubbedRMS))")
|
||||
}
|
||||
|
||||
/// Builds an engine with the pedal added (so `effect()` allocates its buffer + recorders)
|
||||
/// but does NOT start it, so the beat-quantized callbacks can be driven deterministically.
|
||||
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
|
||||
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
let driver: NRTDriver = NRTDriver(outputURL: url, duration: 0.1)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
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: ToneSource = ToneSource(targetBus: srcBus.index)
|
||||
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
// Inject the tempo clock + engine the way PedalBoard.add would. `Pedal.clock` is weak
|
||||
// (owned by ShoeGaze in production), so the caller must keep the returned clock alive.
|
||||
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
|
||||
pedal.clock = clock
|
||||
pedal.hostEngine = engine
|
||||
pedal.sampleRate = sampleRate
|
||||
return (engine, clock, pedal)
|
||||
}
|
||||
|
||||
@Test func beatQuantizedTransportProgressesAndReportsWholeBeatLength() throws {
|
||||
let sampleRate: Double = 44100.0
|
||||
let bpm: Double = 120.0 // 22 050 frames per beat
|
||||
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
|
||||
try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate)
|
||||
// Keep the (weak-referenced) clock alive for the whole test.
|
||||
withExtendedLifetime(clock) {
|
||||
#expect(pedal.transportState == .empty)
|
||||
|
||||
// A record press with a clock present arms for the next beat, not immediately.
|
||||
pedal.toggleRecordStop()
|
||||
#expect(pedal.transportState == .armedRecord)
|
||||
|
||||
// Simulate the routine firing on the beat-1 boundary (0.5 s at 120 BPM).
|
||||
let startSample: SampleTime = SampleTime(sampleRate * 0.5)
|
||||
pedal.beginRecording(at: startSample)
|
||||
#expect(pedal.transportState == .recording)
|
||||
|
||||
// Stop press arms; simulate the close on the beat-5 boundary (2.5 s → a 4-beat loop).
|
||||
pedal.toggleRecordStop()
|
||||
#expect(pedal.transportState == .armedStop)
|
||||
let stopSample: SampleTime = SampleTime(sampleRate * 2.5)
|
||||
pedal.finishRecordingAndPlay(at: stopSample)
|
||||
|
||||
#expect(pedal.transportState == .playing)
|
||||
#expect(pedal.loopFrameCount == Int(stopSample - startSample))
|
||||
#expect(pedal.loopLengthBeats == 4.0, "2.0 s at 120 BPM is exactly 4 beats")
|
||||
|
||||
pedal.resetLoop()
|
||||
#expect(pedal.transportState == .empty)
|
||||
#expect(pedal.loopLengthBeats == 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func staleUndoRestoreIsDroppedWhenGenerationAdvances() throws {
|
||||
let sampleRate: Double = 44100.0
|
||||
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
|
||||
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
|
||||
withExtendedLifetime(clock) {
|
||||
// Get to a playing loop so a buffer + non-zero length exist.
|
||||
pedal.toggleRecordStop()
|
||||
pedal.beginRecording(at: SampleTime(sampleRate * 0.5))
|
||||
pedal.toggleRecordStop()
|
||||
pedal.finishRecordingAndPlay(at: SampleTime(sampleRate * 2.5))
|
||||
|
||||
// A snapshot armed under the current generation…
|
||||
let snapshot: [Double] = [Double](repeating: 0.5, count: 64)
|
||||
let staleGeneration: Int = pedal.transportGeneration
|
||||
|
||||
// …is superseded by a reset (which bumps the generation and clears the buffer).
|
||||
pedal.resetLoop()
|
||||
|
||||
// The deferred restore must now be a no-op: it must not reintroduce audio into the
|
||||
// buffer the user just cleared.
|
||||
pedal.applyUndoRestore(snapshot, generation: staleGeneration)
|
||||
#expect(pedal.transportState == .empty)
|
||||
#expect(pedal.loopFrameCount == 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func beatsForSpanRoundsToWholeBeats() throws {
|
||||
let sampleRate: Double = 48000.0
|
||||
let bpm: Double = 100.0 // 28 800 frames per beat
|
||||
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
|
||||
try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate)
|
||||
let framesPerBeat: Int = 28_800
|
||||
#expect(pedal.beatsForSpan(frames: framesPerBeat * 3, clock: clock) == 3.0)
|
||||
#expect(pedal.beatsForSpan(frames: framesPerBeat * 8, clock: clock) == 8.0)
|
||||
}
|
||||
|
||||
@Test func reverseKeepsLoopAudible() throws {
|
||||
let recordDuration: Double = 0.1
|
||||
let reverseAt: Double = 0.2
|
||||
let totalDuration: Double = 0.6
|
||||
|
||||
let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in
|
||||
pedal.toggleRecordStop()
|
||||
try scheduleAction(recordDuration) { pedal.toggleRecordStop() }
|
||||
try scheduleAction(reverseAt) { pedal.reverse = 1.0 }
|
||||
try scheduleAction(reverseAt) { source.amplitude = 0.0 }
|
||||
}
|
||||
|
||||
let tailStart: Int = Int(Double(samples.count) * 0.85)
|
||||
let tail: [Float] = Array(samples[tailStart...])
|
||||
#expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible")
|
||||
}
|
||||
}
|
||||
@@ -27,28 +27,28 @@ struct MIDIControllerCCTests {
|
||||
return (controller, sg, board, url)
|
||||
}
|
||||
|
||||
/// An address-only pedal-control CC target (hints filled at capture time).
|
||||
private func pedalControl(_ board: Int, _ pedal: Int, _ control: Int) -> MIDIMap.CCTarget {
|
||||
.pedalControl(boardIndex: board, pedalIndex: pedal, controlIndex: control,
|
||||
/// An address-only pedal-control CC target by pedal id (hints filled at capture time).
|
||||
private func pedalControl(_ pedalID: UUID, _ control: Int) -> MIDIMap.CCTarget {
|
||||
.pedalControl(pedalID: pedalID, controlIndex: control,
|
||||
pedalNameHint: nil, controlLabelHint: nil)
|
||||
}
|
||||
|
||||
@Test func learnCapturesBindingAndFiresCallback() throws {
|
||||
let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
|
||||
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
var mapChanged: Bool = false
|
||||
controller.onMapChanged = { mapChanged = true }
|
||||
|
||||
// Position is control 0 on a Volume pedal.
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
|
||||
|
||||
#expect(controller.learnTarget == nil, "learn should clear after capture")
|
||||
#expect(mapChanged, "onMapChanged should fire on capture")
|
||||
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(0, 0, 0))
|
||||
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(board.pedals[0].id, 0))
|
||||
#expect(binding?.controller == 20)
|
||||
if case .pedalControl(_, _, _, let nameHint, let labelHint)? = binding?.target {
|
||||
if case .pedalControl(_, _, let nameHint, let labelHint)? = binding?.target {
|
||||
#expect(nameHint == "Volume")
|
||||
#expect(labelHint == "Position")
|
||||
} else {
|
||||
@@ -64,7 +64,7 @@ struct MIDIControllerCCTests {
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
|
||||
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node // Position, 0...1
|
||||
@@ -86,7 +86,7 @@ struct MIDIControllerCCTests {
|
||||
Issue.record("board should have a master-gain node after finalize")
|
||||
return
|
||||
}
|
||||
let target: MIDIMap.CCTarget = .boardLevel(boardIndex: 0, boardLabelHint: nil)
|
||||
let target: MIDIMap.CCTarget = .boardLevel(boardID: board.id, boardLabelHint: nil)
|
||||
controller.armCCLearn(target)
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 0)) // learn
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 127))
|
||||
@@ -113,7 +113,7 @@ struct MIDIControllerCCTests {
|
||||
|
||||
let sliderIndex: Int = pedal.knobs.count // first control past the knobs is a slider
|
||||
let control: PedalControl = pedal.ccMappableControls[sliderIndex]
|
||||
controller.armCCLearn(pedalControl(0, 0, sliderIndex))
|
||||
controller.armCCLearn(pedalControl(pedal.id, sliderIndex))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 127))
|
||||
#expect(abs(control.node.value - control.range.upperBound) < 1e-9,
|
||||
@@ -126,10 +126,10 @@ struct MIDIControllerCCTests {
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
controller.setCCInverted(for: pedalControl(0, 0, 0), true)
|
||||
#expect(controller.isCCInverted(for: pedalControl(0, 0, 0)))
|
||||
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 0), true)
|
||||
#expect(controller.isCCInverted(for: pedalControl(board.pedals[0].id, 0)))
|
||||
|
||||
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
|
||||
@@ -147,15 +147,15 @@ struct MIDIControllerCCTests {
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// Control 0 = Position, control 1 = Mix on a Volume pedal.
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
controller.armCCLearn(pedalControl(0, 0, 1))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 1))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
controller.setCCInverted(for: pedalControl(0, 0, 1), true)
|
||||
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 1), true)
|
||||
|
||||
// Both bindings survive — the same CC drives both controls.
|
||||
#expect(sg.midiMap?.ccs.count == 2, "assigning a 2nd control must not steal the 1st")
|
||||
#expect(controller.ccBinding(for: pedalControl(0, 0, 0)) != nil)
|
||||
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) != nil)
|
||||
|
||||
let position: UIParamNode = board.pedals[0].ccMappableControls[0].node
|
||||
let mix: UIParamNode = board.pedals[0].ccMappableControls[1].node
|
||||
@@ -200,7 +200,7 @@ struct MIDIControllerCCTests {
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// Learn on channel 0 (the binding captures that channel).
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
|
||||
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
|
||||
@@ -212,15 +212,15 @@ struct MIDIControllerCCTests {
|
||||
}
|
||||
|
||||
@Test func clearRemovesBinding() throws {
|
||||
let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
|
||||
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
controller.armCCLearn(pedalControl(0, 0, 0))
|
||||
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
|
||||
#expect(sg.midiMap?.ccs.isEmpty == false)
|
||||
|
||||
controller.clearCCBinding(for: pedalControl(0, 0, 0))
|
||||
#expect(controller.ccBinding(for: pedalControl(0, 0, 0)) == nil)
|
||||
controller.clearCCBinding(for: pedalControl(board.pedals[0].id, 0))
|
||||
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) == nil)
|
||||
#expect(sg.midiMap?.ccs.isEmpty == true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ struct MIDIControllerPCTests {
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
let node: UIParamNode = boards[0].pedals[0].$bypass
|
||||
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0))
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
|
||||
#expect(node.value == 0.0)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5))
|
||||
@@ -101,7 +101,7 @@ struct MIDIControllerPCTests {
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.boardBypass(boardIndex: 0))
|
||||
controller.armSwitchLearn(.boardBypass(boardID: boards[0].id))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 3))
|
||||
#expect(sg.isBoardBypassed(boards[0]) == true)
|
||||
@@ -116,7 +116,7 @@ struct MIDIControllerPCTests {
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.boardSolo(boardIndex: 1))
|
||||
controller.armSwitchLearn(.boardSolo(boardID: boards[1].id))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2
|
||||
#expect(sg.activeBoardIndex == 1)
|
||||
@@ -162,11 +162,12 @@ struct MIDIControllerPCTests {
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// Bind to a pedal index that doesn't exist; applying it must be a safe no-op.
|
||||
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9))
|
||||
// Bind to a pedal id that doesn't exist in the rig; applying it must be a safe no-op.
|
||||
let ghostID: UUID = UUID()
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: ghostID))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash
|
||||
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != nil)
|
||||
#expect(controller.switchBinding(for: .pedalBypass(pedalID: ghostID)) != nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,12 +180,12 @@ struct MIDIControllerPCTests {
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.rigBypass)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 8))
|
||||
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0))
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC, kept
|
||||
|
||||
// Both bindings survive — one PC drives two actions.
|
||||
#expect(controller.switchBinding(for: .rigBypass)?.program == 8)
|
||||
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 0))?.program == 8)
|
||||
#expect(controller.switchBinding(for: .pedalBypass(pedalID: boards[0].pedals[0].id))?.program == 8)
|
||||
#expect(sg.midiMap?.switches.count == 2)
|
||||
|
||||
// Firing the PC toggles both at once.
|
||||
@@ -209,4 +210,60 @@ struct MIDIControllerPCTests {
|
||||
#expect(sg.midiMap?.switches.count == 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func tunerToggleFlipsEngagedState() throws {
|
||||
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.tunerToggle)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 10)) // learn only
|
||||
#expect(!sg.tunerEngaged)
|
||||
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 10))
|
||||
#expect(sg.tunerEngaged, "first press engages")
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 10))
|
||||
#expect(!sg.tunerEngaged, "second press disengages")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func tapTempoRegistersEachPress() throws {
|
||||
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.tapTempo)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 11)) // learn only
|
||||
#expect(sg.tapTimestamps.isEmpty)
|
||||
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 11))
|
||||
#expect(sg.tapTimestamps.count == 1, "first press registers a tap")
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 11))
|
||||
#expect(sg.tapTimestamps.count == 2, "second press registers a second tap")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func pedalActionDispatchesLooperRecordStop() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
let looper: LooperPedal = LooperPedal()
|
||||
try board.add(looper)
|
||||
try sg.finalizeBoard(board)
|
||||
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only
|
||||
#expect(looper.transportState == .empty)
|
||||
|
||||
// The looper was added via the board, so it carries the shared tempo clock and its
|
||||
// transport is beat-quantized: the mapped press arms recording for the next beat.
|
||||
// Asserting the arm proves the Program Change dispatched to the pedal's action.
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 12))
|
||||
#expect(looper.transportState == .armedRecord,
|
||||
"mapped Program Change should dispatch the looper record/stop action")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,25 +12,37 @@ import Foundation
|
||||
@Suite("MIDIMap persistence")
|
||||
struct MIDIMapCodableTests {
|
||||
|
||||
// Fixed ids so the round-trip comparison is deterministic.
|
||||
private static let boardID: UUID = UUID()
|
||||
private static let looperID: UUID = UUID()
|
||||
private static let volumeID: UUID = UUID()
|
||||
|
||||
private func sampleMap() -> MIDIMap {
|
||||
MIDIMap(
|
||||
switches: [
|
||||
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
|
||||
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"),
|
||||
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"),
|
||||
MIDIMap.SwitchBinding(program: 5, action: .tunerToggle),
|
||||
MIDIMap.SwitchBinding(program: 6, action: .tapTempo),
|
||||
MIDIMap.SwitchBinding(
|
||||
program: 7,
|
||||
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
|
||||
displayNameHint: "Looper"
|
||||
),
|
||||
],
|
||||
ccs: [
|
||||
MIDIMap.CCBinding(
|
||||
controller: 7,
|
||||
channel: 0,
|
||||
target: .pedalControl(
|
||||
boardIndex: 0, pedalIndex: 1, controlIndex: 0,
|
||||
pedalID: Self.volumeID, controlIndex: 0,
|
||||
pedalNameHint: "Volume", controlLabelHint: "Position"
|
||||
)
|
||||
),
|
||||
MIDIMap.CCBinding(
|
||||
controller: 11,
|
||||
channel: 0,
|
||||
target: .boardLevel(boardIndex: 0, boardLabelHint: "Board 1")
|
||||
target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1")
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// MIDIMapMigrationTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("Legacy MIDI map migration")
|
||||
struct MIDIMapMigrationTests {
|
||||
|
||||
/// Two boards; board 0 has two pedals, board 1 has one — with fixed ids to assert against.
|
||||
private func sampleBoards() -> [BoardState] {
|
||||
let od: PedalState = PedalState(type: "Overdrive", knobValues: [], bypass: 0)
|
||||
let rv: PedalState = PedalState(type: "Reverb", knobValues: [], bypass: 0)
|
||||
let dl: PedalState = PedalState(type: "Delay", knobValues: [], bypass: 0)
|
||||
return [
|
||||
BoardState(label: "Board 1", pedals: [od, rv]),
|
||||
BoardState(label: "Board 2", pedals: [dl]),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Unit: positional → id conversion
|
||||
|
||||
@Test func migratesPositionalBindingsToIds() {
|
||||
let boards: [BoardState] = sampleBoards()
|
||||
let legacy: LegacyMIDIMap = LegacyMIDIMap(
|
||||
switches: [
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .rigBypass, displayNameHint: nil),
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardBypass(boardIndex: 1), displayNameHint: "Board 2"),
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
|
||||
],
|
||||
ccs: [
|
||||
LegacyMIDIMap.LegacyCCBinding(controller: 7, channel: nil,
|
||||
target: .pedalControl(boardIndex: 0, pedalIndex: 0, controlIndex: 2, pedalNameHint: "Overdrive", controlLabelHint: "Level"),
|
||||
inverted: false),
|
||||
LegacyMIDIMap.LegacyCCBinding(controller: 11, channel: nil,
|
||||
target: .boardLevel(boardIndex: 1, boardLabelHint: "Board 2"), inverted: false),
|
||||
]
|
||||
)
|
||||
|
||||
let migrated: MIDIMap = legacy.migrated(boards: boards)
|
||||
|
||||
#expect(migrated.switches[0].action == .rigBypass)
|
||||
#expect(migrated.switches[1].action == .boardBypass(boardID: boards[1].id))
|
||||
#expect(migrated.switches[2].action == .pedalBypass(pedalID: boards[0].pedals[1].id))
|
||||
|
||||
#expect(migrated.ccs[0].target == .pedalControl(
|
||||
pedalID: boards[0].pedals[0].id, controlIndex: 2,
|
||||
pedalNameHint: "Overdrive", controlLabelHint: "Level"))
|
||||
#expect(migrated.ccs[1].target == .boardLevel(boardID: boards[1].id, boardLabelHint: "Board 2"))
|
||||
}
|
||||
|
||||
@Test func dropsOutOfRangeBindings() {
|
||||
let boards: [BoardState] = sampleBoards()
|
||||
let legacy: LegacyMIDIMap = LegacyMIDIMap(
|
||||
switches: [
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 9), displayNameHint: nil),
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardSolo(boardIndex: 5), displayNameHint: nil),
|
||||
],
|
||||
ccs: []
|
||||
)
|
||||
let migrated: MIDIMap = legacy.migrated(boards: boards)
|
||||
#expect(migrated.switches.isEmpty, "bindings addressing a non-existent board/pedal are dropped")
|
||||
}
|
||||
|
||||
// MARK: - Integration: legacy JSON decodes through ShoeGazeState
|
||||
|
||||
@Test func legacyFormatJSONDecodesAndMigrates() throws {
|
||||
let boards: [BoardState] = sampleBoards()
|
||||
let legacy: LegacyMIDIMap = LegacyMIDIMap(
|
||||
switches: [
|
||||
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: 0, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
|
||||
],
|
||||
ccs: []
|
||||
)
|
||||
|
||||
// Build the raw rig JSON with the *legacy* midiMap encoding spliced in — exactly what an
|
||||
// old saved rig on disk looks like (boards may or may not carry ids; midiMap is positional).
|
||||
var dict: [String: Any] = [
|
||||
"version": presetFormatVersion,
|
||||
"boards": try jsonObject(boards),
|
||||
"midiMap": try jsonObject(legacy),
|
||||
]
|
||||
// Sanity: the spliced midiMap is the positional shape, not the id shape.
|
||||
#expect(((dict["midiMap"] as? [String: Any])?["switches"] as? [Any])?.isEmpty == false)
|
||||
|
||||
let data: Data = try JSONSerialization.data(withJSONObject: dict)
|
||||
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
|
||||
|
||||
let map: MIDIMap = try #require(state.midiMap, "legacy midiMap should migrate, not drop to nil")
|
||||
#expect(map.switches.count == 1)
|
||||
// The board ids in `state.boards` are what migration used — assert the binding points at
|
||||
// the Reverb (board 0, pedal 1) by that board's decoded pedal id.
|
||||
#expect(map.switches[0].action == .pedalBypass(pedalID: state.boards[0].pedals[1].id))
|
||||
_ = dict.removeValue(forKey: "midiMap")
|
||||
}
|
||||
|
||||
/// Encodes a `Codable` value and re-reads it as a JSON object for splicing.
|
||||
private func jsonObject<T: Encodable>(_ value: T) throws -> Any {
|
||||
let data: Data = try JSONEncoder().encode(value)
|
||||
return try JSONSerialization.jsonObject(with: data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// MIDIMapReindexTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
/// MIDI bindings address pedals/boards by stable UUID, so they follow their target through
|
||||
/// structural edits with no reindexing. These tests assert the identity round-trips through the
|
||||
/// edit API's capture → rebuild, and that a binding resolves to (and only to) its pedal.
|
||||
@MainActor
|
||||
@Suite("MIDIMap identity")
|
||||
struct MIDIMapReindexTests {
|
||||
|
||||
private func makeRig(_ pedals: [String]) throws -> (ShoeGaze, MIDIController, URL, PedalBoard) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
for type: String in pedals {
|
||||
if let pedal: Pedal = PedalRegistry.makePedal(type: type) { try board.add(pedal) }
|
||||
}
|
||||
try sg.finalizeBoard(board)
|
||||
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
|
||||
return (sg, controller, url, board)
|
||||
}
|
||||
|
||||
// MARK: - Identity preservation across edits
|
||||
|
||||
@Test func pedalKeepsIdThroughInsertAndMove() throws {
|
||||
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
|
||||
try makeRig(["Overdrive", "Delay", "Reverb"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let reverbID: UUID = board.pedals[2].id
|
||||
|
||||
// Insert a Fuzz at the front → Reverb slides to index 3 but keeps its id.
|
||||
let afterInsert: PedalBoard = try sg.insertPedal(.fuzz, at: 0, to: board)
|
||||
#expect(afterInsert.pedals.count == 4)
|
||||
#expect(afterInsert.pedals[3].id == reverbID, "Reverb keeps its id after an insert before it")
|
||||
|
||||
// Move it to the front → still the same id.
|
||||
let afterMove: PedalBoard = try sg.movePedal(from: 3, to: 0, in: afterInsert)
|
||||
#expect(afterMove.pedals[0].id == reverbID, "Reverb keeps its id after a move")
|
||||
}
|
||||
|
||||
@Test func pedalIdSurvivesSaveLoadRoundTrip() throws {
|
||||
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
|
||||
try makeRig(["Overdrive", "Reverb"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ids: [UUID] = board.pedals.map { $0.id }
|
||||
|
||||
// Full Codable round-trip (what save/load to disk does).
|
||||
let data: Data = try JSONEncoder().encode(sg.captureState())
|
||||
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
|
||||
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url2) }
|
||||
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
|
||||
try sg2.loadRig(from: state)
|
||||
|
||||
#expect(sg2.boards.first?.pedals.map { $0.id } == ids, "pedal ids persist across save/load")
|
||||
}
|
||||
|
||||
@Test func boardKeepsIdThroughReorder() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let b0: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b0)
|
||||
let b1: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b1)
|
||||
let id0: UUID = b0.id
|
||||
let id1: UUID = b1.id
|
||||
|
||||
sg.moveBoard(b1, to: 0)
|
||||
#expect(sg.boards[0].id == id1)
|
||||
#expect(sg.boards[1].id == id0)
|
||||
}
|
||||
|
||||
// MARK: - Binding follows the pedal (end-to-end via the controller)
|
||||
|
||||
@Test func bypassBindingFollowsPedalAfterInsert() throws {
|
||||
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
|
||||
try makeRig(["Overdrive", "Reverb"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// Map program 5 to the Reverb's bypass (pedal index 1).
|
||||
let reverbID: UUID = board.pedals[1].id
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: reverbID))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
|
||||
|
||||
// Insert a Fuzz at the front — Reverb moves to index 2, keeps its id.
|
||||
let edited: PedalBoard = (try? sg.insertPedal(.fuzz, at: 0, to: board)) ?? board
|
||||
let reverb: Pedal = edited.pedals.first { $0.id == reverbID }!
|
||||
#expect(edited.pedals.firstIndex { $0.id == reverbID } == 2)
|
||||
|
||||
// Firing the binding must still toggle the Reverb (not whatever is at the old index).
|
||||
#expect(reverb.$bypass.value == 0.0)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5))
|
||||
#expect(abs(reverb.$bypass.value - 1.0) < 1e-9, "binding follows the pedal, not the index")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func bindingToRemovedPedalIsInert() throws {
|
||||
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
|
||||
try makeRig(["Overdrive", "Reverb"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
let overdriveID: UUID = board.pedals[0].id
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: overdriveID))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
|
||||
|
||||
// Remove the mapped Overdrive. Firing the binding must not crash or touch the Reverb.
|
||||
let edited: PedalBoard = (try? sg.removePedal(at: 0, from: board)) ?? board
|
||||
let reverbBypassBefore: Double = edited.pedals[0].$bypass.value
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5))
|
||||
#expect(edited.pedals[0].$bypass.value == reverbBypassBefore,
|
||||
"a binding to a removed pedal is inert — it must not fall through to another pedal")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func sameTypePedalsBindIndependently() throws {
|
||||
// The case the positional model got wrong: two identical-type pedals, each with its own
|
||||
// binding, resolve independently by id even after reordering.
|
||||
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
|
||||
try makeRig(["Delay", "Delay"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
let firstDelayID: UUID = board.pedals[0].id
|
||||
controller.armSwitchLearn(.pedalBypass(pedalID: firstDelayID))
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
|
||||
|
||||
// Swap the two Delays.
|
||||
let edited: PedalBoard = (try? sg.movePedal(from: 0, to: 1, in: board)) ?? board
|
||||
let firstDelay: Pedal = edited.pedals.first { $0.id == firstDelayID }!
|
||||
let otherDelay: Pedal = edited.pedals.first { $0.id != firstDelayID }!
|
||||
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 5))
|
||||
#expect(abs(firstDelay.$bypass.value - 1.0) < 1e-9, "binding drives the originally-mapped Delay")
|
||||
#expect(otherDelay.$bypass.value == 0.0, "the other same-type Delay is untouched")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,25 @@ import LyrebirdUI
|
||||
@Suite("RigStore")
|
||||
struct RigStoreTests {
|
||||
|
||||
/// Redirects `RigStore` to a unique temp file so the suite never touches — let alone
|
||||
/// overwrites or deletes — the running app's real autosave in Application Support. Returns
|
||||
/// the temp file URL (its parent directory is created).
|
||||
private func isolateAutosave() throws -> URL {
|
||||
let dir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("RigStoreTests-" + UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
let file: URL = dir.appendingPathComponent("autosave-rig.json")
|
||||
RigStore.autosaveURLOverride = file
|
||||
return file
|
||||
}
|
||||
|
||||
@Test func savesAndRestoresAcrossInstances() throws {
|
||||
let autosave: URL = try isolateAutosave()
|
||||
defer {
|
||||
RigStore.autosaveURLOverride = nil
|
||||
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
|
||||
}
|
||||
RigStore.clear()
|
||||
defer { RigStore.clear() }
|
||||
|
||||
// Build a rig and autosave it.
|
||||
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
@@ -42,7 +58,37 @@ struct RigStoreTests {
|
||||
#expect(b.boards.last?.label == "Clean")
|
||||
}
|
||||
|
||||
@Test func restorePreservesCurrentRigID() throws {
|
||||
let autosave: URL = try isolateAutosave()
|
||||
defer {
|
||||
RigStore.autosaveURLOverride = nil
|
||||
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
|
||||
}
|
||||
RigStore.clear()
|
||||
|
||||
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: urlA) }
|
||||
let a: ShoeGaze = ShoeGaze(engine: engineA)
|
||||
let board: PedalBoard = try a.addBoard()
|
||||
try a.appendPedal(.overdrive, to: board)
|
||||
try a.finalizeBoard(board)
|
||||
let rigID: UUID = UUID()
|
||||
a.currentRigID = rigID
|
||||
#expect(RigStore.save(a))
|
||||
|
||||
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: urlB) }
|
||||
let b: ShoeGaze = ShoeGaze(engine: engineB)
|
||||
#expect(RigStore.restore(into: b))
|
||||
#expect(b.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it")
|
||||
}
|
||||
|
||||
@Test func restoreReturnsFalseWhenNoAutosave() throws {
|
||||
let autosave: URL = try isolateAutosave()
|
||||
defer {
|
||||
RigStore.autosaveURLOverride = nil
|
||||
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
|
||||
}
|
||||
RigStore.clear()
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
@@ -84,21 +84,30 @@ func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] {
|
||||
&clientFormat
|
||||
) == noErr else { return [] }
|
||||
|
||||
let readFrames: UInt32 = 4096
|
||||
var samples: [Float] = [Float](repeating: 0, count: Int(readFrames) * 2)
|
||||
var framesRead: UInt32 = readFrames
|
||||
samples.withUnsafeMutableBufferPointer { ptr in
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
// Read the whole file in fixed-size chunks — a single `ExtAudioFileRead` call only
|
||||
// fills one chunk's worth of frames, so anything past `chunkFrames` would otherwise be
|
||||
// silently dropped for renders longer than one chunk.
|
||||
let chunkFrames: UInt32 = 4096
|
||||
var chunk: [Float] = [Float](repeating: 0, count: Int(chunkFrames) * 2)
|
||||
var allSamples: [Float] = []
|
||||
while true {
|
||||
var framesRead: UInt32 = chunkFrames
|
||||
chunk.withUnsafeMutableBufferPointer { ptr in
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: 2,
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
)
|
||||
)
|
||||
)
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
|
||||
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
|
||||
}
|
||||
guard framesRead > 0 else { break }
|
||||
allSamples.append(contentsOf: chunk.prefix(Int(framesRead) * 2))
|
||||
if framesRead < chunkFrames { break }
|
||||
}
|
||||
return Array(samples.prefix(Int(framesRead) * 2))
|
||||
return allSamples
|
||||
}
|
||||
|
||||
// MARK: - Signal analysis
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// TempoTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("ShoeGaze Tempo")
|
||||
struct TempoTests {
|
||||
|
||||
private func makeShoeGaze(duration: Double = 0.1) -> (ShoeGaze, URL) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
|
||||
return (shoeGaze, url)
|
||||
}
|
||||
|
||||
@Test func clockDefaultsToStandardTempo() throws {
|
||||
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
#expect(shoeGaze.clock.bpm == ShoeGaze.defaultTempoBpm)
|
||||
}
|
||||
|
||||
@Test func tapTempoAtOneSecondIntervalsSetsSixtyBpm() throws {
|
||||
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
// Simulate taps exactly 1s apart by manipulating the tap history directly —
|
||||
// real taps come from wall-clock `Date()`, so back-date synthetic timestamps
|
||||
// instead of sleeping the test for real seconds.
|
||||
let now: Date = Date()
|
||||
shoeGaze.tapTimestamps = [
|
||||
now.addingTimeInterval(-3.0),
|
||||
now.addingTimeInterval(-2.0),
|
||||
now.addingTimeInterval(-1.0),
|
||||
]
|
||||
shoeGaze.tapTempo() // landing "now", completing four 1s-spaced taps
|
||||
|
||||
#expect(abs(shoeGaze.clock.bpm - 60.0) < 0.5)
|
||||
}
|
||||
|
||||
@Test func singleTapDoesNotSetTempo() throws {
|
||||
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let startingBpm: Double = shoeGaze.clock.bpm
|
||||
shoeGaze.tapTempo()
|
||||
#expect(shoeGaze.clock.bpm == startingBpm, "A single tap has no interval to measure — tempo must not change")
|
||||
}
|
||||
|
||||
@Test func longPauseResetsTapHistory() throws {
|
||||
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let now: Date = Date()
|
||||
// Two taps 1s apart, then a long pause before the next tap.
|
||||
shoeGaze.tapTimestamps = [now.addingTimeInterval(-10.0), now.addingTimeInterval(-9.0)]
|
||||
shoeGaze.tapTempo()
|
||||
#expect(shoeGaze.tapTimestamps.count == 1, "A >2s gap should discard prior taps and start a fresh sequence")
|
||||
}
|
||||
|
||||
@Test func tapTempoRespectsBpmRangeViaClockPrecondition() throws {
|
||||
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let now: Date = Date()
|
||||
// Very fast taps (well under minTapInterval == 0.2s) are filtered out of the average.
|
||||
shoeGaze.tapTimestamps = [
|
||||
now.addingTimeInterval(-0.15),
|
||||
now.addingTimeInterval(-0.05),
|
||||
]
|
||||
let startingBpm: Double = shoeGaze.clock.bpm
|
||||
shoeGaze.tapTempo()
|
||||
// The sub-threshold interval is filtered; with no valid interval left the tempo
|
||||
// is left unchanged rather than jumping to an implausible value.
|
||||
#expect(shoeGaze.clock.bpm == startingBpm)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// TunerPitchReadingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGazeUI
|
||||
|
||||
@Suite("TunerPitchReading")
|
||||
struct TunerPitchReadingTests {
|
||||
|
||||
@Test func concertAIsA4WithZeroCents() {
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: 440.0)
|
||||
#expect(reading.noteName == "A4")
|
||||
#expect(abs(reading.cents) < 0.5)
|
||||
}
|
||||
|
||||
@Test func oneOctaveDownIsA3() {
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: 220.0)
|
||||
#expect(reading.noteName == "A3")
|
||||
#expect(abs(reading.cents) < 0.5)
|
||||
}
|
||||
|
||||
@Test func middleCIsC4() {
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: 261.6256)
|
||||
#expect(reading.noteName == "C4")
|
||||
#expect(abs(reading.cents) < 1.0)
|
||||
}
|
||||
|
||||
@Test func slightlySharpReportsPositiveCents() {
|
||||
// ~20 cents sharp of A4.
|
||||
let sharpHz: Double = 440.0 * pow(2.0, 20.0 / 1200.0)
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: sharpHz)
|
||||
#expect(reading.noteName == "A4")
|
||||
#expect(reading.cents > 15.0 && reading.cents < 25.0)
|
||||
}
|
||||
|
||||
@Test func slightlyFlatReportsNegativeCents() {
|
||||
// ~20 cents flat of A4.
|
||||
let flatHz: Double = 440.0 * pow(2.0, -20.0 / 1200.0)
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: flatHz)
|
||||
#expect(reading.noteName == "A4")
|
||||
#expect(reading.cents < -15.0 && reading.cents > -25.0)
|
||||
}
|
||||
|
||||
@Test func lowGuitarStringIsE2() {
|
||||
let reading: TunerPitchReading = TunerPitchReading(hz: 82.41)
|
||||
#expect(reading.noteName == "E2")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// TunerTapTests.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("TunerTap")
|
||||
struct TunerTapTests {
|
||||
|
||||
/// A constant-frequency sine source — same shape as `LooperPedalTests.ToneSource`.
|
||||
private final class ToneSource: SynthesizerBase {
|
||||
private let targetBus: Int
|
||||
private let toneFreq: Double
|
||||
private let amplitude: Double
|
||||
|
||||
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||
self.targetBus = targetBus
|
||||
self.toneFreq = freq
|
||||
self.amplitude = amplitude
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq, mul: amplitude))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func detectsKnownFrequencyWithinTolerance() throws {
|
||||
let toneFreq: Double = 220.0
|
||||
// The YIN tracker decimates 8×, so its 512-sample window needs ~4096 input samples
|
||||
// to fill plus several hops to converge — render generously.
|
||||
let renderDuration: Double = 2.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseControlBus(scratchControlBus)
|
||||
}
|
||||
|
||||
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
|
||||
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(tap, position: NodePosition.after(source))
|
||||
try engine.start()
|
||||
|
||||
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
|
||||
let detected: Double = capture.detectedFrequencyHz
|
||||
let tolerance: Double = 5.0
|
||||
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz, got \(detected) Hz")
|
||||
#expect(capture.detectedConfidence > 0.5, "A pure tone should track with high confidence")
|
||||
}
|
||||
|
||||
@Test func detectsLowGuitarEString() throws {
|
||||
// E2 ≈ 82.4 Hz — below the undecimated FreqTracker floor (~173 Hz), so this only
|
||||
// works because the tuner tap decimates before YIN analysis.
|
||||
let toneFreq: Double = 82.41
|
||||
let renderDuration: Double = 3.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseControlBus(scratchControlBus)
|
||||
}
|
||||
|
||||
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
|
||||
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(tap, position: NodePosition.after(source))
|
||||
try engine.start()
|
||||
|
||||
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
|
||||
let detected: Double = capture.detectedFrequencyHz
|
||||
let tolerance: Double = 3.0
|
||||
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz (low E), got \(detected) Hz")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// TunerTests.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("ShoeGaze Tuner")
|
||||
struct TunerTests {
|
||||
|
||||
private func makeShoeGaze(duration: Double) -> (ShoeGaze, SynthesisEngine, URL) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
|
||||
return (shoeGaze, engine, url)
|
||||
}
|
||||
|
||||
@Test func engageAddsTapAndDisengageRemovesIt() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.2)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
#expect(!shoeGaze.tunerEngaged)
|
||||
#expect(shoeGaze.currentPitchHz == nil)
|
||||
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.tunerEngaged)
|
||||
|
||||
try engine.start()
|
||||
#expect(shoeGaze.currentPitchHz != nil)
|
||||
|
||||
shoeGaze.disengageTuner()
|
||||
#expect(!shoeGaze.tunerEngaged)
|
||||
#expect(shoeGaze.currentPitchHz == nil)
|
||||
}
|
||||
|
||||
@Test func engagingWithMuteOnMutesRigAndDisengageRestores() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
_ = engine
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.tunerMutesRig = true
|
||||
#expect(!shoeGaze.rigMuted)
|
||||
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.rigMuted, "Engaging with tunerMutesRig=true should mute the rig")
|
||||
|
||||
shoeGaze.disengageTuner()
|
||||
#expect(!shoeGaze.rigMuted, "Disengaging should restore the pre-engage mute state")
|
||||
}
|
||||
|
||||
@Test func disengageRestoresPriorMutedStateNotAlwaysUnmuted() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
_ = engine
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.tunerMutesRig = true
|
||||
shoeGaze.setRigMuted(true) // already muted before engaging, for an unrelated reason
|
||||
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.rigMuted)
|
||||
|
||||
shoeGaze.disengageTuner()
|
||||
#expect(shoeGaze.rigMuted, "Rig was already muted before engaging — disengage must not unmute it")
|
||||
}
|
||||
|
||||
@Test func tunerMutesRigFalseDoesNotTouchRigMute() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
_ = engine
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.tunerMutesRig = false
|
||||
shoeGaze.engageTuner()
|
||||
#expect(!shoeGaze.rigMuted)
|
||||
|
||||
shoeGaze.disengageTuner()
|
||||
#expect(!shoeGaze.rigMuted)
|
||||
}
|
||||
|
||||
@Test func toggleTunerEngagedFlipsState() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
_ = engine
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.toggleTunerEngaged()
|
||||
#expect(shoeGaze.tunerEngaged)
|
||||
shoeGaze.toggleTunerEngaged()
|
||||
#expect(!shoeGaze.tunerEngaged)
|
||||
}
|
||||
|
||||
@Test func engageIsANoOpWhenAlreadyEngaged() throws {
|
||||
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
_ = engine
|
||||
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
shoeGaze.engageTuner()
|
||||
shoeGaze.tunerMutesRig = false // change after first engage — should have no effect until re-engage
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.rigMuted, "Second engageTuner() call while already engaged must be a no-op")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user