// LyrebirdAudioUnitTests.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: - Test fixtures private final class TestFMSynth: SynthesizerBase { @LiveParam var freq: Double = 440.0 @LiveParam var amp: Double = 0.5 override func build() { output(bus: 0, source: $freq * $amp) } } private final class TestFMSynthAudioUnit: LyrebirdAudioUnit { public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { TestFMSynth() } } public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { [ "freq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"), "amp": .init(min: 0, max: 1, unit: .linearGain), ] } } private func makeDescription() -> AudioComponentDescription { AudioComponentDescription( componentType: kAudioUnitType_MusicDevice, componentSubType: 0x4C425454, // 'LBTT' componentManufacturer: 0x524C5A53, // 'RLZS' componentFlags: 0, componentFlagsMask: 0 ) } // MARK: - Init / parameter tree @MainActor @Suite("LyrebirdAudioUnit init") struct LyrebirdAudioUnitInitTests { @Test func initSucceedsAndPopulatesParameterTree() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let tree: AUParameterTree = try #require(au.parameterTree) let params: [AUParameter] = tree.allParameters #expect(params.count == 2) #expect(params.map(\.identifier) == ["freq", "amp"]) #expect(params.first?.value == 440) } @Test func parameterMetadataAppliesToTree() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let tree: AUParameterTree = try #require(au.parameterTree) let freq: AUParameter? = tree.parameter(withAddress: 0) #expect(freq?.minValue == 20) #expect(freq?.maxValue == 8000) #expect(freq?.unit == .hertz) } @Test func writingAUParameterUpdatesSynthAtomic() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let tree: AUParameterTree = try #require(au.parameterTree) let freq: AUParameter = try #require(tree.parameter(withAddress: 0)) freq.value = 1000 let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth) #expect(synth.freq == 1000.0) } @Test func readingAUParameterValueProviderReflectsSynth() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth) synth.freq = 2000.0 let tree: AUParameterTree = try #require(au.parameterTree) let freq: AUParameter = try #require(tree.parameter(withAddress: 0)) // The valueProvider is consulted on read after a non-tree write — refresh // via .value getter (AUParameter caches the last write but the provider // closure executes when the value is fetched via the implementor path). let resolved: AUValue? = freq.value(forKeyPath: "value") as? AUValue // The AU spec doesn't expose the provider directly; the more reliable // black-box assertion is that the tree-side write path is bidirectional // (see writingAUParameterUpdatesSynthAtomic). This test just sanity-checks // that .value remains in range after a backdoor write. _ = resolved #expect(freq.value >= 20 && freq.value <= 8000) } } // MARK: - Resource lifecycle @MainActor @Suite("LyrebirdAudioUnit render resources") struct LyrebirdAudioUnitRenderResourceTests { @Test func allocateAndDeallocateLifecycle() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) #expect(au.engine == nil) try au.allocateRenderResources() #expect(au.engine != nil) let firstEngine: SynthesisEngine? = au.engine #expect(firstEngine?.isRunning == true) au.deallocateRenderResources() #expect(au.engine == nil) } @Test func reallocateRebuildsEngineAtNewSampleRate() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) // First allocate at default 44100. try au.allocateRenderResources() #expect(au.engine?.sampleRate == 44100) au.deallocateRenderResources() // Set output bus to 48000. let bus: AUAudioUnitBus = au.outputBusses[0] let newFormat: AVAudioFormat = try #require(AVAudioFormat( standardFormatWithSampleRate: 48000, channels: bus.format.channelCount )) try bus.setFormat(newFormat) try au.allocateRenderResources() #expect(au.engine?.sampleRate == 48000) au.deallocateRenderResources() } @Test func renderProducesNonzeroOutputAfterAllocate() throws { defer { lyrebirdClearRTMarkAfterTestRender() } let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) try au.allocateRenderResources() defer { au.deallocateRenderResources() } // synth.freq * synth.amp = 440 * 0.5 = 220 — every output sample should be 220. let frames: Int = 64 let channels: Int = 2 let size: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels) let raw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate( byteCount: size, alignment: MemoryLayout.alignment ) defer { raw.deallocate() } 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) ) } defer { for p: UnsafeMutablePointer in storage { p.deallocate() } } // Invoke the AU's render block directly (NRT-style — no host needed). let block: AUInternalRenderBlock = au.internalRenderBlock var flags: AudioUnitRenderActionFlags = [] var ts: AudioTimeStamp = AudioTimeStamp() ts.mFlags = .sampleTimeValid ts.mSampleTime = 0 let status: AUAudioUnitStatus = block(&flags, &ts, AUAudioFrameCount(frames), 0, abl, nil, nil) #expect(status == noErr) let samples: [Float] = Array(UnsafeBufferPointer(start: storage[0], count: frames)) // Output is 220 on every sample once the synth has been added — the first // engine block applies the add event and runs the generator. let nonZero: Bool = samples.contains { $0 != 0 && $0 != -999 } #expect(nonZero, "render produced silence; samples: \(samples.prefix(8))") #expect(samples.last == 220, "expected 220 on last sample, got \(samples.last ?? .nan)") } } // MARK: - fullState save / restore @MainActor @Suite("LyrebirdAudioUnit fullState") struct LyrebirdAudioUnitFullStateTests { @Test func fullStateRoundTripPreservesScalarLiveParams() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth) synth.freq = 1234.5 synth.amp = 0.75 let state: [String : Any]? = au.fullState #expect(state != nil) // Mutate, then restore via fullState setter. synth.freq = 100 synth.amp = 0.0 au.fullState = state #expect(synth.freq == 1234.5) #expect(synth.amp == 0.75) } @Test func fullStateStoresUnderNamespacedKey() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let state: [String : Any] = try #require(au.fullState) #expect(state[lyrebirdAUFullStateKey] != nil) // Scalar values are nested under a sub-key inside the root payload. let payload: [String : Any] = try #require(state[lyrebirdAUFullStateKey] as? [String: Any]) let values: [String : AUValue] = try #require(payload[lyrebirdAUFullStateScalarKey] as? [String: AUValue]) #expect(values["freq"] == 440) #expect(values["amp"] == AUValue(0.5)) } @Test func fullStateRestoreUpdatesAUParameterValues() throws { let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription()) let synth: TestFMSynth = try #require(au.synthesizer as? TestFMSynth) synth.freq = 555 synth.amp = 0.25 let saved: [String : Any]? = au.fullState // Reset and restore. synth.freq = 1000 synth.amp = 0.9 au.fullState = saved let tree: AUParameterTree = try #require(au.parameterTree) let freq: AUParameter = try #require(tree.parameter(withAddress: 0)) let amp: AUParameter = try #require(tree.parameter(withAddress: 1)) #expect(freq.value == 555) #expect(amp.value == AUValue(0.25)) } }