// 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 = Atomic(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 = Atomic(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 = EventPattern(make: { ParPolyVoice() }) .bind(\.freq, .sequence([440.0, 550.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(240.0) let mono: MonoEventPattern = 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 = EventPattern(make: { ParPolyVoice() }) .bind(\.freq, .sequence([440.0, 550.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(240.0) let long: MonoEventPattern = 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 = EventPattern(make: { ParPolyVoice() }) .bind(\.freq, .sequence([440.0, 550.0], repeats: 1)) .dur(.sequence([0.02])) .tempo(240.0) let mono: MonoEventPattern = 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 = EventPattern(make: { ParPolyVoice() }) .bind(\.freq, .uniformRandom(low: 100.0, high: 200.0)) .dur(.sequence([0.05])) .tempo(120.0) let mono: MonoEventPattern = 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 = 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 = 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 = 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 } }