// RoutineTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth /// Mutable box for sharing results across `@Sendable` closures in tests. /// `@unchecked Sendable`: test closures access values sequentially (semaphore-gated). private final class Ref: @unchecked Sendable { var value: T init(_ value: T) { self.value = value } } @Suite("LyrebirdRoutine + LyrebirdTask") struct RoutineTests { func makeEngine() -> SynthesisEngine { makeTestEngine() } // MARK: - LyrebirdRoutine: body thread @Test func bodyRunsOnNonMainThread() { let engine: SynthesisEngine = makeEngine() let done: DispatchSemaphore = DispatchSemaphore(value: 0) let result: Ref = Ref(false) let routine: LyrebirdRoutine = LyrebirdRoutine { _ in result.value = !Thread.isMainThread done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) #expect(result.value) } @Test func stateTransitionsIdleRunningToStopped() { let engine: SynthesisEngine = makeEngine() let started: DispatchSemaphore = DispatchSemaphore(value: 0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in started.signal() try ctx.wait(seconds: 0.05) done.signal() } #expect(routine.state == .idle) routine.start(engine: engine) _ = started.wait(timeout: .now() + 2) #expect(routine.state == .running) _ = done.wait(timeout: .now() + 2) Thread.sleep(forTimeInterval: 0.02) #expect(routine.state == .stopped) } // MARK: - LyrebirdRoutine: stop @Test func stopCausesCleanExit() { let engine: SynthesisEngine = makeEngine() let inside: DispatchSemaphore = DispatchSemaphore(value: 0) let exitedCleanly: Ref = Ref(false) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in inside.signal() do { try ctx.wait(seconds: 10.0) } catch LyrebirdRoutineError.stopped { exitedCleanly.value = true throw LyrebirdRoutineError.stopped } } routine.start(engine: engine) _ = inside.wait(timeout: .now() + 2) routine.stop() routine.reset() #expect(exitedCleanly.value) } // MARK: - LyrebirdRoutine: reset allows restart @Test func resetAllowsRestart() { let engine: SynthesisEngine = makeEngine() let runCount: Ref = Ref(0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { _ in runCount.value += 1 done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) routine.reset() #expect(routine.state == .idle) routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) routine.reset() #expect(runCount.value == 2) } // MARK: - Multiple simultaneous routines @Test func multipleRoutinesRunIndependently() { let engine: SynthesisEngine = makeEngine() let group: DispatchGroup = DispatchGroup() let counts: [Ref] = (0..<3).map { _ in Ref(0) } for i: Int in 0..<3 { group.enter() let c: Ref = counts[i] let routine: LyrebirdRoutine = LyrebirdRoutine { _ in c.value += 1 group.leave() } routine.start(engine: engine) } _ = group.wait(timeout: .now() + 2) #expect(counts.map(\.value) == [1, 1, 1]) } // MARK: - waitUntil @Test func waitUntilStopsCleanlyOnStop() { let engine: SynthesisEngine = makeEngine() let inside: DispatchSemaphore = DispatchSemaphore(value: 0) let exitedCleanly: Ref = Ref(false) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in inside.signal() // engine.currentTime never advances (no processBlock) — loop forever until stop. do { try ctx.waitUntil(sampleTime: .max) } catch LyrebirdRoutineError.stopped { exitedCleanly.value = true throw LyrebirdRoutineError.stopped } } routine.start(engine: engine) _ = inside.wait(timeout: .now() + 2) Thread.sleep(forTimeInterval: 0.02) // let routine enter waitUntil loop routine.stop() routine.reset() #expect(exitedCleanly.value) } @Test func waitUntilBlocksUntilTargetSampleTime() throws { // engine.processBlock advances currentTime by blockSize each call. let engine: SynthesisEngine = makeTestEngine(blockSize: 512) try engine.start() let enteredWait: DispatchSemaphore = DispatchSemaphore(value: 0) let exited: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in enteredWait.signal() try ctx.waitUntil(sampleTime: 100) // one processBlock advances time to 512 > 100 exited.signal() } routine.start(engine: engine) _ = enteredWait.wait(timeout: .now() + 2) Thread.sleep(forTimeInterval: 0.03) // ensure routine is polling in waitUntil // currentTime == 0, so routine should still be waiting. #expect(routine.state == .running) // Advance engine time: one block = 512 samples > target 100. engine.processBlock(inputSamples: []) _ = exited.wait(timeout: .now() + 1) #expect(routine.state == .stopped) engine.stop() } // MARK: - Engine calls arrive on main thread @Test func engineAddArrivesOnMainThread() { let engine: SynthesisEngine = makeEngine() let buildCalled: DispatchSemaphore = DispatchSemaphore(value: 0) let calledOnMain: Ref = Ref(false) let probe: MainThreadProbeSynth = MainThreadProbeSynth { calledOnMain.value = Thread.isMainThread buildCalled.signal() } // ctx.add dispatches engine.add to DispatchQueue.main. // prepareAddEvent calls synth.build() on the dispatching thread (main). // probe is @unchecked Sendable — safe to capture in @Sendable closure let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.add(probe) } routine.start(engine: engine) _ = buildCalled.wait(timeout: .now() + 2) #expect(calledOnMain.value) } // MARK: - LyrebirdTask: pause / resume @Test func taskPauseAndResume() { let engine: SynthesisEngine = makeEngine() let reachedWait: DispatchSemaphore = DispatchSemaphore(value: 0) let completed: DispatchSemaphore = DispatchSemaphore(value: 0) let completedAfterResume: Ref = Ref(false) let task: LyrebirdTask = LyrebirdTask { ctx in reachedWait.signal() try ctx.wait(seconds: 1.0) completedAfterResume.value = true completed.signal() } task.start(engine: engine) _ = reachedWait.wait(timeout: .now() + 2) task.pause() #expect(task.state == .paused) Thread.sleep(forTimeInterval: 0.05) #expect(!completedAfterResume.value) task.resume() #expect(task.state == .running) _ = completed.wait(timeout: .now() + 3) #expect(completedAfterResume.value) } @Test func taskStopWhilePaused() { let engine: SynthesisEngine = makeEngine() let reachedWait: DispatchSemaphore = DispatchSemaphore(value: 0) let exitedCleanly: Ref = Ref(false) let task: LyrebirdTask = LyrebirdTask { ctx in reachedWait.signal() do { try ctx.wait(seconds: 10.0) } catch LyrebirdRoutineError.stopped { exitedCleanly.value = true throw LyrebirdRoutineError.stopped } } task.start(engine: engine) _ = reachedWait.wait(timeout: .now() + 2) task.pause() Thread.sleep(forTimeInterval: 0.02) task.stop() task.reset() #expect(exitedCleanly.value) } @Test func taskStateIsIdleBeforeStart() { let task: LyrebirdTask = LyrebirdTask { _ in } #expect(task.state == .idle) } // MARK: - schedule(afterBeats:) / remove(afterBeats:) @Test func scheduleAfterBeatsDispatchesToEngine() { let engine: SynthesisEngine = makeEngine() let built: DispatchSemaphore = DispatchSemaphore(value: 0) let probe: MainThreadProbeSynth = MainThreadProbeSynth { built.signal() } let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 120.0 ctx.schedule(probe, afterBeats: 0.0) } routine.start(engine: engine) let result: DispatchTimeoutResult = built.wait(timeout: .now() + 2) #expect(result == .success) // build() fired → schedule dispatch reached engine } @Test func removeAfterBeatsDispatchesToEngine() { let engine: SynthesisEngine = makeEngine() let dispatched: DispatchSemaphore = DispatchSemaphore(value: 0) let probe: MainThreadProbeSynth = MainThreadProbeSynth { } let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 120.0 ctx.remove(probe, afterBeats: 0.0) // Chain a second main-queue block: fires after remove's dispatch in queue order. DispatchQueue.main.async { dispatched.signal() } } routine.start(engine: engine) let result: DispatchTimeoutResult = dispatched.wait(timeout: .now() + 2) #expect(result == .success) // remove dispatch reached main queue } // MARK: - Tempo and beat timing // MARK: - ctx.now and ctx.currentBeat @Test func nowAdvancesAfterWait() { let engine: SynthesisEngine = makeEngine() let result: Ref = Ref(0.0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in try ctx.wait(seconds: 0.3) result.value = ctx.now done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) #expect(result.value > 0.27) #expect(result.value < 0.50) } @Test func currentBeatMatchesTempo() { // At 120 BPM, after 0.5 s, currentBeat ≈ 1.0 let engine: SynthesisEngine = makeEngine() let result: Ref = Ref(0.0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 120.0 try ctx.wait(seconds: 0.5) result.value = ctx.currentBeat done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) #expect(result.value > 0.85) #expect(result.value < 1.20) } @Test func currentBeatAccumulatesAcrossTempoChanges() { // 0.5 s at 60 BPM = 0.5 beats, then 0.5 s at 120 BPM = 1.0 beats → total ≈ 1.5 beats let engine: SynthesisEngine = makeEngine() let result: Ref = Ref(0.0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 60.0 try ctx.wait(seconds: 0.5) ctx.tempo = 120.0 try ctx.wait(seconds: 0.5) result.value = ctx.currentBeat done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 3) #expect(result.value > 1.2) #expect(result.value < 1.8) } @Test func driftCompensationKeepsSchedule() { // Each iteration: 80 ms work + wait(seconds: 0.2) should total ~0.2 s per step. // Without compensation: 5 iterations × (0.08 + 0.2) = ~1.4 s. // With compensation: 5 iterations × 0.2 s = ~1.0 s. let engine: SynthesisEngine = makeEngine() let done: DispatchSemaphore = DispatchSemaphore(value: 0) let elapsed: Ref = Ref(0.0) let iterationCount: Int = 5 let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in let t: TimeInterval = Date().timeIntervalSinceReferenceDate for _ in 0.. 0.9) #expect(elapsed.value < 1.25) } @Test func waitBeatsConvertsAtTempo() { // 1 beat at 120 BPM = 0.5 s let engine: SynthesisEngine = makeEngine() let done: DispatchSemaphore = DispatchSemaphore(value: 0) let elapsed: Ref = Ref(0.0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 120.0 let t: TimeInterval = Date().timeIntervalSinceReferenceDate try ctx.wait(beats: 1.0) elapsed.value = Date().timeIntervalSinceReferenceDate - t done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) // At 120 BPM, 1 beat = 0.5 s. Allow generous upper bound for Thread.sleep overshoot. #expect(elapsed.value > 0.45) #expect(elapsed.value < 0.80) } @Test func tempoCanChangeInBody() { // 1 beat at 60 BPM (1.0 s) + 1 beat at 120 BPM (0.5 s) = ~1.5 s let engine: SynthesisEngine = makeEngine() let done: DispatchSemaphore = DispatchSemaphore(value: 0) let elapsed: Ref = Ref(0.0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in let t: TimeInterval = Date().timeIntervalSinceReferenceDate ctx.tempo = 60.0 try ctx.wait(beats: 1.0) ctx.tempo = 120.0 try ctx.wait(beats: 1.0) elapsed.value = Date().timeIntervalSinceReferenceDate - t done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 4) // Total ~1.5 s. Allow generous upper bound for Thread.sleep overshoot. #expect(elapsed.value > 1.3) #expect(elapsed.value < 2.1) } // MARK: - Sample-accurate elapsed clock @Test func elapsedSamplesAdvancesWithEngineProcessBlocks() throws { // engine.processBlock advances currentTime by blockSize each call. let engine: SynthesisEngine = makeTestEngine(blockSize: 512) try engine.start() // Process 4 blocks before starting routine. Routine reads elapsedSamples once. for _ in 0..<4 { engine.processBlock(inputSamples: []) } let result: Ref = Ref(-1) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in result.value = ctx.elapsedSamples done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) // Routine started after 4 blocks → elapsedSamples is 0 (anchored at start, not block 0). // Process more blocks would advance — but body already read. #expect(result.value == 0) engine.stop() } @Test func elapsedSamplesAdvancesAfterRoutineStartsBeforeBlocks() throws { // Start routine before any blocks have been processed; then process blocks; routine // reads elapsedSamples after waitUntil returns. let engine: SynthesisEngine = makeTestEngine(blockSize: 512) try engine.start() let result: Ref = Ref(-1) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in try ctx.waitUntil(sampleTime: 512 * 4) result.value = ctx.elapsedSamples done.signal() } routine.start(engine: engine) Thread.sleep(forTimeInterval: 0.02) // let routine reach waitUntil for _ in 0..<5 { engine.processBlock(inputSamples: []) } _ = done.wait(timeout: .now() + 2) #expect(result.value >= 512 * 4) engine.stop() } @Test func elapsedSecondsMatchesElapsedSamples() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 512) try engine.start() let result: Ref<(SampleTime, Double)> = Ref<(SampleTime, Double)>((0, 0.0)) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in try ctx.waitUntil(sampleTime: 512 * 2) result.value = (ctx.elapsedSamples, ctx.elapsedSeconds) done.signal() } routine.start(engine: engine) Thread.sleep(forTimeInterval: 0.02) for _ in 0..<3 { engine.processBlock(inputSamples: []) } _ = done.wait(timeout: .now() + 2) let expectedSeconds: Double = Double(result.value.0) / engine.sampleRate #expect(abs(expectedSeconds - result.value.1) < 1e-9) engine.stop() } @Test func elapsedBeatsTracksTempo() throws { // At 120 BPM, after ≈1.0 s of engine time, elapsedBeats ≈ 2.0. let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100) try engine.start() let result: Ref = Ref(0.0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let targetSamples: SampleTime = 44100 let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 120.0 try ctx.waitUntil(sampleTime: targetSamples) result.value = ctx.elapsedBeats done.signal() } routine.start(engine: engine) Thread.sleep(forTimeInterval: 0.02) // 100 blocks @ 512 samples = 51200 samples ≈ 1.16 s — past target. for _ in 0..<100 { engine.processBlock(inputSamples: []) } _ = done.wait(timeout: .now() + 2) // 1 s at 120 BPM = 2 beats. Allow overshoot from poll granularity. #expect(result.value >= 2.0) #expect(result.value < 3.0) engine.stop() } @Test func elapsedBeatsAccumulatesAcrossTempoChanges() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 512, sampleRate: 44100) try engine.start() let result: Ref = Ref(0.0) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let firstTarget: SampleTime = 44100 / 4 // 0.25 s let secondTarget: SampleTime = 44100 / 2 // 0.50 s let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in ctx.tempo = 60.0 try ctx.waitUntil(sampleTime: firstTarget) ctx.tempo = 240.0 try ctx.waitUntil(sampleTime: secondTarget) result.value = ctx.elapsedBeats done.signal() } routine.start(engine: engine) Thread.sleep(forTimeInterval: 0.02) // Process blocks gradually so routine sees the first target before the second. for _ in 0..<60 { engine.processBlock(inputSamples: []) Thread.sleep(forTimeInterval: 0.002) } _ = done.wait(timeout: .now() + 3) // 0.25 s at 60 BPM = 0.25 beats; 0.25 s at 240 BPM = 1.0 beats. Total ≈ 1.25. #expect(result.value > 1.1) #expect(result.value < 1.6) engine.stop() } // MARK: - Engine elapsed clock @Test func engineElapsedSamplesAnchoredToStart() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 512) // Before start: 0. #expect(engine.elapsedSamples == 0) try engine.start() engine.processBlock(inputSamples: []) engine.processBlock(inputSamples: []) #expect(engine.elapsedSamples == 1024) #expect(abs(engine.elapsedSeconds - 1024.0 / engine.sampleRate) < 1e-9) engine.stop() } @Test func contextEngineSamplesPassesThroughToEngine() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 512) try engine.start() engine.processBlock(inputSamples: []) let result: Ref<(SampleTime, Double)> = Ref<(SampleTime, Double)>((-1, -1)) let done: DispatchSemaphore = DispatchSemaphore(value: 0) let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in result.value = (ctx.engineSamples, ctx.engineNow) done.signal() } routine.start(engine: engine) _ = done.wait(timeout: .now() + 2) #expect(result.value.0 == engine.elapsedSamples) #expect(result.value.1 == engine.elapsedSeconds) engine.stop() } @Test func taskStateIsPausedWhileSuspended() { let engine: SynthesisEngine = makeEngine() let reachedWait: DispatchSemaphore = DispatchSemaphore(value: 0) let task: LyrebirdTask = LyrebirdTask { ctx in reachedWait.signal() try ctx.wait(seconds: 5.0) } task.start(engine: engine) _ = reachedWait.wait(timeout: .now() + 2) task.pause() Thread.sleep(forTimeInterval: 0.02) #expect(task.state == .paused) task.stop() task.reset() } } // MARK: - Test fixture private final class MainThreadProbeSynth: Synthesizer, @unchecked Sendable { private let _onBuild: @Sendable () -> Void init(onBuild: @escaping @Sendable () -> Void) { _onBuild = onBuild } func build() { _onBuild() } } // MARK: - Demo idiom regression tests // // Regression coverage for a bug found in the LyrebirdDemo BufferDemos CLI: // ctx.add / ctx.remove / ctx.schedule from a LyrebirdTask body dispatch to // DispatchQueue.main (single-producer SPSC contract on the engine pendingQueue). // If any change breaks the dispatch-to-main chain, no synthesizer ever has // build() called and the demo runs silently. @Suite("LyrebirdTask demo idiom — ctx.add/remove dispatch") struct LyrebirdTaskDemoIdiomTests { func makeEngine() -> SynthesisEngine { makeTestEngine() } /// Mirrors the BufferDemos CLI pattern: a single LyrebirdTask body issues /// multiple ctx.add / ctx.remove pairs separated by ctx.wait. Each ctx.add /// must result in synth.build() being invoked (on the main thread). @Test func multipleAddRemoveCyclesAllTriggerBuild() { let engine: SynthesisEngine = makeEngine() let buildCount: Ref = Ref(0) let buildLock: NSLock = NSLock() let allDone: DispatchSemaphore = DispatchSemaphore(value: 0) let synthCount: Int = 5 let synths: [MainThreadProbeSynth] = (0.. = Ref(0) let lock: NSLock = NSLock() let synthCount: Int = 3 let synths: [MainThreadProbeSynth] = (0..