// LyrebirdAUVoicePoolBindingTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth private final class TestVoice: SynthesizerBase { @LiveParam var freq: Double = 0 @LiveParam var amp: Double = 0 @LiveParam var gate: Double = 0 override func build() { output(bus: 0, source: $freq * $amp * $gate) } } @MainActor @Suite("LyrebirdAUVoicePoolBinding") struct LyrebirdAUVoicePoolBindingTests { @Test func noteOnAllocatesVoiceAndConfigures() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64) try engine.start() defer { engine.stop() } let pool: VoicePool = try VoicePool( voiceCount: 4, group: engine.rootGroup, engine: engine, factory: { TestVoice() } ) let binding: LyrebirdAUVoicePoolBinding = LyrebirdAUVoicePoolBinding(pool: pool) { voice, note, velocity in voice.freq = Double(note) voice.amp = velocity voice.gate = 1 } binding.handle(message: .noteOn(channel: 0, note: 60, velocity: 100), sampleTime: 0) // Walk the voices array — exactly one voice should have freq == 60. let activeCount: Int = pool.voices.filter { $0.gate == 1 && $0.freq == 60 }.count #expect(activeCount == 1) let voice: TestVoice = try #require(pool.voices.first(where: { $0.freq == 60 })) #expect(abs(voice.amp - Double(100) / Double(midiVelocityMax)) < 1e-6) } @Test func noteOffRunsConfigureForAllVoices() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64) try engine.start() defer { engine.stop() } let pool: VoicePool = try VoicePool( voiceCount: 2, group: engine.rootGroup, engine: engine, factory: { TestVoice() } ) var noteOffCount: Int = 0 let binding: LyrebirdAUVoicePoolBinding = LyrebirdAUVoicePoolBinding(pool: pool) { voice, _, _ in voice.gate = 1 } noteOff: { voice, _ in voice.gate = 0 noteOffCount += 1 } binding.handle(message: .noteOn(channel: 0, note: 60, velocity: 90), sampleTime: 0) binding.handle(message: .noteOff(channel: 0, note: 60, velocity: 0), sampleTime: 0) // Note-off configure fires once per voice (104c documented behaviour). #expect(noteOffCount == 2) #expect(pool.voices.allSatisfy { $0.gate == 0 }) } @Test func channelFilterRespectsValue() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64) try engine.start() defer { engine.stop() } let pool: VoicePool = try VoicePool( voiceCount: 2, group: engine.rootGroup, engine: engine, factory: { TestVoice() } ) let binding: LyrebirdAUVoicePoolBinding = LyrebirdAUVoicePoolBinding( pool: pool, channelFilter: 0, noteOn: { voice, note, _ in voice.freq = Double(note) } ) binding.handle(message: .noteOn(channel: 1, note: 60, velocity: 100), sampleTime: 0) // Filtered out — no voice should have been touched. #expect(pool.voices.allSatisfy { $0.freq == 0 }) binding.handle(message: .noteOn(channel: 0, note: 72, velocity: 100), sampleTime: 0) #expect(pool.voices.contains(where: { $0.freq == 72 })) } }