v2.4.0 release: event patterns + live event conductor

This commit is contained in:
2026-12-03 08:45:07 -08:00
parent a175c437de
commit 6da3615707
40 changed files with 4223 additions and 19 deletions
@@ -0,0 +1,496 @@
// EventConductorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Shared fixture
/// A fresh voice per event, counting `build()` calls so a test can observe when (and whether) the
/// conductor has started a pattern.
private final class CondVoice: SynthesizerBase {
@LiveParam var freq: Double = 0.0
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
override func build() {
CondVoice.buildCount.wrappingAdd(1, ordering: .releasing)
output(bus: 0, source: $freq)
}
}
/// Builds a two-event finite pattern at `tempo`.
@MainActor private func makeFinitePattern(tempo: Double) -> EventPattern<CondVoice> {
EventPattern(make: { CondVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(tempo)
}
/// Builds a never-ending fast pattern at `tempo` — its build counter keeps climbing until stopped,
/// so a test can detect a child the conductor failed to halt.
@MainActor private func makeInfinitePattern(tempo: Double) -> EventPattern<CondVoice> {
EventPattern(make: { CondVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.05]))
.tempo(tempo)
}
// MARK: - Conductor playback
/// `EventConductor` live, clock-driven playback. Serialized because the fixture shares a static
/// build counter.
@Suite("EventConductor", .serialized)
struct EventConductorTests {
@Test func quantiseDelaysEntryThenPlays() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// afterBeats(2) at 120 BPM = a 1.0 s lead-in before the first voice is built.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
c.add(makeFinitePattern(tempo: 120.0), quantize: .afterBeats(2.0))
return c
}
// Well inside the lead-in: nothing built yet, but the conductor clock is running.
try? await Task.sleep(for: .milliseconds(300))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
#expect(conductor.isRunning)
// After the boundary the pattern runs to completion: both events fire.
let deadline: Date = Date().addingTimeInterval(2.0)
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
conductor.stop()
}
@Test func nextMultipleEntersOnGrid() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// nextMultiple(ofBeats: 2) at 120 BPM: the next bar line is at beat 2 = 1.0 s out.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
c.add(makeFinitePattern(tempo: 120.0), quantize: .nextMultiple(ofBeats: 2.0))
return c
}
try? await Task.sleep(for: .milliseconds(300))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
let deadline: Date = Date().addingTimeInterval(2.5)
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
conductor.stop()
}
@Test func liveAddAfterStartPlaysAndIdles() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// Start the conductor empty, as a running engine would sit waiting for input. The pattern
// is built on the main actor (its `\.freq` key path is main-actor-isolated) but not yet
// handed over; the conductor supplies the engine later.
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
let p: EventPattern<CondVoice> = EventPattern(make: { CondVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
return (c, p)
}
// Add it AFTER start, from off the main thread — standing in for a UI / OSC / MIDI callback.
conductor.add(pattern, quantize: .nextBeat)
// waitUntilIdle (off main here) blocks until the pattern has entered and finished.
conductor.waitUntilIdle()
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 3)
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func addBeforeStartIsServicedAfterStart() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// Queue a pattern, THEN start — the conductor must service the pre-start inbox on its first
// poll relative to beat 0.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.add(makeFinitePattern(tempo: 240.0), quantize: .now) // before start
c.start(on: engine)
return c
}
conductor.waitUntilIdle()
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func multipleAddsInOnePollAllPlay() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// Three finite patterns added before the first poll — all must enter and finish.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
c.add(makeFinitePattern(tempo: 240.0), quantize: .now)
c.start(on: engine)
return c
}
conductor.waitUntilIdle()
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 6) // 3 patterns × 2 events
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func polytempoEntryAlignsToConductorClock() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// Conductor at 120, pattern at 60 (half tempo). Entry must align to the CONDUCTOR'S grid —
// the bar at conductor beat 2 (1.0 s) — not be stretched by the pattern's slow tempo.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
let slow: EventPattern<CondVoice> = EventPattern(make: { CondVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(60.0)
c.add(slow, quantize: .nextMultiple(ofBeats: 2.0))
return c
}
// Still inside the 1.0 s conductor lead-in: nothing built.
try? await Task.sleep(for: .milliseconds(300))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
// Enters on the conductor's bar line and runs to completion.
let deadline: Date = Date().addingTimeInterval(2.5)
while CondVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
conductor.stop()
}
@Test func currentBeatAdvancesWhileRunning() async {
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
return c
}
#expect(conductor.currentBeat >= 0.0)
try? await Task.sleep(for: .milliseconds(500))
// 500 ms at 120 BPM ≈ 1.0 beat; assert a generous lower bound to avoid CI-load flake.
#expect(conductor.currentBeat > 0.3)
conductor.stop()
}
@Test func stopDuringStartHaltsEverything() async {
// Race stop() against the inbox service across many iterations with a randomised sub-poll
// delay, so some iterations land stop() mid-hop (the post-hop `.stopped` branch) rather than
// before the first 10 ms poll. After each iteration nothing may keep playing.
for iteration: Int in 0..<24 {
CondVoice.buildCount.store(0, ordering: .releasing)
let (conductor, patterns): (EventConductor, [EventPattern<CondVoice>]) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
let ps: [EventPattern<CondVoice>] = (0..<4).map { _ in makeInfinitePattern(tempo: 240.0) }
return (c, ps)
}
for pattern: EventPattern<CondVoice> in patterns {
conductor.add(pattern, quantize: .now)
}
// 0–15 ms: sometimes before the first poll, sometimes mid-service.
let delayMs: Int = (iteration * 7) % 16
if delayMs > 0 {
try? await Task.sleep(for: .milliseconds(delayMs))
}
conductor.stop()
// Let any in-flight start land and any missed child reveal itself by climbing the counter.
try? await Task.sleep(for: .milliseconds(120))
let countA: Int = CondVoice.buildCount.load(ordering: .acquiring)
try? await Task.sleep(for: .milliseconds(120))
let countB: Int = CondVoice.buildCount.load(ordering: .acquiring)
#expect(countA == countB, "iteration \(iteration): a child kept building after stop()")
#expect(!conductor.hasActiveChildren, "iteration \(iteration): active child survived stop()")
#expect(!conductor.isRunning)
}
}
@Test func stopHaltsConductorAndChildren() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// An infinite pattern, started immediately.
let conductor: EventConductor = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
c.add(makeInfinitePattern(tempo: 120.0), quantize: .now)
return c
}
try? await Task.sleep(for: .milliseconds(200))
#expect(conductor.hasActiveChildren)
conductor.stop()
let deadline: Date = Date().addingTimeInterval(2.0)
while conductor.hasActiveChildren, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!conductor.hasActiveChildren)
#expect(!conductor.isRunning)
// A stopped conductor ignores further adds.
let countAfterStop: Int = CondVoice.buildCount.load(ordering: .acquiring)
await MainActor.run { conductor.add(makeFinitePattern(tempo: 120.0), quantize: .now) }
try? await Task.sleep(for: .milliseconds(150))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == countAfterStop)
}
@Test func concurrentAddsFromManyThreadsAllPlay() async {
CondVoice.buildCount.store(0, ordering: .releasing)
let patternCount: Int = 8
let (conductor, patterns): (EventConductor, [EventPattern<CondVoice>]) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
let ps: [EventPattern<CondVoice>] = (0..<patternCount).map { _ in makeFinitePattern(tempo: 240.0) }
return (c, ps)
}
// Hammer add(_:) from many threads at once — the lock-guarded inbox must accept them all.
let box: PatternBox = PatternBox(patterns)
DispatchQueue.concurrentPerform(iterations: patternCount) { i in
box.add(into: conductor, index: i)
}
conductor.waitUntilIdle()
#expect(CondVoice.buildCount.load(ordering: .acquiring) == patternCount * 2)
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func addReturnsHandlePlayingUntilDone() async {
CondVoice.buildCount.store(0, ordering: .releasing)
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
return (c, makeFinitePattern(tempo: 240.0))
}
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
#expect(handle.isPlaying) // pending → reports playing before it even enters
conductor.waitUntilIdle()
#expect(!handle.isPlaying) // finite pattern finished
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 2)
conductor.stop()
}
@Test func perPartStopLeavesOtherPartsPlaying() async {
CondVoice.buildCount.store(0, ordering: .releasing)
let (conductor, patternA, patternB): (EventConductor, EventPattern<CondVoice>, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
return (c, makeInfinitePattern(tempo: 240.0), makeInfinitePattern(tempo: 240.0))
}
let handleA: EventConductorHandle = conductor.add(patternA, quantize: .now)
let handleB: EventConductorHandle = conductor.add(patternB, quantize: .now)
// Wait until both have entered and are building voices.
let entryDeadline: Date = Date().addingTimeInterval(1.0)
while !conductor.hasActiveChildren, Date() < entryDeadline {
try? await Task.sleep(for: .milliseconds(20))
}
try? await Task.sleep(for: .milliseconds(150))
#expect(handleA.isPlaying)
#expect(handleB.isPlaying)
// Stop ONE part. Its pattern tears down (an infinite pattern's teardown is not instant), so
// poll its handle with a deadline rather than assuming a fixed delay.
handleA.stop()
let aStopDeadline: Date = Date().addingTimeInterval(2.0)
while handleA.isPlaying, Date() < aStopDeadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handleA.isPlaying) // the stopped part is gone
// The other part must keep playing and keep building voices.
let countAfterStopA: Int = CondVoice.buildCount.load(ordering: .acquiring)
try? await Task.sleep(for: .milliseconds(250))
let countLater: Int = CondVoice.buildCount.load(ordering: .acquiring)
#expect(handleB.isPlaying) // the other part survives
#expect(conductor.hasActiveChildren)
#expect(countLater > countAfterStopA) // part B kept building
conductor.stop()
let stopDeadline: Date = Date().addingTimeInterval(2.0)
while handleB.isPlaying, Date() < stopDeadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handleB.isPlaying)
#expect(!conductor.hasActiveChildren)
}
@Test func handleStopBeforeEntryNeverBuilds() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// afterBeats(1) at 240 BPM = a 0.25 s lead-in, so the entry falls WELL INSIDE the wait
// window below: were the pre-entry cancel skip removed, the pattern would enter and build.
// The immediate stop() must prevent that.
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
return (c, makeInfinitePattern(tempo: 240.0))
}
let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(1.0))
handle.stop() // cancel while still pending
// waitUntilIdle must return (covers `_starting` decrement on the skip path); the entry
// window (0.25 s) elapses well within the wait.
conductor.waitUntilIdle()
try? await Task.sleep(for: .milliseconds(350))
#expect(!handle.isPlaying)
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0) // never entered
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func addAfterStopReturnsStoppedHandle() async {
CondVoice.buildCount.store(0, ordering: .releasing)
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
return (c, makeInfinitePattern(tempo: 240.0))
}
conductor.stop()
// Adding to a stopped conductor returns an already-cancelled handle and never builds.
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
#expect(!handle.isPlaying)
try? await Task.sleep(for: .milliseconds(150))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
}
@Test func conductorStopCancelsPendingHandle() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// A part queued far out, then the whole conductor stopped before it enters: its handle must
// report not-playing and it must never build a voice.
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 120.0)
c.start(on: engine)
return (c, makeInfinitePattern(tempo: 120.0))
}
let handle: EventConductorHandle = conductor.add(pattern, quantize: .afterBeats(8.0)) // 4 s out
try? await Task.sleep(for: .milliseconds(100)) // let it resolve into _pending
conductor.stop()
try? await Task.sleep(for: .milliseconds(150))
#expect(!handle.isPlaying)
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
}
@Test func handleAddedBeforeStartCanBeStopped() async {
CondVoice.buildCount.store(0, ordering: .releasing)
// Add BEFORE start (the _inbox path), stop the handle, THEN start. It must never enter.
let (conductor, handle): (EventConductor, EventConductorHandle) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
let h: EventConductorHandle = c.add(makeInfinitePattern(tempo: 240.0), quantize: .now)
h.stop()
c.start(on: engine)
return (c, h)
}
try? await Task.sleep(for: .milliseconds(200))
#expect(!handle.isPlaying)
#expect(CondVoice.buildCount.load(ordering: .acquiring) == 0)
#expect(!conductor.hasActiveChildren)
conductor.stop()
}
@Test func handleStopRacingEntryNeverLeaksAChild() async {
// Stress the per-part stop against the entry hop: add one infinite part `.now`, stop its
// handle after a randomised sub-poll delay, and confirm nothing keeps playing. Exercises the
// pre-hop skip and the attach-after-cancel path.
for iteration: Int in 0..<24 {
CondVoice.buildCount.store(0, ordering: .releasing)
let (conductor, pattern): (EventConductor, EventPattern<CondVoice>) = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let c: EventConductor = EventConductor(tempo: 240.0)
c.start(on: engine)
return (c, makeInfinitePattern(tempo: 240.0))
}
let handle: EventConductorHandle = conductor.add(pattern, quantize: .now)
let delayMs: Int = (iteration * 7) % 16
if delayMs > 0 {
try? await Task.sleep(for: .milliseconds(delayMs))
}
handle.stop()
let deadline: Date = Date().addingTimeInterval(2.0)
while handle.isPlaying, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handle.isPlaying, "iteration \(iteration): part kept playing after handle.stop()")
// Counter must stabilise — no orphaned child building on.
let countA: Int = CondVoice.buildCount.load(ordering: .acquiring)
try? await Task.sleep(for: .milliseconds(120))
#expect(CondVoice.buildCount.load(ordering: .acquiring) == countA,
"iteration \(iteration): a child kept building after handle.stop()")
conductor.stop()
}
}
}
/// Carries the main-built patterns into the `concurrentPerform` closure without tripping Sendable
/// checking — the array is read-only after construction and each index is touched once.
private final class PatternBox: @unchecked Sendable {
private let patterns: [EventPattern<CondVoice>]
init(_ patterns: [EventPattern<CondVoice>]) { self.patterns = patterns }
func add(into conductor: EventConductor, index: Int) {
conductor.add(patterns[index], quantize: .now)
}
}
+425
View File
@@ -0,0 +1,425 @@
// EventPatternTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Shared fixtures
/// Voice recording the parameter values it was configured with and the sustain it was handed.
/// A `SynthesizerBase` so `engine.add` invokes `build()` immediately (a bare `Synthesizer`
/// only builds on a later rebuild, which the offline test engine never triggers). Key paths
/// into its `@LiveParam`s are formed on the main actor (both suites do so).
private final class EventTestVoice: SynthesizerBase, EventSustainAware {
@LiveParam var freq: Double = 0.0
@LiveParam var amp: Double = 0.0
var sustainSeconds: Double = -1.0
/// Counts `build()` calls so the playback suite can see real spawns.
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
func setEventSustain(seconds: Double) {
sustainSeconds = seconds
}
override func build() {
EventTestVoice.buildCount.wrappingAdd(1, ordering: .releasing)
output(bus: 0, source: $amp)
}
}
/// Voice that does **not** conform to `EventSustainAware` — proves the no-hand-off branch
/// resolves cleanly.
private final class PlainEventVoice: SynthesizerBase {
@LiveParam var freq: Double = 0.0
override func build() {
output(bus: 0, source: $freq)
}
}
/// Voice conforming to `EventGated`: exposes a gate `@LiveParam` (default open) that `EventPattern`
/// drives. Used to prove the gate note-off path — opened on add, closed after `sustain`, and the
/// voice is never hard-removed by the pattern.
private final class GatedEventVoice: SynthesizerBase, EventGated {
@LiveParam var freq: Double = 0.0
@LiveParam var gate: Double = 1.0
var eventGate: ParameterNode { $gate }
override func build() {
output(bus: 0, source: $freq * $gate)
}
}
/// Voice conforming to BOTH ``EventGated`` and ``EventSustainAware``. Proves gate precedence: the
/// pattern drives release through the gate and never calls `setEventSustain`, so `sustainSeconds`
/// keeps its sentinel value.
private final class GatedAndSustainVoice: SynthesizerBase, EventGated, EventSustainAware {
@LiveParam var freq: Double = 0.0
@LiveParam var gate: Double = 1.0
var sustainSeconds: Double = -1.0
var eventGate: ParameterNode { $gate }
func setEventSustain(seconds: Double) {
sustainSeconds = seconds
}
override func build() {
output(bus: 0, source: $freq * $gate)
}
}
/// Carries a captured gated voice out of the main-actor setup block so the playback suite can
/// inspect its gate value and binding after waiting off-main. `@unchecked Sendable`: written and
/// read only inside `MainActor.run` hops.
private final class GatedVoiceHolder: @unchecked Sendable {
var voice: GatedEventVoice?
}
/// The gated voice's current gate value (reads the `@LiveParam` node). Read on the main actor.
@MainActor private func gateValue(_ voice: GatedEventVoice?) -> Double {
voice?.gate ?? -1.0
}
/// `true` while a gated voice is still bound to an engine. Read on the main actor.
@MainActor private func isBoundGated(_ voice: GatedEventVoice?) -> Bool {
guard let voice: GatedEventVoice = voice else { return false }
return voice._engineBinding.load(ordering: .acquiring) != 0
}
// MARK: - Pure-logic suite
/// `EventPattern` event resolution — driven synchronously through the `EventStream` core on
/// the main actor. No background task, no engine: deterministic. Key paths (`\.freq`) are
/// formed on the main actor, which is where user setup code runs.
///
/// Note: `Pattern.sequence` defaults to `repeats: -1` (infinite cycling), so tests that expect a
/// bounded stream pass `repeats: 1`.
@MainActor
@Suite("EventPattern")
struct EventPatternLogicTests {
/// Drains a pattern's stream synchronously, returning the resolved events. `max` bounds
/// infinite streams.
private func drain<V: Synthesizer>(
_ pattern: EventPattern<V>,
max: Int = 100
) -> [EventStream<V>.Event] {
let stream: EventStream<V> = pattern.makeEventStream()
var events: [EventStream<V>.Event] = []
while events.count < max, let event: EventStream<V>.Event = stream.next() {
events.append(event)
}
return events
}
@Test func bindsParametersInSequence() {
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
.bind(\.amp, .sequence([0.1, 0.2, 0.3], repeats: 1))
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
#expect(events.count == 3)
#expect(events.map(\.voice.freq) == [440.0, 550.0, 660.0])
#expect(events.map(\.voice.amp) == [0.1, 0.2, 0.3])
}
@Test func endsWhenAnyBoundPatternExhausts() {
// freq has 2 values, amp has 5 — the stream must stop after 2 events.
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.bind(\.amp, .sequence([0.1, 0.2, 0.3, 0.4, 0.5], repeats: 1))
#expect(drain(pattern).count == 2)
}
@Test func durExhaustionEndsStream() {
// A finite dur pattern ends the stream even when a binding is infinite.
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.25, 0.25], repeats: 1))
#expect(drain(pattern).count == 2)
}
@Test func legatoDeterminesSustain() {
// delta = 1 beat, legato 0.5 → sustain 0.5 beat; tempo 120 → 0.25 s.
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([1.0]))
.legato(0.5)
.tempo(120.0)
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
#expect(events.count == 1)
let event: EventStream<EventTestVoice>.Event? = events.first
#expect(abs((event?.sustain ?? -1.0) - 0.5) < 1e-9)
#expect(abs((event?.voice.sustainSeconds ?? -1.0) - 0.25) < 1e-9)
}
@Test func repeatsReplaysTheWholeSet() {
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.repeats(3)
let freqs: [Double] = drain(pattern).map(\.voice.freq)
#expect(freqs == [440.0, 550.0, 440.0, 550.0, 440.0, 550.0])
}
@Test func nonAwareVoiceResolves() {
let pattern: EventPattern<PlainEventVoice> = EventPattern(make: { PlainEventVoice() })
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
let events: [EventStream<PlainEventVoice>.Event] = drain(pattern)
#expect(events.map(\.voice.freq) == [100.0, 200.0, 300.0])
}
@Test func gatedVoiceCarriesGateAndIsSelfFreeing() {
let pattern: EventPattern<GatedEventVoice> = EventPattern(make: { GatedEventVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
let events: [EventStream<GatedEventVoice>.Event] = drain(pattern)
#expect(events.count == 1)
#expect(events.first?.gate != nil) // gate node captured → note-off is driven
#expect(events.first?.selfFreeing == true) // not hard-removed
}
@Test func sustainAwareVoiceHasNoGateButIsSelfFreeing() {
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
let event: EventStream<EventTestVoice>.Event? = drain(pattern).first
#expect(event?.gate == nil) // sustain model, no gate
#expect(event?.selfFreeing == true) // still not hard-removed (self-timed envelope)
}
@Test func gatedVoiceWinsOverSustainAware() {
// A voice conforming to both: the gate drives release, so `setEventSustain` is NOT called
// and the two release mechanisms never both fire.
let pattern: EventPattern<GatedAndSustainVoice> = EventPattern(make: { GatedAndSustainVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([1.0]))
.legato(1.0)
.tempo(60.0)
let event: EventStream<GatedAndSustainVoice>.Event? = drain(pattern).first
#expect(event?.gate != nil) // gate drives release
#expect(event?.selfFreeing == true) // not hard-removed
#expect(event?.voice.sustainSeconds == -1.0) // setEventSustain NOT called → gate wins
}
@Test func plainVoiceIsNotSelfFreeing() {
let pattern: EventPattern<PlainEventVoice> = EventPattern(make: { PlainEventVoice() })
.bind(\.freq, .sequence([100.0], repeats: 1))
let event: EventStream<PlainEventVoice>.Event? = drain(pattern).first
#expect(event?.gate == nil)
#expect(event?.selfFreeing == false) // neither protocol → hard-removed as a backstop
}
@Test func repeatsBelowOnePlaysNothing() {
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.repeats(0)
#expect(drain(pattern).isEmpty)
}
@Test func emptyPassWithHugeRepeatsTerminates() {
// A pass yielding nothing must end the stream rather than spin — the guard against an
// empty pattern combined with a very large `repeats`.
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([], repeats: 1))
.repeats(Int.max)
#expect(drain(pattern).isEmpty)
}
@Test func tempoScalesSustainSeconds() {
// delta 1 beat, legato 1.0, tempo 60 → sustain 1 beat = 1.0 s.
let pattern: EventPattern<EventTestVoice> = EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([1.0]))
.legato(1.0)
.tempo(60.0)
let events: [EventStream<EventTestVoice>.Event] = drain(pattern)
#expect(events.count == 1)
#expect(abs((events.first?.voice.sustainSeconds ?? -1.0) - 1.0) < 1e-9)
}
}
// MARK: - Playback suite (real play(on:))
/// `EventPattern.play(on:)` driving the engine through a background `LyrebirdTask`. The suite
/// is **not** `@MainActor`: the body's `ctx.add` / `ctx.onMain` hops need the real main thread
/// free to service them, so each test waits off-main while the pattern builds voices. Key
/// paths are formed inside a `MainActor.run` (the pattern is `@unchecked Sendable`).
@Suite("EventPattern Playback", .serialized)
struct EventPatternPlaybackTests {
@Test func playsConfiguredVoicesOnEngine() async {
EventTestVoice.buildCount.store(0, ordering: .releasing)
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
return EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
.play(on: engine)
}
handle.waitUntilComplete()
// `ctx.add` is dispatched async to main, so `build()` runs after the body ends; poll
// off-main (leaving main free to drain those adds) until both voices are built.
let deadline: Date = Date().addingTimeInterval(2.0)
while EventTestVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(EventTestVoice.buildCount.load(ordering: .acquiring) == 2)
}
@Test func stopHaltsSpawning() async {
EventTestVoice.buildCount.store(0, ordering: .releasing)
// Infinite stream at a modest rate (0.05 beat @ 120 bpm = 25 ms/event).
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
return EventPattern(make: { EventTestVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.05]))
.tempo(120.0)
.play(on: engine)
}
try? await Task.sleep(for: .milliseconds(150)) // a few events spawn
handle.stop()
let deadline: Date = Date().addingTimeInterval(2.0)
while handle.isPlaying, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handle.isPlaying)
let afterStop: Int = EventTestVoice.buildCount.load(ordering: .acquiring)
#expect(afterStop > 0) // it really was spawning
try? await Task.sleep(for: .milliseconds(120)) // nothing new should spawn
#expect(EventTestVoice.buildCount.load(ordering: .acquiring) == afterStop)
}
@Test func finiteStreamStopsPlayingWhenComplete() async {
EventTestVoice.buildCount.store(0, ordering: .releasing)
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
return EventPattern(make: { EventTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
.play(on: engine)
}
handle.waitUntilComplete()
// A finite pattern's task has finished once `waitUntilComplete` returns, so the handle
// reports not playing (neither running nor paused).
let deadline: Date = Date().addingTimeInterval(2.0)
while handle.isPlaying, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handle.isPlaying)
}
}
// MARK: - Gate playback suite (EventGated note-off)
/// `EventPattern` driving an ``EventGated`` voice: the gate opens on add and is closed after
/// `sustain` (the note-off), and the pattern never hard-removes the voice. Not `@MainActor` — the
/// body's hops need the real main thread free, so each test waits off-main.
@Suite("EventPattern Gate Playback", .serialized)
struct EventPatternGatePlaybackTests {
/// Polls off-main (leaving main free to drain dispatched engine ops) until `check` holds or the
/// deadline passes; returns the final value.
private func poll(timeout: Double = 2.0, _ check: @escaping @MainActor () -> Bool) async -> Bool {
let deadline: Date = Date().addingTimeInterval(timeout)
while await MainActor.run(body: check) == false, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
return await MainActor.run(body: check)
}
@Test func gatedVoiceGetsNoteOffAndIsNotHardRemoved() async {
let holder: GatedVoiceHolder = GatedVoiceHolder()
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let voice: GatedEventVoice = GatedEventVoice()
holder.voice = voice
// Single short event → one voice, one scheduled note-off at sustain.
return EventPattern(make: { voice })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([0.05]))
.legato(0.5)
.tempo(240.0)
.play(on: engine)
}
// `waitUntilComplete` returns only after the body's `waitForScheduledSets` has fired the
// note-off, so the gate is already closed by the time it returns.
handle.waitUntilComplete()
#expect(await poll { gateValue(holder.voice) == 0.0 }) // note-off fired
// The gated voice was never hard-removed — it would free only via `doneAction` during
// rendering, which the offline test engine does not drive. So it is still bound.
#expect(await poll { isBoundGated(holder.voice) })
}
@Test func stopClosesOutstandingGate() async {
let holder: GatedVoiceHolder = GatedVoiceHolder()
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let voice: GatedEventVoice = GatedEventVoice()
holder.voice = voice
// One very long event: the voice is added, its note-off scheduled far in the future,
// and the body parks in `wait`. `stop()` must close the gate now rather than leak it open.
return EventPattern(make: { voice })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([100.0]))
.legato(1.0)
.tempo(60.0)
.play(on: engine)
}
#expect(await poll { gateValue(holder.voice) == 1.0 }) // gate open while sounding
handle.stop()
#expect(await poll { !handle.isPlaying })
#expect(await poll { gateValue(holder.voice) == 0.0 }) // stop flushed the note-off
}
@Test func releasePaddingDelaysReturnPastCompletion() async {
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
return EventPattern(make: { GatedEventVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([0.01]))
.tempo(240.0)
.play(on: engine)
}
// The suite is off-main, so `waitUntilComplete` takes the plain-sleep padding branch. The
// short pattern finishes near-instantly, so the measured time is dominated by the padding.
let padding: Double = 0.3
let start: Date = Date()
handle.waitUntilComplete(releasePadding: padding)
let elapsed: Double = Date().timeIntervalSince(start)
#expect(elapsed >= padding)
}
}
@@ -0,0 +1,49 @@
// EventQuantumTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
/// `EventQuantum.targetBeat(from:)` — pure resolution of each quantum against a current beat.
@Suite("EventQuantum")
struct EventQuantumTests {
@Test func nowResolvesToNow() {
#expect(EventQuantum.now.targetBeat(from: 3.4) == 3.4)
}
@Test func nextBeatIsStrictlyAfterNow() {
#expect(EventQuantum.nextBeat.targetBeat(from: 3.4) == 4.0)
// On an exact beat, the next boundary is the following whole beat, not the current one.
#expect(EventQuantum.nextBeat.targetBeat(from: 3.0) == 4.0)
}
@Test func nextMultipleSnapsToTheNextGridLine() {
#expect(EventQuantum.nextMultiple(ofBeats: 4.0).targetBeat(from: 5.2) == 8.0)
// On an exact bar line, the next bar is the following one.
#expect(EventQuantum.nextMultiple(ofBeats: 4.0).targetBeat(from: 4.0) == 8.0)
#expect(EventQuantum.nextMultiple(ofBeats: 2.0).targetBeat(from: 0.5) == 2.0)
}
@Test func atBeatIsAbsolute() {
#expect(EventQuantum.atBeat(10.0).targetBeat(from: 2.0) == 10.0)
}
@Test func atBeatInThePastResolvesToThatPastBeat() {
// A beat already gone by resolves to itself (below now); the conductor treats it as already due.
#expect(EventQuantum.atBeat(1.0).targetBeat(from: 5.0) == 1.0)
}
@Test func nextBeatHandlesNearBoundaryFloat() {
// Just shy of beat 3 rounds down to 2, so the next whole beat is 3.
#expect(EventQuantum.nextBeat.targetBeat(from: 2.9999999999) == 3.0)
}
@Test func afterBeatsIsRelativeAndClampsNegative() {
#expect(EventQuantum.afterBeats(2.5).targetBeat(from: 2.0) == 4.5)
#expect(EventQuantum.afterBeats(-1.0).targetBeat(from: 2.0) == 2.0)
}
}
@@ -0,0 +1,297 @@
// MonoEventPatternTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Shared fixtures
/// Single reused voice for `MonoEventPattern`. Records the sustain it was handed and counts its
/// own re-articulations. A `SynthesizerBase` so `engine.add` invokes `build()` immediately.
private final class MonoTestVoice: SynthesizerBase, EventRetriggerable, EventSustainAware {
@LiveParam var freq: Double = 0.0
var sustainSeconds: Double = -1.0
/// Number of `retrigger()` calls — expected to be one less than the event count (the first
/// event is articulated by `build()` on add, not by `retrigger()`).
var retriggerCount: Int = 0
/// Counts `build()` calls so the playback suite can prove the voice is added exactly once.
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
func setEventSustain(seconds: Double) {
sustainSeconds = seconds
}
func retrigger() {
retriggerCount += 1
}
override func build() {
MonoTestVoice.buildCount.wrappingAdd(1, ordering: .releasing)
output(bus: 0, source: $freq)
}
}
/// Voice conforming to neither optional protocol — proves a plain persistent voice (no
/// re-articulation, no sustain hand-off) resolves cleanly.
private final class PlainMonoVoice: SynthesizerBase {
@LiveParam var freq: Double = 0.0
override func build() {
output(bus: 0, source: $freq)
}
}
/// Mono voice conforming to BOTH ``EventGated`` and ``EventSustainAware``. Proves gate precedence
/// in the mono stream: a gated voice releases through its gate and is not also self-timed, so
/// `setEventSustain` is never called and `sustainSeconds` keeps its sentinel.
private final class GatedMonoVoice: SynthesizerBase, EventGated, EventSustainAware {
@LiveParam var freq: Double = 0.0
@LiveParam var gate: Double = 1.0
var sustainSeconds: Double = -1.0
var eventGate: ParameterNode { $gate }
func setEventSustain(seconds: Double) {
sustainSeconds = seconds
}
override func build() {
output(bus: 0, source: $freq * $gate)
}
}
/// Carries the persistent voice out of the main-actor setup block so the playback suite can
/// inspect it (binding state, retrigger count) after waiting off-main. `@unchecked Sendable`:
/// the voice is written and read only inside `MainActor.run` hops.
private final class VoiceHolder: @unchecked Sendable {
var voice: MonoTestVoice?
}
/// `true` while `voice` is still bound to an engine (its ownership atomic is non-zero). Read on
/// the main actor.
@MainActor private func isBound(_ voice: MonoTestVoice?) -> Bool {
guard let voice: MonoTestVoice = voice else { return false }
return voice._engineBinding.load(ordering: .acquiring) != 0
}
// MARK: - Pure-logic suite
/// `MonoEventPattern` event resolution — driven synchronously through the `MonoEventStream` core
/// on the main actor. No background task, no engine: deterministic.
///
/// Note: `Pattern.sequence` defaults to `repeats: -1` (infinite cycling), so tests that expect a
/// bounded stream pass `repeats: 1`.
@MainActor
@Suite("MonoEventPattern")
struct MonoEventPatternLogicTests {
/// Drains a pattern's stream synchronously, snapshotting the reused voice's `freq` after each
/// event. Returns the voice and the per-event `freq` snapshots.
private func drainFreqs<V: Synthesizer>(
_ pattern: MonoEventPattern<V>,
reading freq: KeyPath<V, Double>,
max: Int = 100
) -> (voice: V, freqs: [Double]) {
let stream: MonoEventStream<V> = pattern.makeEventStream()
var freqs: [Double] = []
while freqs.count < max, stream.next() != nil {
freqs.append(stream.voice[keyPath: freq])
}
return (stream.voice, freqs)
}
@Test func writesSequenceToOneVoice() {
var makeCount: Int = 0
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: {
makeCount += 1
return MonoTestVoice()
})
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
#expect(result.freqs == [440.0, 550.0, 660.0])
// One voice made for the whole stream.
#expect(makeCount == 1)
}
@Test func retriggerSkipsTheFirstEvent() {
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
#expect(result.freqs.count == 3)
// 3 events → 2 re-articulations (first is build()'s job).
#expect(result.voice.retriggerCount == 2)
}
@Test func endsWhenAnyBoundPatternExhausts() {
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.25, 0.25, 0.25, 0.25, 0.25], repeats: 1))
#expect(drainFreqs(pattern, reading: \.freq).freqs.count == 2)
}
@Test func durExhaustionEndsStream() {
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.25, 0.25], repeats: 1))
#expect(drainFreqs(pattern, reading: \.freq).freqs.count == 2)
}
@Test func repeatsReplaysTheWholeSet() {
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.repeats(3)
#expect(drainFreqs(pattern, reading: \.freq).freqs == [440.0, 550.0, 440.0, 550.0, 440.0, 550.0])
}
@Test func legatoDeterminesSustainSeconds() {
// delta 1 beat, legato 0.5 → sustain 0.5 beat; tempo 120 → 0.25 s.
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([1.0]))
.legato(0.5)
.tempo(120.0)
let result: (voice: MonoTestVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
#expect(result.freqs.count == 1)
#expect(abs(result.voice.sustainSeconds - 0.25) < 1e-9)
}
@Test func gatedMonoVoiceWinsOverSustainAware() {
// A mono voice conforming to both: the gate drives release, so `setEventSustain` is never
// called and `sustainSeconds` keeps its sentinel.
let pattern: MonoEventPattern<GatedMonoVoice> = MonoEventPattern(make: { GatedMonoVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([1.0]))
.legato(1.0)
.tempo(60.0)
let result: (voice: GatedMonoVoice, freqs: [Double]) = drainFreqs(pattern, reading: \.freq)
#expect(result.freqs.count == 1)
#expect(result.voice.sustainSeconds == -1.0) // gated → setEventSustain not called
}
@Test func plainVoiceResolvesWithoutOptionalProtocols() {
let pattern: MonoEventPattern<PlainMonoVoice> = MonoEventPattern(make: { PlainMonoVoice() })
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
#expect(drainFreqs(pattern, reading: \.freq).freqs == [100.0, 200.0, 300.0])
}
@Test func repeatsBelowOnePlaysNothing() {
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([440.0], repeats: 1))
.repeats(0)
#expect(drainFreqs(pattern, reading: \.freq).freqs.isEmpty)
}
@Test func emptyPassWithHugeRepeatsTerminates() {
// A pass yielding nothing must end the stream rather than spin, even with huge repeats.
let pattern: MonoEventPattern<MonoTestVoice> = MonoEventPattern(make: { MonoTestVoice() })
.bind(\.freq, .sequence([], repeats: 1))
.repeats(Int.max)
#expect(drainFreqs(pattern, reading: \.freq).freqs.isEmpty)
}
}
// MARK: - Playback suite (real play(on:))
/// `MonoEventPattern.play(on:)` driving the engine through a background `LyrebirdTask`. Not
/// `@MainActor`: the body's hops need the real main thread free, so each test waits off-main.
@Suite("MonoEventPattern Playback", .serialized)
struct MonoEventPatternPlaybackTests {
/// Polls off-main (leaving main free to drain dispatched engine ops) until `check` holds or
/// the deadline passes; returns the final value.
private func poll(timeout: Double = 2.0, _ check: @escaping @MainActor () -> Bool) async -> Bool {
let deadline: Date = Date().addingTimeInterval(timeout)
while await MainActor.run(body: check) == false, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
return await MainActor.run(body: check)
}
@Test func addsAndRetriggersThenRemovesAtStreamEnd() async {
MonoTestVoice.buildCount.store(0, ordering: .releasing)
let holder: VoiceHolder = VoiceHolder()
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let voice: MonoTestVoice = MonoTestVoice()
holder.voice = voice
return MonoEventPattern(make: { voice })
.bind(\.freq, .sequence([440.0, 550.0, 660.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
.play(on: engine)
}
handle.waitUntilComplete()
// The persistent voice is added once (one build), re-struck on the 2nd and 3rd events,
// and unbound once the finite stream ends.
let unbound: Bool = await poll { isBound(holder.voice) == false }
#expect(unbound)
#expect(MonoTestVoice.buildCount.load(ordering: .acquiring) == 1)
await MainActor.run {
#expect(holder.voice?.retriggerCount == 2)
}
}
@Test func removesVoiceOnStop() async {
let holder: VoiceHolder = VoiceHolder()
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let voice: MonoTestVoice = MonoTestVoice()
holder.voice = voice
return MonoEventPattern(make: { voice })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.05]))
.tempo(120.0)
.play(on: engine)
}
// Let the voice get added, then stop — the voice must still be removed even though
// `ctx.wait` throws `.stopped` out of the loop before the trailing remove.
_ = await poll { isBound(holder.voice) }
handle.stop()
#expect(await poll { !handle.isPlaying })
#expect(await poll { isBound(holder.voice) == false })
}
@Test func repeatsZeroAddsNothing() async {
MonoTestVoice.buildCount.store(0, ordering: .releasing)
let holder: VoiceHolder = VoiceHolder()
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let voice: MonoTestVoice = MonoTestVoice()
holder.voice = voice
return MonoEventPattern(make: { voice })
.bind(\.freq, .sequence([440.0], repeats: 1))
.dur(.sequence([0.02]))
.repeats(0)
.play(on: engine)
}
handle.waitUntilComplete()
_ = await poll { !handle.isPlaying }
// No events → the voice is never added (never built) and never bound.
#expect(MonoTestVoice.buildCount.load(ordering: .acquiring) == 0)
#expect(await MainActor.run { isBound(holder.voice) } == false)
}
}
@@ -0,0 +1,261 @@
// ParallelEventPatternTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Shared fixtures
/// Voice for the polyphonic child — a fresh instance per event, so `build()` runs once per
/// spawned voice.
private final class ParPolyVoice: SynthesizerBase {
@LiveParam var freq: Double = 0.0
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
override func build() {
ParPolyVoice.buildCount.wrappingAdd(1, ordering: .releasing)
output(bus: 0, source: $freq)
}
}
/// Voice for the monophonic child — one reused instance, so `build()` runs exactly once.
private final class ParMonoVoice: SynthesizerBase {
@LiveParam var freq: Double = 0.0
nonisolated static let buildCount: Atomic<Int> = Atomic<Int>(0)
override func build() {
ParMonoVoice.buildCount.wrappingAdd(1, ordering: .releasing)
output(bus: 0, source: $freq)
}
}
// MARK: - Playback suite
/// `ParallelEventPattern.play(on:)` running a heterogeneous set of children (one `EventPattern`,
/// one `MonoEventPattern`) on one engine through their own background tasks. Serialized because
/// the fixtures share static build counters.
@Suite("ParallelEventPattern Playback", .serialized)
struct ParallelEventPatternPlaybackTests {
@Test func playsEveryChildToCompletion() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
ParMonoVoice.buildCount.store(0, ordering: .releasing)
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
.bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
return ParallelEventPattern([poly, mono]).play(on: engine)
}
handle.waitUntilComplete()
// Poly spawns one voice per event (2); mono adds one reused voice (1).
let deadline: Date = Date().addingTimeInterval(2.0)
while (ParPolyVoice.buildCount.load(ordering: .acquiring) < 2
|| ParMonoVoice.buildCount.load(ordering: .acquiring) < 1), Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == 1)
let stopped: Bool = await MainActor.run { !handle.isPlaying }
#expect(stopped)
}
@Test func isPlayingStaysTrueWhileAnyChildRuns() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
ParMonoVoice.buildCount.store(0, ordering: .releasing)
// A short finite poly child (2 quick events) alongside a long finite mono child (~0.5 s).
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let short: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
let long: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
.bind(\.freq, .sequence(Array(repeating: 100.0, count: 20), repeats: 1))
.dur(.sequence([0.05]))
.tempo(120.0)
return ParallelEventPattern([short, long]).play(on: engine)
}
// Once the short child has spawned both its voices it is done, but the long child keeps
// the merged handle playing.
let shortDone: Date = Date().addingTimeInterval(1.0)
while ParPolyVoice.buildCount.load(ordering: .acquiring) < 2, Date() < shortDone {
try? await Task.sleep(for: .milliseconds(10))
}
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(await MainActor.run { handle.isPlaying })
handle.waitUntilComplete()
let deadline: Date = Date().addingTimeInterval(2.0)
while handle.isPlaying, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handle.isPlaying)
}
@Test func nestedParallelPatternPlays() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
ParMonoVoice.buildCount.store(0, ordering: .releasing)
// A ParallelEventPattern nested as a child of another.
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
.bind(\.freq, .sequence([100.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
let inner: ParallelEventPattern = ParallelEventPattern([mono])
return ParallelEventPattern([poly, inner]).play(on: engine)
}
handle.waitUntilComplete()
let deadline: Date = Date().addingTimeInterval(2.0)
while (ParPolyVoice.buildCount.load(ordering: .acquiring) < 2
|| ParMonoVoice.buildCount.load(ordering: .acquiring) < 1), Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == 1)
#expect(await MainActor.run { !handle.isPlaying })
}
@Test func stopStopsEveryChild() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
ParMonoVoice.buildCount.store(0, ordering: .releasing)
// Built with the no-arg initializer + add(_:), driving the builder path. Both children
// are infinite.
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let poly: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.05]))
.tempo(120.0)
let mono: MonoEventPattern<ParMonoVoice> = MonoEventPattern(make: { ParMonoVoice() })
.bind(\.freq, .uniformRandom(low: 100.0, high: 200.0))
.dur(.sequence([0.05]))
.tempo(120.0)
return ParallelEventPattern()
.add(poly)
.add(mono)
.play(on: engine)
}
try? await Task.sleep(for: .milliseconds(150))
handle.stop()
let deadline: Date = Date().addingTimeInterval(2.0)
while handle.isPlaying, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(!handle.isPlaying)
// Both children were spawning, and both halt after stop.
let polyAfterStop: Int = ParPolyVoice.buildCount.load(ordering: .acquiring)
let monoAfterStop: Int = ParMonoVoice.buildCount.load(ordering: .acquiring)
#expect(polyAfterStop > 0)
#expect(monoAfterStop == 1) // mono adds its single voice once
try? await Task.sleep(for: .milliseconds(120))
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == polyAfterStop)
#expect(ParMonoVoice.buildCount.load(ordering: .acquiring) == monoAfterStop)
}
@Test func addAfterStaggersChildEntry() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
// One child, staggered two beats in. At 120 BPM that is a 1.0 s lead-in before its first
// voice is built; the task is live (waiting) throughout.
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let delayed: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(120.0)
return ParallelEventPattern()
.addAfter(beats: 2.0, eventPattern: delayed)
.play(on: engine)
}
// Well inside the 1.0 s lead-in, no voice has been built yet, but the handle is playing.
try? await Task.sleep(for: .milliseconds(300))
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0)
#expect(await MainActor.run { handle.isPlaying })
// After the lead-in elapses the stream runs to completion: both events fire.
handle.waitUntilComplete()
let deadline: Date = Date().addingTimeInterval(2.0)
while ParPolyVoice.buildCount.load(ordering: .acquiring) < 2, Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(await MainActor.run { !handle.isPlaying })
}
@Test func addAfterZeroEntersWithGroup() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
// addAfter(beats: 0) is equivalent to add(_:) — no lead-in, enters immediately.
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let child: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(240.0)
return ParallelEventPattern()
.addAfter(beats: 0.0, eventPattern: child)
.play(on: engine)
}
handle.waitUntilComplete()
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 2)
#expect(await MainActor.run { !handle.isPlaying })
}
@Test func stopDuringLeadInBuildsNoVoice() async {
ParPolyVoice.buildCount.store(0, ordering: .releasing)
// A long-staggered child stopped mid-lead-in must self-terminate without building a voice.
let handle: EventPatternHandle = await MainActor.run {
let engine: SynthesisEngine = makeTestEngine()
let delayed: EventPattern<ParPolyVoice> = EventPattern(make: { ParPolyVoice() })
.bind(\.freq, .sequence([440.0, 550.0], repeats: 1))
.dur(.sequence([0.02]))
.tempo(120.0)
return ParallelEventPattern()
.addAfter(beats: 8.0, eventPattern: delayed) // 4 s lead-in at 120 BPM
.play(on: engine)
}
// Still well inside the lead-in: playing, nothing built.
try? await Task.sleep(for: .milliseconds(300))
#expect(await MainActor.run { handle.isPlaying })
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0)
handle.stop()
let deadline: Date = Date().addingTimeInterval(2.0)
while (await MainActor.run { handle.isPlaying }), Date() < deadline {
try? await Task.sleep(for: .milliseconds(20))
}
#expect(await MainActor.run { !handle.isPlaying })
#expect(ParPolyVoice.buildCount.load(ordering: .acquiring) == 0) // never reached its first event
}
}
@@ -0,0 +1,100 @@
// RoutineContextScheduledSetTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Synchronization
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// `LyrebirdRoutineContext.set(_:to:after:)` — non-blocking scheduled parameter writes, serviced
/// on the body's own timeline during waits. These back the event-pattern gate note-off.
///
/// Not `@MainActor`: `LyrebirdTask.run` blocks the calling thread and the body runs off-main, so
/// running the test off-main leaves the main queue free (matching the other `LyrebirdTask` suites).
/// A bare `ParameterNode` is the write target — its value get/set is atomic and thread-safe, so no
/// synthesizer or engine graph is needed to observe the write.
@Suite("RoutineContext scheduled set") struct RoutineContextScheduledSetTests {
@Test func scheduledSetFiresAfterDelayNotBefore() {
let engine: SynthesisEngine = makeTestEngine()
let node: ParameterNode = ParameterNode(1.0)
let before: Ref<Double> = Ref(-1.0)
let after: Ref<Double> = Ref(-1.0)
LyrebirdTask.run(engine: engine) { ctx in
ctx.set(node, to: 0.0, after: 0.05)
before.value = node.value // not yet due — still 1.0
try ctx.wait(seconds: 0.15) // services the pending set en route
after.value = node.value // fired — 0.0
}
#expect(before.value == 1.0)
#expect(after.value == 0.0)
}
@Test func multipleScheduledSetsFireIndependently() {
let engine: SynthesisEngine = makeTestEngine()
let a: ParameterNode = ParameterNode(0.0)
let b: ParameterNode = ParameterNode(0.0)
let midA: Ref<Double> = Ref(-1.0)
let midB: Ref<Double> = Ref(-1.0)
let endA: Ref<Double> = Ref(-1.0)
let endB: Ref<Double> = Ref(-1.0)
LyrebirdTask.run(engine: engine) { ctx in
ctx.set(a, to: 1.0, after: 0.04) // fires first
ctx.set(b, to: 1.0, after: 0.12) // fires later
try ctx.wait(seconds: 0.08) // past a, before b
midA.value = a.value // 1.0
midB.value = b.value // still 0.0
try ctx.wait(seconds: 0.10) // past b
endA.value = a.value
endB.value = b.value // 1.0
}
#expect(midA.value == 1.0)
#expect(midB.value == 0.0)
#expect(endA.value == 1.0)
#expect(endB.value == 1.0)
}
@Test func waitForScheduledSetsDrainsPending() {
let engine: SynthesisEngine = makeTestEngine()
let node: ParameterNode = ParameterNode(1.0)
let result: Ref<Double> = Ref(-1.0)
LyrebirdTask.run(engine: engine) { ctx in
ctx.set(node, to: 0.0, after: 0.05)
// No explicit wait — `waitForScheduledSets` must itself block until the write fires.
try ctx.waitForScheduledSets()
result.value = node.value
}
#expect(result.value == 0.0)
}
@Test func flushFiresPendingSetsImmediately() {
let engine: SynthesisEngine = makeTestEngine()
let node: ParameterNode = ParameterNode(1.0)
let afterFlush: Ref<Double> = Ref(-1.0)
LyrebirdTask.run(engine: engine) { ctx in
ctx.set(node, to: 0.0, after: 100.0) // due far in the future
ctx._flushScheduledSets() // fire now regardless of due time
afterFlush.value = node.value
}
#expect(afterFlush.value == 0.0)
}
}
/// Minimal reference box so a `@Sendable` task body can report a result back to the test.
/// `@unchecked Sendable`: the body writes `value`, the test reads it only after `LyrebirdTask.run`
/// has joined the body thread — no concurrent access.
private final class Ref<T>: @unchecked Sendable {
var value: T
init(_ value: T) { self.value = value }
}