Files
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

799 lines
30 KiB
Swift
Raw Permalink 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.
// 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<T>: @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<Bool> = 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<Bool> = 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<Int> = 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<Int>] = (0..<3).map { _ in Ref(0) }
for i: Int in 0..<3 {
group.enter()
let c: Ref<Int> = 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<Bool> = 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<Bool> = 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<Bool> = 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<Bool> = 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<Double> = 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<Double> = 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<Double> = 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<Double> = Ref(0.0)
let iterationCount: Int = 5
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
let t: TimeInterval = Date().timeIntervalSinceReferenceDate
for _ in 0..<iterationCount {
Thread.sleep(forTimeInterval: 0.08) // simulate work
try ctx.wait(seconds: 0.2)
}
elapsed.value = Date().timeIntervalSinceReferenceDate - t
done.signal()
}
routine.start(engine: engine)
_ = done.wait(timeout: .now() + 5)
// Total schedule: 5 × 0.2 = 1.0 s. Allow some overshoot for Thread.sleep imprecision.
#expect(elapsed.value > 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<Double> = 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<Double> = 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<SampleTime> = Ref<SampleTime>(-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<SampleTime> = Ref<SampleTime>(-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<Double> = 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<Double> = 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<Int> = Ref(0)
let buildLock: NSLock = NSLock()
let allDone: DispatchSemaphore = DispatchSemaphore(value: 0)
let synthCount: Int = 5
let synths: [MainThreadProbeSynth] = (0..<synthCount).map { _ in
MainThreadProbeSynth {
buildLock.lock()
buildCount.value += 1
buildLock.unlock()
}
}
let task: LyrebirdTask = LyrebirdTask { ctx in
for synth: MainThreadProbeSynth in synths {
ctx.add(synth)
try ctx.wait(seconds: 0.02)
ctx.remove(synth)
try ctx.wait(seconds: 0.01)
}
allDone.signal()
}
task.start(engine: engine)
_ = allDone.wait(timeout: .now() + 5)
// Drain any still-pending main-async dispatches before asserting.
let drain: DispatchSemaphore = DispatchSemaphore(value: 0)
DispatchQueue.main.async { drain.signal() }
_ = drain.wait(timeout: .now() + 1)
buildLock.lock()
let final: Int = buildCount.value
buildLock.unlock()
#expect(final == synthCount,
"Every ctx.add must dispatch and trigger build(); got \(final) of \(synthCount)")
}
/// ctx.remove dispatches to DispatchQueue.main and reaches engine.remove.
/// Verifies the remove path is symmetric with add.
@Test func ctxRemoveDispatchesToEngine() {
let engine: SynthesisEngine = makeEngine()
let buildCalled: DispatchSemaphore = DispatchSemaphore(value: 0)
let probe: MainThreadProbeSynth = MainThreadProbeSynth { buildCalled.signal() }
let bodyDone: DispatchSemaphore = DispatchSemaphore(value: 0)
let task: LyrebirdTask = LyrebirdTask { ctx in
ctx.add(probe)
try ctx.wait(seconds: 0.05)
ctx.remove(probe)
try ctx.wait(seconds: 0.02)
bodyDone.signal()
}
task.start(engine: engine)
// Build must fire (add reached engine).
let buildResult: DispatchTimeoutResult = buildCalled.wait(timeout: .now() + 2)
#expect(buildResult == .success)
// Body completes (remove dispatch did not stall the task).
let doneResult: DispatchTimeoutResult = bodyDone.wait(timeout: .now() + 2)
#expect(doneResult == .success)
}
/// ctx.schedule(_:after:) inside a task body dispatches to engine.
/// Note: schedule is the underlying primitive for both schedule(at:) and
/// schedule(afterBeats:); this is the minimal CLI-style coverage.
@Test func ctxScheduleDispatchesToEngine() {
let engine: SynthesisEngine = makeEngine()
let buildCalled: DispatchSemaphore = DispatchSemaphore(value: 0)
let probe: MainThreadProbeSynth = MainThreadProbeSynth { buildCalled.signal() }
let task: LyrebirdTask = LyrebirdTask { ctx in
ctx.schedule(probe, after: 0.0)
}
task.start(engine: engine)
let result: DispatchTimeoutResult = buildCalled.wait(timeout: .now() + 2)
#expect(result == .success,
"ctx.schedule must dispatch to main and trigger build()")
}
/// `LyrebirdTask.run(engine:body:)` convenience: blocks until body completes
/// and dispatched main-async work has all run. Mirrors the CLI / scripting
/// idiom intended for BufferDemos and similar.
@Test func runConvenienceBlocksUntilBodyCompletes() {
let engine: SynthesisEngine = makeEngine()
let buildCount: Ref<Int> = Ref(0)
let lock: NSLock = NSLock()
let synthCount: Int = 3
let synths: [MainThreadProbeSynth] = (0..<synthCount).map { _ in
MainThreadProbeSynth {
lock.lock()
buildCount.value += 1
lock.unlock()
}
}
let task: LyrebirdTask = LyrebirdTask.run(engine: engine) { ctx in
for synth: MainThreadProbeSynth in synths {
ctx.add(synth)
try ctx.wait(seconds: 0.02)
ctx.remove(synth)
try ctx.wait(seconds: 0.01)
}
}
// Drain any final dispatched main-async blocks scheduled just before
// body return (build() is invoked from within engine.add on the main
// queue; the very last add may still be in flight when run() returns).
let drain: DispatchSemaphore = DispatchSemaphore(value: 0)
DispatchQueue.main.async { drain.signal() }
_ = drain.wait(timeout: .now() + 1)
lock.lock()
let final: Int = buildCount.value
lock.unlock()
#expect(final == synthCount,
"LyrebirdTask.run must let all dispatched build() calls complete; got \(final) of \(synthCount)")
#expect(task.state == .stopped,
"Task must be in .stopped state after run() returns; got \(task.state)")
}
/// `task.waitUntilComplete()` returns immediately when called after the task
/// has already terminated (idempotent / fast-path branch).
@Test func waitUntilCompleteFastPathOnTerminalState() {
let engine: SynthesisEngine = makeEngine()
let bodyDone: DispatchSemaphore = DispatchSemaphore(value: 0)
let task: LyrebirdTask = LyrebirdTask { _ in
bodyDone.signal()
}
task.start(engine: engine)
_ = bodyDone.wait(timeout: .now() + 2)
// Give the thread a moment to flip threadActive false.
Thread.sleep(forTimeInterval: 0.05)
let start: Date = Date()
task.waitUntilComplete()
let elapsed: TimeInterval = Date().timeIntervalSince(start)
#expect(elapsed < 0.1,
"waitUntilComplete must return immediately on terminal state; took \(elapsed)s")
}
/// `ctx.set(_:to:)` writes a live-parameter node from the routine body (its own thread) with no
/// main-thread dispatch — the value is readable immediately after via the node's atomic.
@Test func ctxSetWritesLiveParameter() {
let engine: SynthesisEngine = makeEngine()
let param: ParameterNode = ParameterNode(1.0) // Sendable — captured in the @Sendable body
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
ctx.set(param, to: 7.5)
done.signal()
}
routine.start(engine: engine)
_ = done.wait(timeout: .now() + 2)
#expect(abs(param.value - 7.5) < 1e-9,
"ctx.set must store the value in the parameter node's atomic")
}
/// `ctx.ramp(_:to:seconds:)` blocks for the duration and lands exactly on the target.
@Test func ctxRampLandsOnTarget() {
let engine: SynthesisEngine = makeEngine()
let param: ParameterNode = ParameterNode(1.0)
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
try? ctx.ramp(param, to: 5.0, seconds: 0.05)
done.signal()
}
routine.start(engine: engine)
_ = done.wait(timeout: .now() + 2)
#expect(abs(param.value - 5.0) < 1e-9, "ramp must finish exactly on the target value")
}
/// A non-positive duration jumps straight to the target (no stepping).
@Test func ctxRampZeroDurationJumps() {
let engine: SynthesisEngine = makeEngine()
let param: ParameterNode = ParameterNode(2.0)
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in
try? ctx.ramp(param, to: 9.0, seconds: 0.0)
done.signal()
}
routine.start(engine: engine)
_ = done.wait(timeout: .now() + 2)
#expect(abs(param.value - 9.0) < 1e-9)
}
}