Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift
T
josh bdfbe04713 Looper: wide 3-column layout to fit tall pedal without scrolling
The looper stacked too many sections to fit the board canvas. Render it (only)
in a wide, three-column layout at widthUnits = 3:

- Left column: loop timeline, Free/Sync switch, Reset footswitch.
- Centre column: the four effect knobs (2×2) over a Level + Bypass footer, with
  the Mix slot reserved empty so Bypass stays horizontally centred like a normal
  pedal.
- Right column: transport footswitches in a 2×2 grid — Record / Reverse over
  Stop / Cue Stop (ordered by label).

Every other pedal keeps the default single-column section stack (extracted into
PedalView.defaultContent, no behaviour change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 13:05:57 -07:00

667 lines
32 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 to the looper.
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)
}
}
/// Posts a `TriggerEvent` at an exact sample-accurate time within a single NRT render, so a
/// test can flip 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, then renders and returns the stereo samples. No clock is injected, so
/// the looper transport is immediate (un-quantized).
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 engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let listener: TriggerListener = TriggerListener(engine: engine)
driver.triggerListener = listener
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index)
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
MainActor.assumeIsolated { action() }
}
}
try configure(engine, source, pedal, scheduleAction)
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
/// Builds an engine with the pedal added (so `effect()` allocates buffers + recorders) but
/// does NOT start it, so beat-quantized callbacks can be driven deterministically. The caller
/// keeps the returned (weak-referenced) engine + clock alive.
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))
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
pedal.clock = clock
pedal.hostEngine = engine
pedal.sampleRate = sampleRate
return (engine, clock, pedal)
}
// MARK: - Controls
@Test func exposesLooperControls() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#expect(pedal.effectSwitches.map { $0.label } == ["Sync to Tempo"])
#expect(pedal.effectButtons.isEmpty)
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse", "Reset"])
}
@Test func looperIsTripleWidth() throws {
#expect(LooperPedal().widthUnits == 3)
#expect(LooperPedal.trackCount == 4)
}
@Test func rebuildDoesNotDoubleTrackGenerators() throws {
// effect() runs from build(), which the engine re-invokes on every add — including the
// re-adds a board edit performs on the same instance. It must be idempotent (not append
// to the per-track arrays each time), or the looper's generators/state desync.
let pedal: LooperPedal = LooperPedal()
pedal.sampleRate = 44100.0
let dry: any ValidGeneratorInput = OscSin.Audio(freq: 100.0)
_ = pedal.effect(dry)
_ = pedal.effect(dry) // simulate a second build()
let counts: (buffers: Int, players: Int, overdub: Int, gates: Int) = pedal.trackGeneratorCountsForTesting
#expect(counts.buffers == LooperPedal.trackCount)
#expect(counts.players == LooperPedal.trackCount)
#expect(counts.overdub == LooperPedal.trackCount)
#expect(counts.gates == LooperPedal.trackCount)
#expect(pedal.transportState == .clear)
}
@Test func looperHidesMixControl() throws {
// The looper always passes the clean signal through and adds the loop on top, so the
// wet/dry Mix knob is hidden; a plain pedal keeps it.
#expect(LooperPedal().showsMixControl == false)
}
@Test func cleanSignalPassesThroughWhilePlaying() throws {
// With the loop muted (loopOn = 0) but a loop recorded and a live tone present, the
// output must still carry the clean signal at full level — it is never gated by the loop.
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, _, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() } // play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub
try scheduleAction(0.2) { pedal.loopOn = 0.0 } // mute the loop, keep live tone
}
let tailStart: Int = Int(Double(samples.count) * 0.9)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Clean signal must pass through even with the loop muted")
}
// MARK: - Audio behaviour (immediate / un-quantized)
@Test func clearStatePassesDryThrough() throws {
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(samples), "Cleared looper should pass the dry signal through")
}
@Test func recordCloseThenPlaysAfterInputSilenced() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.7) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record track A
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, keep playing
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.8)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Recorded loop should keep playing after the input is silenced")
}
@Test func resetReturnsToClearAndSilence() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(0.2) { pedal.resetLoop() }
try scheduleAction(0.2) { 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 loop content should remain")
}
@Test func playbackLevelAttenuatesLoop() throws {
let recordDuration: Double = 0.1
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.playbackLevel = playbackLevelDb
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { 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")
}
@Test func reverseKeepsLoopAudible() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.6) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(0.25) { pedal.reverse = 1.0 }
try scheduleAction(0.25) { 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")
}
@Test func overdubbingTrackAAddsEnergyToTheLoop() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.25
let overdubEnd: Double = 0.35
// Record silence into A, then overdub a tone onto A; the baked-in loop should be audible.
func renderWithOverdub(_ overdub: Bool) throws -> Double {
let samples: [Float] = try render(totalDuration: 0.7, toneAmplitude: 0.0) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record A (silent)
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, just play
if overdub {
try scheduleAction(overdubStart) { source.amplitude = 0.3 } // feed a tone
try scheduleAction(overdubStart) { pedal.pressLoop() } // overdub A on
try scheduleAction(overdubEnd) { pedal.pressLoop() } // overdub A off
}
try scheduleAction(overdubEnd) { source.amplitude = 0.0 } // silence input
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
return rms(Array(samples[tailStart...]))
}
let withoutOverdub: Double = try renderWithOverdub(false)
let withOverdub: Double = try renderWithOverdub(true)
#expect(withOverdub > withoutOverdub,
"Overdubbing a tone onto silent track A should bake audible content into the loop")
}
// MARK: - State machine (headless)
@Test func statesProgressFromClearToPlaying() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil // immediate transport
#expect(pedal.transportState == .clear)
#expect(pedal.loopButtonCaption == "Record")
pedal.pressLoop() // → recording A
#expect(pedal.transportState == .recordingMaster)
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop() // → playing + overdubbing A
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
#expect(pedal.loopButtonCaption == "Play") // next press ends overdub
pedal.pressLoop() // → playing, overdub off
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.trackHasContent(0))
#expect(pedal.loopButtonCaption == "Overdub") // A has content, next press overdubs
} }
}
@Test func masterLengthQuantizesToWholeBeats() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate) // 22 050 frames / beat
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop() // arm record (routine won't fire; engine idle)
pedal.beginMasterRecording(at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop() // arm close
pedal.closeMasterAndPlay(at: SampleTime(sampleRate * 2.5)) // 2.0 s = 4 beats
#expect(pedal.transportState == .playing)
#expect(pedal.loopFrameCount == Int(sampleRate * 2.0))
#expect(pedal.loopLengthBeats == 4.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.loopFrameCount == 0)
} }
}
@Test func onlyTrackASelectableWhileClear() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
#expect(pedal.selectedTrackIndex == 0)
pedal.selectTrack(2) // ignored while clear
#expect(pedal.selectedTrackIndex == 0)
} }
}
@Test func selectingTrackWhilePlayingEndsOverdubAndSwitches() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.selectTrack(1) // select B — ends A's overdub
#expect(pedal.selectedTrackIndex == 1)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(!pedal.trackHasContent(1))
#expect(pedal.loopButtonCaption == "Record") // empty B, next press records it
pedal.pressLoop() // overdub (record) B
#expect(pedal.overdubbingTrackIndex == 1)
#expect(pedal.trackHasContent(1))
} }
}
@Test func overdubBlockedWhileReversed() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
pedal.pressLoop() // end overdub, just playing
#expect(pedal.overdubbingTrackIndex == nil)
pedal.reverse = 1.0 // engage reverse
pedal.pressLoop() // must NOT start overdub while reversed
#expect(pedal.overdubbingTrackIndex == nil, "overdub can't be engaged while reversed")
pedal.reverse = 0.0 // forward again
pedal.pressLoop() // now overdub engages
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func engagingReverseWhileOverdubbingEndsOverdub() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.toggleReverse() // engage reverse mid-overdub
#expect(pedal.reverse == 1.0)
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse must end the overdub")
pedal.toggleReverse() // back to forward — overdub stays off
#expect(pedal.reverse == 0.0)
#expect(pedal.overdubbingTrackIndex == nil)
} }
}
@Test func reverseDoesNotJumpPlayHeadPosition() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Record a 1-second master (record start at 0, close at 44100) → masterLength = 44100.
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(0))
let closeSample: SampleTime = SampleTime(sampleRate)
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: closeSample)
#expect(pedal.transportState == .playing)
// A quarter of the way in, moving forward.
let quarter: SampleTime = closeSample + SampleTime(sampleRate * 0.25)
#expect(abs(pedal.playHeadFraction(at: quarter) - 0.25) < 0.001)
// Reversing here must NOT jump the read-out to the mirror point (0.75) — it stays at 0.25.
pedal.applyReverse(at: quarter)
#expect(abs(pedal.playHeadFraction(at: quarter) - 0.25) < 0.001,
"reverse must continue from the current position, not jump to duration − position")
// Advancing time now walks the position backward from 0.25.
let laterBy: SampleTime = SampleTime(sampleRate * 0.10)
#expect(abs(pedal.playHeadFraction(at: quarter + laterBy) - 0.15) < 0.001,
"reversed play head moves backward from the reverse point")
} }
}
@Test func reverseDefersToNextBeatInSyncMode() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(0))
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate))
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
// Sync mode (default): the press is deferred — direction and overdub are untouched.
pedal.toggleReverse()
#expect(pedal.reverse == 0.0, "sync-mode reverse waits for the next beat")
#expect(pedal.overdubbingTrackIndex == 0, "overdub survives until the deferred reverse fires")
// The beat arrives: direction flips and the overdub ends.
pedal.applyDeferredReverse(generation: pedal.reverseGeneration, at: SampleTime(sampleRate * 2))
#expect(pedal.reverse == 1.0)
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse ends the overdub")
} }
}
@Test func reverseIsImmediateInFreeMode() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.syncToBeat = 0.0
pedal.pressLoop() // record A (immediate)
pedal.pressLoop() // play + overdub A (immediate)
#expect(pedal.transportState == .playing)
// Free mode: reverse applies right away, even with a clock present.
pedal.toggleReverse()
#expect(pedal.reverse == 1.0, "free-mode reverse is immediate")
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse ends the overdub")
} }
}
@Test func engineStopResetsLooperAndPostsNotice() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.engineDidStop()
#expect(pedal.transportState == .clear, "engine stop returns the looper to clear")
#expect(pedal.loopFrameCount == 0)
#expect(pedal.stateDescription == "Looper reset — engine stopped.",
"a transient notice is shown after the engine-stop reset")
// A no-op when already clear (no spurious notice).
let clearPedal: LooperPedal = LooperPedal()
clearPedal.engineDidStop()
#expect(clearPedal.transportState == .clear)
} }
}
@Test func rigTeardownResetsLooper() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
pedal.rigWillTeardown()
#expect(pedal.transportState == .clear, "a rig teardown returns the looper to clear")
#expect(pedal.stateDescription == "Looper reset — rig changed.")
} }
}
@Test func recordsAgainAfterReset() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing + overdub A
pedal.toggleReverse() // leave reverse engaged before reset
#expect(pedal.reverse == 1.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.reverse == 0.0, "reset returns to forward playback")
// Second take must behave exactly like the first — including auto-overdub on A,
// which was silently blocked when reset didn't clear a left-on reverse.
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "record after reset should re-enter recording")
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0, "auto-overdub on A must engage after a reset")
#expect(pedal.trackHasContent(0))
} }
}
@Test func quantizedRecordsAgainAfterReset() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Mimic the real (beat-quantized) app path: pressLoop arms + starts a routine that
// fires applyQuantizedTransport with the generation captured at arm time.
// Session 1
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 2.5))
#expect(pedal.transportState == .playing)
// Reset, then session 2 — the quantized callbacks must still land.
pedal.resetLoop()
#expect(pedal.transportState == .clear)
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 4.5))
#expect(pedal.transportState == .recordingMaster, "quantized record after reset must reach recording")
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 6.5))
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func freeformModeRecordsImmediatelyDespiteClock() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Sync off: even with a clock present, transport is immediate — no armed/waiting state.
pedal.syncToBeat = 0.0
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "freeform record starts immediately")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.loopLengthBeats == 0.0, "freeform loops aren't beat-measured")
// Flip to Sync: the next take arms for the beat instead.
pedal.resetLoop()
pedal.syncToBeat = 1.0
pedal.pressLoop()
#expect(pedal.transportState == .armedRecord, "sync record arms for the next beat")
} }
}
@Test func tapTrackSelectsThenMutesRecordedTrack() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing, A selected + has content
pedal.pressLoop() // end auto-overdub, just playing
#expect(pedal.selectedTrackIndex == 0)
#expect(pedal.trackHasContent(0))
#expect(!pedal.isTrackMuted(0))
// Second tap on the selected, recorded track A mutes it; third un-mutes.
pedal.tapTrack(0)
#expect(pedal.isTrackMuted(0), "tapping the selected recorded track mutes it")
pedal.tapTrack(0)
#expect(!pedal.isTrackMuted(0), "tapping again un-mutes it")
// Tapping a different track selects it (doesn't mute), leaving A audible.
pedal.tapTrack(1)
#expect(pedal.selectedTrackIndex == 1)
#expect(!pedal.isTrackMuted(0))
#expect(!pedal.isTrackMuted(1))
pedal.resetLoop()
#expect(!pedal.isTrackMuted(0), "reset un-mutes all tracks")
} }
}
@Test func cycleSyncModeOscillatesThroughOptions() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.syncToBeat == 1.0) // Sync by default
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 0.0, "cycle → Free")
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 1.0, "cycle wraps back → Sync")
}
@Test func stopResumeAndCueStop() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.loopButtonCaption == "Play")
pedal.pressLoop() // resume
#expect(pedal.transportState == .playing)
#expect(pedal.isPlaying == 1.0)
// Cue Stop arms while playing (routine waits; engine idle so it never fires here).
#expect(!pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(!pedal.isStopAtLoopEndArmed)
} }
}
}