// LyrebirdAudioUnitMultiBusTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation import AudioToolbox import AVFoundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // MARK: - Multi-output-bus fixture private final class StemRenderSynth: SynthesizerBase { @LiveParam var gainA: Double = 0.5 @LiveParam var gainB: Double = 0.5 override func build() { // Bus 0 (main, 2ch): channels 0+1 output(bus: 0, source: $gainA) output(bus: 1, source: $gainA) // Bus 1 (aux, 2ch): channels 2+3 output(bus: 2, source: $gainB) output(bus: 3, source: $gainB) } } private final class StemRenderAU: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { StemRenderSynth() } public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] { [ .init(name: "Main", channelCount: 2), .init(name: "FX Send", channelCount: 2), ] } } // MARK: - Multi-input-bus (main + sidechain) fixture private final class SidechainPassthrough: SynthesizerBase { override func build() { // Main input bus 0 → output bus 0 (passthrough) let mainL: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 0) let mainR: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 1) output(bus: 0, source: mainL) output(bus: 1, source: mainR) } } private final class SidechainAU: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { SidechainPassthrough() } public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] { [.init(name: "Output", channelCount: 2)] } public override class var lyrebirdInputBusses: [LyrebirdAUBusSpec] { [ .init(name: "Main In", channelCount: 2), .init(name: "Sidechain", channelCount: 2), ] } } // MARK: - Single-bus back-compat fixture private final class SingleBusSynth: SynthesizerBase { override func build() { output(bus: 0, source: 0.0) } } private final class SingleBusAU: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { SingleBusSynth() } // No bus-spec overrides — must keep the default single-bus behaviour. } private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription { AudioComponentDescription( componentType: kAudioUnitType_MusicDevice, componentSubType: subtype, componentManufacturer: 0x524C5A53, componentFlags: 0, componentFlagsMask: 0 ) } @Suite("LyrebirdAudioUnit multi-bus — defaults") struct LyrebirdAudioUnitMultiBusDefaultTests { @Test func singleBusAUKeeps104aShape() throws { let au: SingleBusAU = try SingleBusAU(componentDescription: makeAUDesc(subtype: 0x53424102)) #expect(au.outputBusses.count == 1) #expect(au.inputBusses.count == 0) try au.allocateRenderResources() defer { au.deallocateRenderResources() } let engine: SynthesisEngine = try #require(au.engine) #expect(engine.numOutputChannels == 2) #expect(engine.numInputChannels == 0) #expect(engine.auOutputBusOffsets == [0]) #expect(engine.auInputBusOffsets == []) } } @Suite("LyrebirdAudioUnit multi-bus — multi-output") struct LyrebirdAudioUnitMultiOutputBusTests { @Test func twoOutputBussesAreExposed() throws { let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F42)) #expect(au.outputBusses.count == 2) #expect(au.outputBusses[0].format.channelCount == 2) #expect(au.outputBusses[1].format.channelCount == 2) // Bus names are reflected via the format's channel layout name — // the spec name itself is internal, so just confirm bus instances exist. } @Test func twoOutputBussesEngineLayout() throws { let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F43)) try au.allocateRenderResources() defer { au.deallocateRenderResources() } let engine: SynthesisEngine = try #require(au.engine) // 2 + 2 channels across two output busses. #expect(engine.numOutputChannels == 4) // Bus 0 starts at engine channel 0; bus 1 at engine channel 2. #expect(engine.auOutputBusOffsets == [0, 2]) } @Test func asymmetricBusPullsDoNotCrash() throws { // AU spec lets a host pull bus 0 repeatedly without pulling bus 1. // Without the driver's saturation guard this would overflow bus 1's // ring buffer after `capacity / blockSize` engine advances. // Verify many pulls of bus 0 with zero pulls of bus 1 stay safe. let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x53415359)) try au.allocateRenderResources() defer { au.deallocateRenderResources() } let frames: Int = 64 let fixture: ABLFixture = makeABL(channels: 2, frames: frames) defer { deallocateABL(fixture) } var flags: AudioUnitRenderActionFlags = [] var ts: AudioTimeStamp = AudioTimeStamp() ts.mFlags = .sampleTimeValid ts.mSampleTime = 0 let block: AUInternalRenderBlock = au.internalRenderBlock // 64 pulls of bus 0 — more than the ring capacity / blockSize. With // the saturation guard in place, the driver resets bus 1's ring // when it would overflow rather than tripping a precondition. for _ in 0..<64 { let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0, fixture.abl, nil, nil) #expect(status == noErr) ts.mSampleTime += Float64(frames) } // Now pull bus 1 once — should succeed (returns the freshest block, // not the long-stale data dropped by saturation). let fixtureB: ABLFixture = makeABL(channels: 2, frames: frames) defer { deallocateABL(fixtureB) } let statusB: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 1, fixtureB.abl, nil, nil) #expect(statusB == noErr) } @Test func renderingRoutesEachBusIndependently() throws { let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F44)) try au.allocateRenderResources() defer { au.deallocateRenderResources() } let synth: StemRenderSynth = try #require(au.synthesizer as? StemRenderSynth) synth.gainA = 0.25 synth.gainB = 0.75 let frames: Int = 64 let fixtureA: ABLFixture = makeABL(channels: 2, frames: frames) let fixtureB: ABLFixture = makeABL(channels: 2, frames: frames) defer { deallocateABL(fixtureA); deallocateABL(fixtureB) } var flags: AudioUnitRenderActionFlags = [] var ts: AudioTimeStamp = AudioTimeStamp() ts.mFlags = .sampleTimeValid ts.mSampleTime = 0 let block: AUInternalRenderBlock = au.internalRenderBlock // Render multiple cycles so the @LiveParam ramp completes (default // engine blockSize 256, so ≥ 4 × 64-frame renders reach the // steady-state gain). Check the LAST sample of each bus's ABL on // the final cycle. let cycles: Int = 8 for _ in 0.. = UnsafeMutablePointer.allocate(capacity: 1) let countSC: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: 1) countMain.initialize(to: 0) countSC.initialize(to: 0) defer { countMain.deinitialize(count: 1); countMain.deallocate() countSC.deinitialize(count: 1); countSC.deallocate() } let pull: AURenderPullInputBlock = { _, _, inFrames, inputBusNumber, inputData in switch inputBusNumber { case 0: countMain.pointee += 1 case 1: countSC.pointee += 1 default: break } let abl: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(inputData) let fillValue: Float = inputBusNumber == 0 ? 1.0 : -1.0 for c: Int in 0.. = raw.assumingMemoryBound(to: Float.self) for i: Int in 0.. 0, "main input bus pullInputBlock should be called") #expect(countSC.pointee > 0, "sidechain input bus pullInputBlock should be called") } @Test func auInputBusIndexResolves() throws { let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E34)) try au.allocateRenderResources() defer { au.deallocateRenderResources() } let engine: SynthesisEngine = try #require(au.engine) // Seed engine input buses directly: main = +1 ramp; sidechain = -1 ramp. for i: Int in 0.. let channelStorage: [UnsafeMutablePointer] } private func makeABL(channels: Int, frames: Int) -> ABLFixture { let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels) let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate( byteCount: size, alignment: MemoryLayout.alignment ) let abl: UnsafeMutablePointer = raw.assumingMemoryBound(to: AudioBufferList.self) let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl) listPtr.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(channels) var storage: [UnsafeMutablePointer] = [] for c: Int in 0.. = UnsafeMutablePointer.allocate(capacity: frames) for i: Int in 0...size), mData: UnsafeMutableRawPointer(p) ) } return ABLFixture(abl: abl, channelStorage: storage) } private func deallocateABL(_ fixture: ABLFixture) { for p: UnsafeMutablePointer in fixture.channelStorage { p.deallocate() } UnsafeMutableRawPointer(fixture.abl).deallocate() }