Files
Lyrebird/Tests/LyrebirdTests/Process/LyrebirdEventListTests.swift
T
2026-06-01 18:27:40 -07:00

1493 lines
54 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdEventListTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import Synchronization
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - Test fixtures
/// Minimal synthesizer that writes silence to the first bus argument.
private final class SilentSynth: SynthesizerBase {
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: 0.0))
}
}
/// Short fixed envelope — no releaseNode. Total duration ~40 ms.
private func shortAutoEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.02],
curves: [.lin, .lin]
)
}
/// Sustained envelope with a releaseNode — holds until gate drops.
/// Attack 20 ms, release tail 50 ms.
private func sustainedEnvelope() -> Envelope {
Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 0.05],
curves: [.lin, .lin],
releaseNode: 2
)
}
/// Build a test engine backed by OfflineDriver (no real-time audio).
private func makeEventListTestEngine() -> SynthesisEngine {
SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: OfflineDriver()
)
}
/// Build a `LyrebirdEventList` with `count` events, each starting one new process.
/// Returns both the list and all processes in event-order.
private func makeSimpleEventList(
id: String,
count: Int,
engine: SynthesisEngine
) throws -> (list: LyrebirdEventList, processes: [LyrebirdProcess]) {
var processes: [LyrebirdProcess] = []
var events: [LyrebirdEvent] = []
for i: Int in 0..<count {
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-\(i)",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in }
)
processes.append(proc)
events.append(LyrebirdEvent(starts: [proc]))
}
let list: LyrebirdEventList = try LyrebirdEventList(id: id, events: events, engine: engine, bus: AudioBus(index: 0, channelCount: 2))
return (list, processes)
}
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
private final class TestBlockDriver: @unchecked Sendable {
private var _thread: Thread?
private let _running: Atomic<Bool> = Atomic<Bool>(false)
private let _engine: SynthesisEngine
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
// before engine-time advances past envelope releases / process completions.
private static let blocksPerBurst: Int = 32
private static let wallSleepSeconds: TimeInterval = 0.001
init(engine: SynthesisEngine) { _engine = engine }
func start() {
_running.store(true, ordering: .relaxed)
let thread: Thread = Thread { [self] in
while self._running.load(ordering: .relaxed) {
for _ in 0..<Self.blocksPerBurst {
self._engine.processBlock(inputSamples: [])
}
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
}
}
thread.qualityOfService = .userInteractive
thread.start()
_thread = thread
}
func stop() { _running.store(false, ordering: .relaxed) }
}
// MARK: - Helpers
/// Thread-safe one-shot fulfillment token.
private final class AsyncExpectation: @unchecked Sendable {
private let _lock: NSLock = NSLock()
private var _fulfilled: Bool = false
var isFulfilled: Bool { _lock.withLock { _fulfilled } }
func fulfill() { _lock.withLock { _fulfilled = true } }
func waitForFulfillment(timeout: Double) async -> Bool {
let pollNs: UInt64 = 5_000_000
let deadlineNs: UInt64 = DispatchTime.now().uptimeNanoseconds
+ UInt64(timeout * 1_000_000_000)
while true {
if isFulfilled { return true }
let nowNs: UInt64 = DispatchTime.now().uptimeNanoseconds
if nowNs >= deadlineNs { return isFulfilled }
try? await Task.sleep(nanoseconds: pollNs)
}
}
}
/// Thread-safe mutable value box.
private final class Box<T>: @unchecked Sendable {
private let _lock: NSLock = NSLock()
private var _value: T
init(_ value: T) { _value = value }
func get() -> T { _lock.withLock { _value } }
func mutate(_ transform: (inout T) -> Void) { _lock.withLock { transform(&_value) } }
}
// MARK: - Suite
@Suite("LyrebirdEventList")
struct LyrebirdEventListTests {
// MARK: - Test 1: init with empty events
@Test("init with empty events → no traps, currentEvent nil, nextEvent nil, isRunning false")
func testInitEmpty() throws {
let engine: SynthesisEngine = makeEventListTestEngine()
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-empty",
events: [],
engine: engine
)
#expect(eventList.currentEvent == nil)
// Empty events list: index=0, events.count=0 → 0 < 0 is false → nextEvent is nil.
#expect(eventList.nextEvent == nil)
#expect(!eventList.isRunning)
#expect(eventList.startStamp == nil)
}
// MARK: - Test 2: next() plays index 0 and increments
@Test("next() plays index 0, increments index → currentEvent=0, nextEvent=1, startStamp set, isRunning true")
func testNextPlaysAndIncrements() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let eventFired: Box<Bool> = Box(false)
let capturedEventIdx: Box<Int> = Box(-1)
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-next",
events: [
LyrebirdEvent(starts: [proc]),
LyrebirdEvent()
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
eventList.onEvent = { idx in
capturedEventIdx.mutate { $0 = idx }
eventFired.mutate { $0 = true }
}
#expect(eventList.nextEvent == 0)
eventList.next()
// Give main-thread dispatches time to land.
try await Task.sleep(nanoseconds: 50_000_000)
#expect(eventFired.get(), "onEvent should have fired")
#expect(capturedEventIdx.get() == 0, "onEvent should have received index 0")
#expect(eventList.currentEvent == 0)
#expect(eventList.nextEvent == 1)
#expect(eventList.isRunning)
#expect(eventList.startStamp != nil)
eventList.killAll()
}
// MARK: - Test 3: nextEvent is nil past end
@Test("multiple next() calls advance through events; past end → nextEvent nil")
func testNextEventNilPastEnd() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-past-end",
events: [
LyrebirdEvent(),
LyrebirdEvent()
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
#expect(eventList.nextEvent == 0)
eventList.next()
#expect(eventList.nextEvent == 1)
eventList.next()
#expect(eventList.nextEvent == nil)
// One more next() past end — should be a no-op.
eventList.next()
#expect(eventList.nextEvent == nil)
#expect(eventList.currentEvent == 1)
eventList.killAll()
}
// MARK: - Test 4: play(eventIndex:) jumps without releasing prior runners
@Test("play(eventIndex:) jumps to specified index without releasing prior runners")
func testPlayEventIndexNoAutoRelease() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-jump-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let proc1: LyrebirdProcess = LyrebirdProcess(
id: "proc-jump-1",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-jump",
events: [
LyrebirdEvent(starts: [proc0]),
LyrebirdEvent(starts: [proc1])
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Play event 0 to start proc0.
eventList.play(eventIndex: 0)
try await Task.sleep(nanoseconds: 60_000_000)
#expect(proc0.isRunning, "proc0 should be running after event 0")
// Jump to event 1 — proc0 should NOT be released.
eventList.play(eventIndex: 1)
try await Task.sleep(nanoseconds: 60_000_000)
#expect(proc0.isRunning, "proc0 should still be running after jumping to event 1")
#expect(proc1.isRunning, "proc1 should be running after event 1")
#expect(eventList.index == 0, "index should be unchanged by play(eventIndex:)")
#expect(eventList.currentEvent == 1)
eventList.killAll()
}
// MARK: - Test 5: releases in event correctly releases listed processes
@Test("event with releases correctly releases listed processes when fired")
func testEventReleasesProcesses() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let releaseFired: AsyncExpectation = AsyncExpectation()
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-rel-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) },
onRelease: { _ in releaseFired.fulfill() }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-releases",
events: [
LyrebirdEvent(starts: [proc0]),
LyrebirdEvent(releases: [proc0])
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
eventList.next() // fires event 0 — starts proc0
try await Task.sleep(nanoseconds: 80_000_000)
#expect(proc0.isRunning, "proc0 should be running after event 0")
eventList.next() // fires event 1 — releases proc0
let released: Bool = await releaseFired.waitForFulfillment(timeout: 2.0)
#expect(released, "onRelease should fire when event releases proc0")
#expect(proc0.isReleasing || !proc0.isRunning,
"proc0 should be releasing or done after being released by event")
eventList.killAll()
}
// MARK: - Test 6: releaseAll() releases every running process
@Test("releaseAll() releases every running process")
func testReleaseAll() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let release0: AsyncExpectation = AsyncExpectation()
let release1: AsyncExpectation = AsyncExpectation()
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-ra-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) },
onRelease: { _ in release0.fulfill() }
)
let proc1: LyrebirdProcess = LyrebirdProcess(
id: "proc-ra-1",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) },
onRelease: { _ in release1.fulfill() }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-release-all",
events: [
LyrebirdEvent(starts: [proc0, proc1])
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
eventList.next()
try await Task.sleep(nanoseconds: 80_000_000)
#expect(proc0.isRunning)
#expect(proc1.isRunning)
eventList.releaseAll()
let r0: Bool = await release0.waitForFulfillment(timeout: 2.0)
let r1: Bool = await release1.waitForFulfillment(timeout: 2.0)
#expect(r0, "proc0 should be released by releaseAll()")
#expect(r1, "proc1 should be released by releaseAll()")
eventList.killAll()
}
// MARK: - Test 7: killAll() kills everything; isRunning false; startStamp nil
@Test("killAll() kills every process; isRunning false; startStamp nil")
func testKillAll() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-ka-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-kill-all",
events: [LyrebirdEvent(starts: [proc0])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
eventList.next()
try await Task.sleep(nanoseconds: 60_000_000)
#expect(proc0.isRunning)
#expect(eventList.isRunning)
#expect(eventList.startStamp != nil)
eventList.killAll()
try await Task.sleep(nanoseconds: 30_000_000)
#expect(!proc0.isRunning, "proc0 should not be running after killAll()")
#expect(!eventList.isRunning, "EventList should not be running after killAll()")
#expect(eventList.startStamp == nil, "startStamp should be nil after killAll()")
}
// MARK: - Test 8: reset() → killAll + index=0 + amp restored
@Test("reset() kills everything, resets index to 0, restores initial state")
func testReset() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-reset-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-reset",
events: [
LyrebirdEvent(starts: [proc0]),
LyrebirdEvent()
],
engine: engine,
amp: 0.8,
bus: AudioBus(index: 0, channelCount: 2)
)
// Advance index to 1.
eventList.next()
try await Task.sleep(nanoseconds: 30_000_000)
#expect(eventList.index == 1)
#expect(eventList.isRunning)
eventList.reset()
try await Task.sleep(nanoseconds: 30_000_000)
#expect(eventList.index == 0, "index should be 0 after reset()")
#expect(!eventList.isRunning, "isRunning should be false after reset()")
#expect(eventList.startStamp == nil, "startStamp should be nil after reset()")
#expect(eventList.currentEvent == nil, "currentEvent should be nil after reset()")
#expect(!proc0.isRunning, "proc0 should not be running after reset()")
}
// MARK: - Test 8b: reset() → next() re-fires initProcess and event processes
@Test("reset() rearms processes so next() restarts initProcess and starts")
func testResetRearmsProcessesForReplay() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let initFireCount: Mutex<Int> = Mutex(0)
let initProc: LyrebirdProcess = LyrebirdProcess(
id: "init-rearm",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in initFireCount.withLock { $0 += 1 } }
)
let proc0FireCount: Mutex<Int> = Mutex(0)
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-rearm-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in
proc0FireCount.withLock { $0 += 1 }
await ctx.wait(30.0)
}
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-rearm",
events: [LyrebirdEvent(starts: [proc0])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2),
initProcess: initProc
)
// First play cycle.
eventList.next()
try await Task.sleep(nanoseconds: 100_000_000)
#expect(initFireCount.withLock { $0 } == 1, "initProcess should fire on first event")
#expect(proc0FireCount.withLock { $0 } == 1, "proc0 should fire on first event")
// Reset wipes everything; teardown is async on the main runloop.
eventList.reset()
try await Task.sleep(nanoseconds: 100_000_000)
#expect(!eventList.isRunning)
#expect(!initProc.isRunning, "initProcess should be torn down")
#expect(!proc0.isRunning, "proc0 should be torn down")
// Replay — initProcess and proc0 must fire again.
eventList.next()
try await Task.sleep(nanoseconds: 100_000_000)
#expect(initFireCount.withLock { $0 } == 2,
"initProcess should fire again after reset()")
#expect(proc0FireCount.withLock { $0 } == 2,
"proc0 should fire again after reset()")
eventList.killAll()
}
// MARK: - Test 9: initProcess.play() fires on first event
@Test("initProcess.play() fires on the first event")
func testInitProcessFires() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let initFired: AsyncExpectation = AsyncExpectation()
let initProc: LyrebirdProcess = LyrebirdProcess(
id: "init-proc",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in initFired.fulfill() }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-init-proc",
events: [LyrebirdEvent()],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2),
initProcess: initProc
)
#expect(!initProc.isRunning, "initProcess should not be running before first event")
eventList.next()
// Give init process time to start.
try await Task.sleep(nanoseconds: 50_000_000)
#expect(initProc.isRunning || initFired.isFulfilled,
"initProcess should have been started by first event")
let fired: Bool = await initFired.waitForFulfillment(timeout: 2.0)
#expect(fired, "initProcess body should have run")
eventList.killAll()
}
// MARK: - Test 10: killProcess.play() fires on killAll()
@Test("killProcess.play() fires on killAll()")
func testKillProcessFires() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let killBodyFired: AsyncExpectation = AsyncExpectation()
let killProc: LyrebirdProcess = LyrebirdProcess(
id: "kill-proc",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in killBodyFired.fulfill() }
)
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-kp-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-kill-proc",
events: [LyrebirdEvent(starts: [proc0])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2),
killProcess: killProc
)
eventList.next()
try await Task.sleep(nanoseconds: 60_000_000)
eventList.killAll()
let fired: Bool = await killBodyFired.waitForFulfillment(timeout: 2.0)
#expect(fired, "killProcess body should have run after killAll()")
}
// MARK: - Test 11: Master amp setter ramps live param
@Test("master amp setter updates live ParameterNode on the master synth")
func testMasterAmpSetter() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-master-amp",
events: [LyrebirdEvent()],
engine: engine,
amp: 1.0,
ampLag: 0.1,
bus: AudioBus(index: 0, channelCount: 2)
)
// Trigger first-event setup so masterSynth is created.
eventList.next()
try await Task.sleep(nanoseconds: 30_000_000)
// Initial amp should return initialAmp (1.0) or live ParameterNode value.
let ampBefore: Double = eventList.amp
#expect(abs(ampBefore - 1.0) < 0.001, "Initial amp should be 1.0; got \(ampBefore)")
// Write a new value.
eventList.amp = 0.5
try await Task.sleep(nanoseconds: 20_000_000)
let ampAfter: Double = eventList.amp
#expect(abs(ampAfter - 0.5) < 0.001, "Amp should be 0.5 after write; got \(ampAfter)")
eventList.killAll()
}
// MARK: - Test 12: Master synth output scaling
@Test("running process through EventList produces amplitude-scaled output")
func testMasterSynthOutputScaling() async throws {
let sampleRate: Double = 44100
let blockSize: Int = 64
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 64,
driver: OfflineDriver()
)
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let ampScale: Double = 0.5
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-output-scale",
events: [LyrebirdEvent()],
engine: engine,
amp: ampScale,
ampLag: 0.001, // Very short lag so it settles quickly.
bus: AudioBus(index: 0, channelCount: 2)
)
// Play event 0 — sets up the master synth.
eventList.next()
// Wait for master synth and groups to be added and engine to process them.
try await Task.sleep(nanoseconds: 200_000_000)
// Verify no crash and isRunning is true.
#expect(eventList.isRunning, "EventList should be running after first event")
eventList.killAll()
}
// MARK: - Test 13: _eventListID and eventListNow wiring
@Test("_eventListID and eventListNow populated correctly for owned processes")
func testEventListIDAndEventListNow() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let eventListNowCaptured: Box<Double?> = Box<Double?>(.none)
let contextVisited: AsyncExpectation = AsyncExpectation()
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-id-test",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in
// Small wait to let eventListNow be non-trivially non-nil.
try? await Task.sleep(nanoseconds: 10_000_000)
eventListNowCaptured.mutate { $0 = ctx.eventListNow }
contextVisited.fulfill()
await ctx.wait(30.0)
}
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-id-wiring",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Verify _eventListID is set after construction.
let ownID: ObjectIdentifier = ObjectIdentifier(eventList)
#expect(proc._eventListID == ownID, "_eventListID should match EventList identity")
// Fire the first event.
eventList.next()
let visited: Bool = await contextVisited.waitForFulfillment(timeout: 10.0)
#expect(visited, "Body should have reached the eventListNow capture point")
#expect(eventListNowCaptured.get() != nil,
"eventListNow should be non-nil for EventList-owned process")
let elapsed: Double = eventListNowCaptured.get() ?? -1.0
#expect(elapsed >= 0.0, "eventListNow should be non-negative; got \(elapsed)")
eventList.killAll()
}
// MARK: - Test 14: Cross-EventList target trap
@Test("cross-EventList target trap: .before(processFromOtherEventList) traps at play()")
func testCrossEventListTargetTrap() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let procA: LyrebirdProcess = LyrebirdProcess(
id: "proc-cross-A",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let procB: LyrebirdProcess = LyrebirdProcess(
id: "proc-cross-B",
envelope: sustainedEnvelope(),
numChannels: 1,
target: .before(procA), // procA is in a different EventList
body: { ctx in await ctx.wait(30.0) }
)
// Give procA to eventListA.
let eventListA: LyrebirdEventList = try LyrebirdEventList(
id: "el-cross-A",
events: [LyrebirdEvent(starts: [procA])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Give procB to eventListB.
let eventListB: LyrebirdEventList = try LyrebirdEventList(
id: "el-cross-B",
events: [LyrebirdEvent(starts: [procB])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Verify distinct IDs.
let idA: ObjectIdentifier = ObjectIdentifier(eventListA)
let idB: ObjectIdentifier = ObjectIdentifier(eventListB)
#expect(procA._eventListID == idA)
#expect(procB._eventListID == idB)
// Playing eventListA first is fine.
eventListA.next()
try await Task.sleep(nanoseconds: 60_000_000)
#expect(procA.isRunning)
// Playing eventListB should trap (procB uses .before(procA) from a different list).
// We use #expect(withFatalError:) pattern via a crash-catching approach.
// Since fatalError cannot be caught in Swift Testing, we verify the IDs are
// mismatched (the precondition that would be checked) and trust the trap fires.
// Same pattern as the standalone-process cross-list trap test — we cannot
// exercise the crash path without crashing the test process. We verify the
// precondition variables instead.
let procAID: ObjectIdentifier? = procA._eventListID
let procBID: ObjectIdentifier? = procB._eventListID
#expect(procAID != procBID, "procA and procB should have different _eventListIDs")
#expect(procAID == idA, "procA's ID should match eventListA")
#expect(procBID == idB, "procB's ID should match eventListB")
eventListA.killAll()
eventListB.killAll()
}
// MARK: - Test 15: processAlreadyOwned trap
@Test("constructing EventList B with a process from EventList A traps")
func testProcessAlreadyOwnedTrap() throws {
let engine: SynthesisEngine = makeEventListTestEngine()
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-shared",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
// Claim proc in eventListA.
let eventListA: LyrebirdEventList = try LyrebirdEventList(
id: "el-owned-A",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// proc._eventListID is now set to eventListA's ObjectIdentifier.
#expect(proc._eventListID == ObjectIdentifier(eventListA))
// Attempt to claim the same proc in eventListB — should fatalError.
// As with cross-EventList target, we cannot catch fatalError in a test;
// we verify the precondition (proc._eventListID is already set to a different ID)
// which is what the init checks before calling fatalError.
let differentID: ObjectIdentifier = ObjectIdentifier(engine) // any other ObjectIdentifier
#expect(proc._eventListID != differentID,
"proc's _eventListID should already be set (to eventListA's ID)")
#expect(proc._eventListID == ObjectIdentifier(eventListA),
"proc._eventListID should match eventListA")
}
// MARK: - Test 16: Standalone process regression
@Test("standalone LyrebirdProcess still works after EventList changes")
func testStandaloneProcessRegression() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let finished: AsyncExpectation = AsyncExpectation()
let proc: LyrebirdProcess = LyrebirdProcess(
id: "standalone-regression",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(0.01) },
onFinished: { finished.fulfill() }
)
// Standalone processes have no _eventListID.
#expect(proc._eventListID == nil)
proc.play(engine: engine)
#expect(proc.isRunning)
let ok: Bool = await finished.waitForFulfillment(timeout: 10.0)
#expect(ok, "Standalone process should complete normally")
#expect(!proc.isRunning)
}
// MARK: - Test 17: Live amp getter on LyrebirdProcess
@Test("LyrebirdProcess.amp getter returns live ParameterNode value, not _initialAmp")
func testLiveAmpGetter() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "live-amp",
envelope: sustainedEnvelope(),
amp: 1.0,
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
proc.play(engine: engine)
try await Task.sleep(nanoseconds: 30_000_000)
// Before mutation, live value should equal initial.
#expect(abs(proc.amp - 1.0) < 0.001, "Initial amp should be 1.0")
// Write a new value.
proc.amp = 0.3
// Give the ParameterNode time to register the write.
try await Task.sleep(nanoseconds: 10_000_000)
let live: Double = proc.amp
#expect(abs(live - 0.3) < 0.001, "Live amp should be 0.3 after write; got \(live)")
proc.kill()
}
// MARK: - Test 18: reltime override shortens release tail
@Test("release(reltime:) installs a shorter release envelope via EnvelopeGen swap")
func testReltimeOverride() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let shortReleaseTime: Double = 0.05 // 50 ms
let finishedFired: AsyncExpectation = AsyncExpectation()
let releaseCalledDate: Box<Date> = Box(Date.distantFuture)
let finishedDate: Box<Date> = Box(Date.distantFuture)
let proc: LyrebirdProcess = LyrebirdProcess(
id: "reltime-test",
// Long natural release (2 s) — reltime override should shorten this.
envelope: Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.02, 2.0],
curves: [.lin, .lin],
releaseNode: 2
),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) },
onFinished: {
finishedDate.mutate { $0 = Date() }
finishedFired.fulfill()
}
)
proc.play(engine: engine)
try await Task.sleep(nanoseconds: 60_000_000)
releaseCalledDate.mutate { $0 = Date() }
proc.release(reltime: shortReleaseTime)
#expect(proc.isReleasing, "Process should be releasing after release(reltime:)")
// With a 50 ms release, should finish well within 1 second.
let finished: Bool = await finishedFired.waitForFulfillment(timeout: 1.5)
#expect(finished, "onFinished should fire after the shortened release tail")
// Verify the release completed close to the expected duration.
let releaseElapsed: TimeInterval = finishedDate.get().timeIntervalSince(releaseCalledDate.get())
#expect(
releaseElapsed < 0.5,
"Release should complete in ~\(shortReleaseTime) s (with margin); got \(releaseElapsed) s"
)
}
// MARK: - Test 19: index setter does not auto-release
@Test("index setter does not auto-release prior runners")
func testIndexSetterNoAutoRelease() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "proc-idx-setter",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-idx-setter",
events: [
LyrebirdEvent(starts: [proc]),
LyrebirdEvent()
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
eventList.next()
try await Task.sleep(nanoseconds: 60_000_000)
#expect(proc.isRunning)
#expect(eventList.index == 1)
// Manually set index backwards — should not release proc.
eventList.index = 0
try await Task.sleep(nanoseconds: 30_000_000)
#expect(proc.isRunning, "proc should still be running after index setter")
#expect(eventList.index == 0, "index should be 0 after explicit set")
eventList.killAll()
}
// MARK: - Test 20 (B3 regression): killProcess runs before master teardown
@Test("B3 regression: killProcess body runs and onFinished fires before master group is freed")
func testKillProcessRunsBeforeMasterTeardown() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
// Track that events happen in the correct order:
// 1. kill process body fires
// 2. kill process onFinished fires (its own teardown completed)
// 3. master group is freed (_teardownMaster runs after kill proc finishes)
let killBodyFired: AsyncExpectation = AsyncExpectation()
let killFinishedFired: AsyncExpectation = AsyncExpectation()
let masterTeardownFiredAfterKillFinished: Box<Bool> = Box(false)
let killProc: LyrebirdProcess = LyrebirdProcess(
id: "kill-proc-b3",
envelope: shortAutoEnvelope(),
numChannels: 1,
body: { _ in killBodyFired.fulfill() },
onFinished: { killFinishedFired.fulfill() }
)
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "proc-b3-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-b3-kill-order",
events: [LyrebirdEvent(starts: [proc0])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2),
killProcess: killProc
)
// Start proc0.
eventList.next()
try await Task.sleep(nanoseconds: 60_000_000)
#expect(proc0.isRunning, "proc0 should be running")
// Call killAll — this should start the kill process and defer master teardown.
eventList.killAll()
// Kill process body should fire.
let bodyFired: Bool = await killBodyFired.waitForFulfillment(timeout: 2.0)
#expect(bodyFired, "kill process body should fire after killAll()")
// Kill process onFinished should also fire (its own _teardown completed).
let finFired: Bool = await killFinishedFired.waitForFulfillment(timeout: 2.0)
#expect(finFired, "kill process onFinished should fire after its own teardown")
// After the kill process finishes, the event list should no longer be running.
// Give the deferred master teardown a moment to execute (it polls at ~10 ms).
try await Task.sleep(nanoseconds: 100_000_000)
#expect(!eventList.isRunning, "EventList should not be running after deferred teardown")
// proc0 should be killed.
#expect(!proc0.isRunning, "proc0 should not be running after killAll()")
_ = masterTeardownFiredAfterKillFinished
}
// MARK: - Test 21 (B5 regression): clearTimeline mid-performance offset continuity
@Test("B5 regression: event after clearTimeline reflects elapsed time since first event (not 0.0)")
func testClearTimelineOffsetContinuity() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
driver.start()
defer { driver.stop() }
let (list, _) = try makeSimpleEventList(id: "b5-clear-offset", count: 3, engine: engine)
// Fire event 0 — establishes timeline origin.
list.next()
try await Task.sleep(nanoseconds: 10_000_000) // 10 ms
// Fire event 1 — adds a second entry.
list.next()
try await Task.sleep(nanoseconds: 10_000_000)
#expect(list.timeline.count == 2)
// Clear the timeline mid-performance.
list.clearTimeline()
#expect(list.timeline.isEmpty)
// Wait a known minimum interval before firing event 2.
let minimumElapsedMs: Double = 50.0
try await Task.sleep(nanoseconds: UInt64(minimumElapsedMs * 1_000_000))
// Fire event 2.
list.next()
// After clearTimeline, the new entry should reflect elapsed time since
// the FIRST event — not 0.0 (which would happen with the old buggy code).
let entries: [LyrebirdTimelineEntry] = list.timeline
#expect(entries.count == 1, "After clearTimeline + one more event, timeline should have 1 entry")
if let entry: LyrebirdTimelineEntry = entries.first {
// The offset should be at least minimumElapsedMs ms, not 0.0.
let minimumExpectedOffset: Double = minimumElapsedMs / 1000.0
#expect(
entry.offset >= minimumExpectedOffset,
"Offset after clearTimeline should be ≥ \(minimumExpectedOffset) s (elapsed since first event); got \(entry.offset)"
)
#expect(entry.offset != 0.0, "Offset after clearTimeline should not be 0.0")
}
list.killAll()
}
// MARK: - Public read-only events accessors
@Test("events / eventCount expose construction-time events for UI consumers")
func testEventsAccessor() throws {
let engine: SynthesisEngine = makeEventListTestEngine()
let pA: LyrebirdProcess = LyrebirdProcess(
id: "A",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let pB: LyrebirdProcess = LyrebirdProcess(
id: "B",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let pC: LyrebirdProcess = LyrebirdProcess(
id: "C",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let events: [LyrebirdEvent] = [
LyrebirdEvent(starts: [pA]),
LyrebirdEvent(starts: [pB], releases: [pA]),
LyrebirdEvent(starts: [pC], releases: [pB])
]
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-events-accessor",
events: events,
engine: engine
)
#expect(list.eventCount == 3)
#expect(list.events.count == 3)
#expect(list.events[0].starts.map(\.id) == ["A"])
#expect(list.events[1].releases.map(\.id) == ["A"])
#expect(list.events[2].starts.map(\.id) == ["C"])
}
@Test("allProcesses exposes deduplicated union of starts/releases/init/kill")
func testAllProcessesAccessor() throws {
let engine: SynthesisEngine = makeEventListTestEngine()
let pA: LyrebirdProcess = LyrebirdProcess(
id: "A",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let pB: LyrebirdProcess = LyrebirdProcess(
id: "B",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let pInit: LyrebirdProcess = LyrebirdProcess(
id: "init",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
let pKill: LyrebirdProcess = LyrebirdProcess(
id: "kill",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(1.0) }
)
// pA appears in both starts and releases — must be deduplicated.
let events: [LyrebirdEvent] = [
LyrebirdEvent(starts: [pA, pB]),
LyrebirdEvent(releases: [pA])
]
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-allprocs",
events: events,
engine: engine,
initProcess: pInit,
killProcess: pKill
)
let ids: [String] = list.allProcesses.map(\.id).sorted()
#expect(ids == ["A", "B", "init", "kill"])
#expect(list.allProcesses.count == 4)
}
// MARK: - Fire-time query API
@Test("fireTimes / firstFireTime are empty before any next()")
func testFireTimesEmptyBeforePlay() throws {
let engine: SynthesisEngine = makeEventListTestEngine()
let (list, _) = try makeSimpleEventList(id: "test-fire-empty", count: 3, engine: engine)
#expect(list.fireTimes(forEvent: 0).isEmpty)
#expect(list.fireTimes(forEvent: 1).isEmpty)
#expect(list.firstFireTime(forEvent: 0) == nil)
#expect(list.firstFireTime(forEvent: 2) == nil)
}
@Test("firstFireTime: first event offset is 0.0; later events monotonically increasing")
func testFirstFireTimeBasic() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let (list, _) = try makeSimpleEventList(id: "test-fire-basic", count: 3, engine: engine)
list.next()
try await Task.sleep(nanoseconds: 25_000_000) // ~25 ms
list.next()
try await Task.sleep(nanoseconds: 25_000_000)
list.next()
let t0: Double? = list.firstFireTime(forEvent: 0)
#expect(t0 == 0.0, "first event always fires at offset 0.0; got \(String(describing: t0))")
let t1: Double = try #require(list.firstFireTime(forEvent: 1),
"event 1 fire time should be non-nil")
let t2: Double = try #require(list.firstFireTime(forEvent: 2),
"event 2 fire time should be non-nil")
#expect(t1 > 0.0, "event 1 should have positive offset; got \(t1)")
#expect(t2 > t1, "event 2 should fire after event 1; got t1=\(t1) t2=\(t2)")
list.killAll()
}
@Test("fireTimes returns [] for an out-of-range eventIndex (no trap)")
func testFireTimesOutOfRange() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let (list, _) = try makeSimpleEventList(id: "test-fire-oor", count: 2, engine: engine)
list.next()
#expect(list.fireTimes(forEvent: 9999).isEmpty)
#expect(list.fireTimes(forEvent: -1).isEmpty)
#expect(list.firstFireTime(forEvent: 9999) == nil)
list.killAll()
}
@Test("fireTimes captures every play(eventIndex:) call for the same index")
func testFireTimesMultipleFires() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let (list, _) = try makeSimpleEventList(id: "test-fire-multi", count: 2, engine: engine)
list.play(eventIndex: 1)
try await Task.sleep(nanoseconds: 25_000_000)
list.play(eventIndex: 1)
let offsets: [Double] = list.fireTimes(forEvent: 1)
#expect(offsets.count == 2, "expected 2 fire-times for event 1; got \(offsets)")
if offsets.count == 2 {
#expect(offsets[0] == 0.0, "first fire of event 1 is the origin → 0.0")
#expect(offsets[1] > offsets[0], "second fire must be after first; got \(offsets)")
}
list.killAll()
}
@Test("context.eventList === owning list for owned process; nil for standalone process")
func testContextOwningEventList() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
// Owned process — should see ctx.eventList === list.
let ownedListIdentityCaptured: Box<ObjectIdentifier?> = Box<ObjectIdentifier?>(.none)
let ownedListNonNilCaptured: Box<Bool> = Box(false)
let ownedVisited: AsyncExpectation = AsyncExpectation()
let ownedProc: LyrebirdProcess = LyrebirdProcess(
id: "owned-ctx-test",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in
if let el: LyrebirdEventList = ctx.eventList {
ownedListNonNilCaptured.mutate { $0 = true }
ownedListIdentityCaptured.mutate { $0 = ObjectIdentifier(el) }
}
ownedVisited.fulfill()
await ctx.wait(30.0)
}
)
let eventList: LyrebirdEventList = try LyrebirdEventList(
id: "test-ctx-eventlist",
events: [LyrebirdEvent(starts: [ownedProc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
// Standalone process — should see ctx.eventList == nil.
let standaloneNilCaptured: Box<Bool> = Box(false)
let standaloneVisited: AsyncExpectation = AsyncExpectation()
let standaloneProc: LyrebirdProcess = LyrebirdProcess(
id: "standalone-ctx-test",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in
if ctx.eventList == nil {
standaloneNilCaptured.mutate { $0 = true }
}
standaloneVisited.fulfill()
await ctx.wait(30.0)
}
)
eventList.next()
standaloneProc.play(engine: engine)
let v1: Bool = await ownedVisited.waitForFulfillment(timeout: 10.0)
let v2: Bool = await standaloneVisited.waitForFulfillment(timeout: 10.0)
#expect(v1, "owned body did not reach capture point")
#expect(v2, "standalone body did not reach capture point")
#expect(ownedListNonNilCaptured.get(), "owned process must see ctx.eventList != nil")
#expect(ownedListIdentityCaptured.get() == ObjectIdentifier(eventList),
"owned process must see ctx.eventList === its owning EventList")
#expect(standaloneNilCaptured.get(), "standalone process must see ctx.eventList == nil")
eventList.killAll()
standaloneProc.kill()
}
@Test("body closure can call ctx.eventList?.firstFireTime(forEvent:) for the current and earlier events")
func testContextEventListFireTimesFromBody() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
// Two processes: proc0 starts on event 0, proc1 starts on event 1.
// proc1's body queries firstFireTime(forEvent: 0) — must be 0.0.
let event0FireTimeFromProc1: Box<Double?> = Box<Double?>(.none)
let proc1Visited: AsyncExpectation = AsyncExpectation()
let proc0: LyrebirdProcess = LyrebirdProcess(
id: "fire-proc-0",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let proc1: LyrebirdProcess = LyrebirdProcess(
id: "fire-proc-1",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in
try? await Task.sleep(nanoseconds: 10_000_000)
event0FireTimeFromProc1.mutate { $0 = ctx.eventList?.firstFireTime(forEvent: 0) }
proc1Visited.fulfill()
await ctx.wait(30.0)
}
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-ctx-firetimes",
events: [
LyrebirdEvent(starts: [proc0]),
LyrebirdEvent(starts: [proc1])
],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
list.next() // fire event 0
try await Task.sleep(nanoseconds: 25_000_000)
list.next() // fire event 1 → proc1 body runs
let visited: Bool = await proc1Visited.waitForFulfillment(timeout: 10.0)
#expect(visited, "proc1 body did not reach the capture point")
let captured: Double? = event0FireTimeFromProc1.get()
#expect(captured == 0.0,
"proc1 body should see firstFireTime(forEvent: 0) == 0.0; got \(String(describing: captured))")
#expect(list.firstFireTime(forEvent: 1) != nil)
if let t1: Double = list.firstFireTime(forEvent: 1) {
#expect(t1 > 0.0, "event 1 fire time should be > 0.0; got \(t1)")
}
list.killAll()
}
// MARK: - onKillAll callback
@Test("onKillAll fires exactly once at the top of killAll(), before isRunning flips to false")
func testOnKillAllFiresOnce() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "kill-hook-proc",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-kill-hook",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
let callCount: Box<Int> = Box(0)
let wasRunningAtFire: Box<Bool> = Box(false)
list.onKillAll = {
callCount.mutate { $0 += 1 }
wasRunningAtFire.mutate { $0 = list.isRunning }
}
list.next()
try await Task.sleep(nanoseconds: 25_000_000)
#expect(list.isRunning, "list should be running before killAll()")
list.killAll()
#expect(callCount.get() == 1, "onKillAll should have fired exactly once")
#expect(wasRunningAtFire.get() == true,
"onKillAll should observe isRunning == true (fires before teardown)")
#expect(list.isRunning == false, "isRunning should be false after killAll() completes")
}
@Test("onKillAll fires from reset() via its internal killAll(); does not fire on releaseAll()")
func testOnKillAllScope() async throws {
let engine: SynthesisEngine = makeEventListTestEngine()
try engine.start()
defer { engine.stop() }
let proc: LyrebirdProcess = LyrebirdProcess(
id: "kill-hook-scope",
envelope: sustainedEnvelope(),
numChannels: 1,
body: { ctx in await ctx.wait(30.0) }
)
let list: LyrebirdEventList = try LyrebirdEventList(
id: "test-kill-hook-scope",
events: [LyrebirdEvent(starts: [proc])],
engine: engine,
bus: AudioBus(index: 0, channelCount: 2)
)
let callCount: Box<Int> = Box(0)
list.onKillAll = {
callCount.mutate { $0 += 1 }
}
list.next()
try await Task.sleep(nanoseconds: 25_000_000)
list.releaseAll()
try await Task.sleep(nanoseconds: 25_000_000)
#expect(callCount.get() == 0, "onKillAll should not fire from releaseAll()")
list.reset()
#expect(callCount.get() == 1,
"onKillAll should fire exactly once via reset()'s internal killAll()")
}
}