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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user