// 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 = Atomic(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( _ pattern: EventPattern, max: Int = 100 ) -> [EventStream.Event] { let stream: EventStream = pattern.makeEventStream() var events: [EventStream.Event] = [] while events.count < max, let event: EventStream.Event = stream.next() { events.append(event) } return events } @Test func bindsParametersInSequence() { let pattern: EventPattern = 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.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 = 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 = 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 = EventPattern(make: { EventTestVoice() }) .bind(\.freq, .sequence([440.0], repeats: 1)) .dur(.sequence([1.0])) .legato(0.5) .tempo(120.0) let events: [EventStream.Event] = drain(pattern) #expect(events.count == 1) let event: EventStream.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 = 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 = EventPattern(make: { PlainEventVoice() }) .bind(\.freq, .sequence([100.0, 200.0, 300.0], repeats: 1)) let events: [EventStream.Event] = drain(pattern) #expect(events.map(\.voice.freq) == [100.0, 200.0, 300.0]) } @Test func gatedVoiceCarriesGateAndIsSelfFreeing() { let pattern: EventPattern = EventPattern(make: { GatedEventVoice() }) .bind(\.freq, .sequence([440.0], repeats: 1)) let events: [EventStream.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 = EventPattern(make: { EventTestVoice() }) .bind(\.freq, .sequence([440.0], repeats: 1)) let event: EventStream.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 = EventPattern(make: { GatedAndSustainVoice() }) .bind(\.freq, .sequence([440.0], repeats: 1)) .dur(.sequence([1.0])) .legato(1.0) .tempo(60.0) let event: EventStream.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 = EventPattern(make: { PlainEventVoice() }) .bind(\.freq, .sequence([100.0], repeats: 1)) let event: EventStream.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 = 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 = 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 = EventPattern(make: { EventTestVoice() }) .bind(\.freq, .sequence([440.0], repeats: 1)) .dur(.sequence([1.0])) .legato(1.0) .tempo(60.0) let events: [EventStream.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) } }