Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift
T
josh 465e3e6dfd Looper: multi-slot + timeline + stop/cue-stop, quantized transport
Checkpoint before the multitrack redesign. Adds 4 loop slots (one player
swapped via setBuffer), a play-head timeline with A/B/C/D dots, Loop/Stop/
Cue Stop/Reverse stomp toggles below the knobs, beat-quantized transport,
overdub undo, reverse, and feedback-decay overdub — all reviewed for RT
safety (transportGeneration guards on deferred beat/undo/cue callbacks).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:14:46 -07:00

603 lines
28 KiB
Swift

// 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)
// Transport row: Loop / Stop / Cue Stop / Reverse, with the two toggles flanking the stops.
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse"])
#expect(pedal.effectTransportButtons.filter { $0.style == .toggle }.map { $0.label } == ["Loop", "Reverse"])
#expect(pedal.effectButtons.map { $0.label } ==
["Record / Stop", "Overdub", "Undo", "Slot", "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 slotsHoldIndependentLoopsAndSwitch() throws {
let sampleRate: Double = 44100.0
var captured: LooperPedal?
let samples: [Float] = try render(totalDuration: 1.0, sampleRate: sampleRate) { engine, source, pedal, scheduleAction in
captured = pedal
pedal.hostEngine = engine // enable the player buffer swap
pedal.toggleRecordStop() // record slot A (default)
try scheduleAction(0.1) { pedal.toggleRecordStop() } // close A → playing
try scheduleAction(0.12) { source.amplitude = 0.0 } // silence live input
try scheduleAction(0.3) { pedal.selectSlot(1) } // switch to empty slot B
try scheduleAction(0.6) { pedal.selectSlot(0) } // switch back to A
}
let stride: Int = 2
// While parked on empty slot B (input silenced), output should be silent.
let bStart: Int = Int(0.45 * sampleRate) * stride
let bEnd: Int = Int(0.58 * sampleRate) * stride
let onEmptyB: [Float] = Array(samples[bStart ..< min(bEnd, samples.count)])
#expect(!hasNonSilentOutput(onEmptyB), "Empty slot B with silenced input should be silent")
// After switching back to A, its recorded loop should be audible again.
let aStart: Int = Int(0.85 * sampleRate) * stride
let backOnA: [Float] = Array(samples[aStart...])
#expect(hasNonSilentOutput(backOnA), "Switching back to slot A should replay its loop")
let pedal: LooperPedal = try #require(captured)
#expect(pedal.activeSlotIndex == 0)
#expect(pedal.slotHasContent(0))
#expect(!pedal.slotHasContent(1))
}
@Test func cycleSlotWrapsThroughAllSlots() throws {
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(clock) {
#expect(pedal.activeSlotIndex == 0)
for expected: Int in [1, 2, 3, 0] {
pedal.cycleSlot()
#expect(pedal.activeSlotIndex == expected)
}
}
}
@Test func stopPlaybackHaltsAndRecordStopResumes() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil // immediate (un-quantized) transport
pedal.toggleRecordStop() // recording
pedal.toggleRecordStop() // close → playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.playbackPosition01() == nil)
pedal.toggleRecordStop() // Record / Stop resumes from a stopped loop
#expect(pedal.transportState == .playing)
#expect(pedal.isPlaying == 1.0)
} }
}
@Test func stopAtLoopEndArmsAndCancels() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Reach a playing loop through the quantized path.
pedal.toggleRecordStop()
pedal.beginRecording(at: SampleTime(sampleRate * 0.5))
pedal.toggleRecordStop()
pedal.finishRecordingAndPlay(at: SampleTime(sampleRate * 2.5))
#expect(pedal.transportState == .playing)
#expect(!pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed, "first press arms the end-stop")
pedal.toggleStopAtLoopEnd()
#expect(!pedal.isStopAtLoopEndArmed, "second press disarms it")
// An immediate Stop while armed cancels the pending end-stop.
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(!pedal.isStopAtLoopEndArmed)
} }
}
@Test func selectSlotIsNoOpWhileRecording() throws {
let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(clock) {
// Drop the clock so transport is immediate (un-quantized): a record press lands
// directly in `.recording` rather than arming for the next beat.
pedal.clock = nil
pedal.toggleRecordStop()
#expect(pedal.transportState == .recording)
// Switching slots must be ignored mid-record — no active-slot change, no phase change.
pedal.selectSlot(1)
#expect(pedal.activeSlotIndex == 0)
#expect(pedal.transportState == .recording)
}
}
@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, slot: pedal.activeSlotIndex, 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")
}
}