Files
Lyrebird/Tests/LyrebirdTests/AUv3/LyrebirdAudioUnitMultiBusTests.swift
T

352 lines
15 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.
// 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 { MainActor.assumeIsolated { 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 { MainActor.assumeIsolated { 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 { MainActor.assumeIsolated { 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
)
}
@MainActor
@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 == [])
}
}
@MainActor
@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 {
defer { lyrebirdClearRTMarkAfterTestRender() }
// 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 {
defer { lyrebirdClearRTMarkAfterTestRender() }
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..<cycles {
let statusA: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0,
fixtureA.abl, nil, nil)
let statusB: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 1,
fixtureB.abl, nil, nil)
#expect(statusA == noErr)
#expect(statusB == noErr)
ts.mSampleTime += Float64(frames)
}
let lastA: Float = fixtureA.channelStorage[0][frames - 1]
let lastB: Float = fixtureB.channelStorage[0][frames - 1]
// Allow some tolerance for the ramp tail.
#expect(abs(Double(lastA) - 0.25) < 0.05,
"bus 0 final sample should be near 0.25, got \(lastA)")
#expect(abs(Double(lastB) - 0.75) < 0.05,
"bus 1 final sample should be near 0.75, got \(lastB)")
}
}
@MainActor
@Suite("LyrebirdAudioUnit multi-bus — sidechain input") struct LyrebirdAudioUnitSidechainTests {
@Test func twoInputBussesAreExposed() throws {
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E32))
#expect(au.inputBusses.count == 2)
#expect(au.inputBusses[0].format.channelCount == 2)
#expect(au.inputBusses[1].format.channelCount == 2)
}
@Test func sidechainEngineOffsetMapPopulated() throws {
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E33))
try au.allocateRenderResources()
defer { au.deallocateRenderResources() }
let engine: SynthesisEngine = try #require(au.engine)
#expect(engine.numInputChannels == 4)
// Main In at engine bus 2, Sidechain at engine bus 4.
#expect(engine.auInputBusOffsets == [2, 4])
}
@Test func renderLoopDispatchesPerInputBusPullBlock() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// Drive the full internalRenderBlock → driver → _fillInputStagingFromHost
// path with a synthetic pullInputBlock that fills bus 0 ABL with +1.0
// and bus 1 ABL with -1.0. Verify the AU passes bus 0 samples through
// to its output (SidechainPassthrough's build wires bus 0 → output).
let au: SidechainAU = try SidechainAU(componentDescription: makeAUDesc(subtype: 0x53494E50))
try au.allocateRenderResources()
defer { au.deallocateRenderResources() }
let frames: Int = 64
let fixture: ABLFixture = makeABL(channels: 2, frames: frames)
defer { deallocateABL(fixture) }
// Synthetic pullInputBlock fills bus N's ABL based on the bus number.
// Heap-allocated Int counters captured by raw pointer so the
// @convention(block) closure can mutate them.
let countMain: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.allocate(capacity: 1)
let countSC: UnsafeMutablePointer<Int> = UnsafeMutablePointer<Int>.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..<abl.count {
guard let raw: UnsafeMutableRawPointer = abl[c].mData else { continue }
let dst: UnsafeMutablePointer<Float> = raw.assumingMemoryBound(to: Float.self)
for i: Int in 0..<Int(inFrames) { dst[i] = fillValue }
}
return noErr
}
var flags: AudioUnitRenderActionFlags = []
var ts: AudioTimeStamp = AudioTimeStamp()
ts.mFlags = .sampleTimeValid
ts.mSampleTime = 0
let block: AUInternalRenderBlock = au.internalRenderBlock
// 8 render cycles so the @LiveParam ramps complete and the
// passthrough output converges on the input value.
for _ in 0..<8 {
let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0,
fixture.abl, nil, pull)
#expect(status == noErr)
ts.mSampleTime += Float64(frames)
}
// Output should track bus 0's +1.0 (main input passthrough), not
// bus 1's -1.0 (sidechain).
let lastSample: Float = fixture.channelStorage[0][frames - 1]
#expect(abs(Double(lastSample) - 1.0) < 0.05,
"main-input passthrough should converge on 1.0, got \(lastSample)")
// Both input busses must be pulled at least once.
#expect(countMain.pointee > 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..<engine.blockSize {
engine.audioBuses[2][i] = Float(i)
engine.audioBuses[3][i] = Float(i)
engine.audioBuses[4][i] = -Float(i)
engine.audioBuses[5][i] = -Float(i)
}
let mainGen: AUInput.Audio = AUInput.Audio(busIndex: 0, channel: 0)
let scGen: AUInput.Audio = AUInput.Audio(busIndex: 1, channel: 0)
let graph: SynthGraph = makeSynthGraph(engine: engine)
let mainOut: [[Double]] = mainGen._computeSamples(graph: graph, count: 32)
let scOut: [[Double]] = scGen._computeSamples(graph: graph, count: 32)
#expect(mainOut[0][10] == Double(10))
#expect(scOut[0][10] == Double(-10))
}
}
// MARK: - ABL helpers (mirrors AUv3DriverTests fixture)
private struct ABLFixture {
let abl: UnsafeMutablePointer<AudioBufferList>
let channelStorage: [UnsafeMutablePointer<Float>]
}
private func makeABL(channels: Int, frames: Int) -> ABLFixture {
let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels)
let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(
byteCount: size,
alignment: MemoryLayout<AudioBufferList>.alignment
)
let abl: UnsafeMutablePointer<AudioBufferList> = raw.assumingMemoryBound(to: AudioBufferList.self)
let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl)
listPtr.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(channels)
var storage: [UnsafeMutablePointer<Float>] = []
for c: Int in 0..<channels {
let p: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: frames)
for i: Int in 0..<frames { p[i] = 0 }
storage.append(p)
listPtr[c] = AudioBuffer(
mNumberChannels: 1,
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
mData: UnsafeMutableRawPointer(p)
)
}
return ABLFixture(abl: abl, channelStorage: storage)
}
private func deallocateABL(_ fixture: ABLFixture) {
for p: UnsafeMutablePointer<Float> in fixture.channelStorage { p.deallocate() }
UnsafeMutableRawPointer(fixture.abl).deallocate()
}