// 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 = Atomic(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( _ pattern: MonoEventPattern, reading freq: KeyPath, max: Int = 100 ) -> (voice: V, freqs: [Double]) { let stream: MonoEventStream = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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) } }