1.0.0 release
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
// AUInputTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AUInput.Audio") struct AUInputAudioTests {
|
||||
|
||||
@Test func channelMustBeNonNegative() {
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
#expect(gen.channel == 0)
|
||||
}
|
||||
|
||||
@Test func computeReturnsSilenceWhenEngineHasNoInputs() throws {
|
||||
// Engine with zero input channels — AUInput.Audio should defensively
|
||||
// return zeros rather than read past the bus array.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = gen._computeSamples(graph: graph, count: 32)
|
||||
#expect(result.count == 1)
|
||||
#expect(result[0].prefix(32).allSatisfy { $0 == 0 })
|
||||
}
|
||||
|
||||
@Test func computeReadsFromHostInputBus() throws {
|
||||
// Engine with two input channels — engine.audioBuses[numOutputChannels
|
||||
// + ch] holds the staged host input. We seed those buses directly
|
||||
// and verify AUInput.Audio reads them.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 32,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 2)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let inputBusIdx: Int = engine.numOutputChannels
|
||||
for i: Int in 0..<32 {
|
||||
engine.audioBuses[inputBusIdx][i] = Float(i) * 0.1
|
||||
}
|
||||
for i: Int in 0..<32 {
|
||||
engine.audioBuses[inputBusIdx + 1][i] = -Float(i) * 0.1
|
||||
}
|
||||
|
||||
let leftIn: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let rightIn: AUInput.Audio = AUInput.Audio(channel: 1)
|
||||
let graph: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let leftResult: [[Double]] = leftIn._computeSamples(graph: graph, count: 32)
|
||||
let rightResult: [[Double]] = rightIn._computeSamples(graph: graph, count: 32)
|
||||
#expect(leftResult[0][10] == Double(Float(10) * 0.1))
|
||||
#expect(leftResult[0][31] == Double(Float(31) * 0.1))
|
||||
#expect(rightResult[0][10] == Double(-Float(10) * 0.1))
|
||||
#expect(rightResult[0][31] == Double(-Float(31) * 0.1))
|
||||
}
|
||||
|
||||
@Test func outputChannelCountIsAlwaysOne() {
|
||||
let gen: AUInput.Audio = AUInput.Audio(channel: 5)
|
||||
#expect(gen.outputChannelCount == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// AUv3DriverTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Test fixtures
|
||||
|
||||
/// Synth that writes a deterministic counter into each output channel: sample i
|
||||
/// of channel c receives the value `Double(sampleIndex + i + c * 10000)`. Lets
|
||||
/// tests verify the ring buffer preserves temporal + channel ordering.
|
||||
private final class CounterSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let gen: CounterGen = CounterGen()
|
||||
output(bus: 0, source: gen[0])
|
||||
output(bus: 1, source: gen[1])
|
||||
}
|
||||
}
|
||||
|
||||
private final class CounterGen: GeneratorBase, AudioGenerator {
|
||||
private var _sampleIndex: Int = 0
|
||||
override init(channels: Int = 2) {
|
||||
super.init(channels: channels)
|
||||
}
|
||||
public override var outputChannelCount: Int { _result.count }
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = Double(_sampleIndex + i)
|
||||
_result[1][i] = Double(_sampleIndex + i + 10000)
|
||||
}
|
||||
_sampleIndex += count
|
||||
return _result
|
||||
}
|
||||
public func floatValue(graph: SynthGraph) -> Double {
|
||||
calculatedSamples(graph: graph, count: graph.engine.blockSize).first?.first ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Builds a heap-allocated AudioBufferList for `channels` mono Float channels,
|
||||
/// each `frames` long. Returns the buffer-list pointer + the per-channel storage
|
||||
/// arrays so the caller can inspect samples after `render`.
|
||||
private struct ABLFixture {
|
||||
let abl: UnsafeMutablePointer<AudioBufferList>
|
||||
let channelStorage: [UnsafeMutablePointer<Float>]
|
||||
let frames: Int
|
||||
let channels: Int
|
||||
|
||||
init(channels: Int, frames: Int) {
|
||||
self.channels = channels
|
||||
self.frames = frames
|
||||
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)
|
||||
abl.pointee = AudioBufferList(mNumberBuffers: UInt32(channels),
|
||||
mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
|
||||
var storage: [UnsafeMutablePointer<Float>] = []
|
||||
let listPtr: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(abl)
|
||||
for c: Int in 0..<channels {
|
||||
let ptr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: frames)
|
||||
for i: Int in 0..<frames { ptr[i] = 0 }
|
||||
storage.append(ptr)
|
||||
listPtr[c] = AudioBuffer(
|
||||
mNumberChannels: 1,
|
||||
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
|
||||
mData: UnsafeMutableRawPointer(ptr)
|
||||
)
|
||||
}
|
||||
self.abl = abl
|
||||
self.channelStorage = storage
|
||||
}
|
||||
|
||||
func channelSlice(_ c: Int) -> [Float] {
|
||||
let ptr: UnsafeMutablePointer<Float> = channelStorage[c]
|
||||
return Array(UnsafeBufferPointer(start: ptr, count: frames))
|
||||
}
|
||||
|
||||
func deallocate() {
|
||||
for p: UnsafeMutablePointer<Float> in channelStorage { p.deallocate() }
|
||||
UnsafeMutableRawPointer(abl).deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("AUv3Driver") struct AUv3DriverTests {
|
||||
|
||||
@Test func returnsUninitializedBeforeSetup() {
|
||||
let driver: AUv3Driver = AUv3Driver()
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 64)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == kAudioUnitErr_Uninitialized)
|
||||
}
|
||||
|
||||
@Test func rejectsFrameCountAboveMax() throws {
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 256)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
try engine.start()
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 512)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 512, outputData: fixture.abl)
|
||||
#expect(status == kAudioUnitErr_TooManyFramesToProcess)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func smallHostFrameCountDrivesMultipleEngineBlocks() throws {
|
||||
// Engine block 128; host requests 64 per call — two calls per engine block.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 64)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 64)
|
||||
defer { fixture.deallocate() }
|
||||
|
||||
// First render — engine produces one block (128 frames); ring delivers 64.
|
||||
var status: AUAudioUnitStatus = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let firstL: [Float] = fixture.channelSlice(0)
|
||||
let firstR: [Float] = fixture.channelSlice(1)
|
||||
#expect(firstL.first == 0)
|
||||
#expect(firstL.last == 63)
|
||||
#expect(firstR.first == 10000)
|
||||
#expect(firstR.last == 10063)
|
||||
|
||||
// Second render — pulls remaining 64 from the same engine block.
|
||||
status = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let secondL: [Float] = fixture.channelSlice(0)
|
||||
#expect(secondL.first == 64)
|
||||
#expect(secondL.last == 127)
|
||||
|
||||
// Third render — engine must advance another block.
|
||||
status = driver.render(frameCount: 64, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let thirdL: [Float] = fixture.channelSlice(0)
|
||||
#expect(thirdL.first == 128)
|
||||
#expect(thirdL.last == 191)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func largeHostFrameCountPullsMultipleEngineBlocks() throws {
|
||||
// Host wants 1024 per call but engine block is 256 — 4 engine blocks per
|
||||
// render call.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 256, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 1024)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: 1024, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let samples: [Float] = fixture.channelSlice(0)
|
||||
#expect(samples.first == 0)
|
||||
#expect(samples[256] == 256)
|
||||
#expect(samples[512] == 512)
|
||||
#expect(samples.last == 1023)
|
||||
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@Test func alternatingFrameCountsPreserveContinuity() throws {
|
||||
// Hosts may switch frame counts mid-stream; the ring must keep sample
|
||||
// continuity intact.
|
||||
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 128, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
let synth: CounterSynth = CounterSynth()
|
||||
try engine.start()
|
||||
try engine.add(synth)
|
||||
|
||||
let counts: [Int] = [1, 7, 64, 1, 200, 33, 511, 1]
|
||||
var nextExpected: Float = 0
|
||||
for count: Int in counts {
|
||||
let fixture: ABLFixture = ABLFixture(channels: 2, frames: count)
|
||||
defer { fixture.deallocate() }
|
||||
let status: AUAudioUnitStatus = driver.render(frameCount: count, outputData: fixture.abl)
|
||||
#expect(status == noErr)
|
||||
let samples: [Float] = fixture.channelSlice(0)
|
||||
#expect(samples.first == nextExpected, "first mismatch at count=\(count)")
|
||||
#expect(samples.last == nextExpected + Float(count - 1), "last mismatch at count=\(count)")
|
||||
nextExpected += Float(count)
|
||||
}
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// AUv3RingBufferTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AUv3RingBuffer") struct AUv3RingBufferTests {
|
||||
|
||||
@Test func capacityRoundsUpToPowerOfTwo() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 1000)
|
||||
#expect(ring.capacity == 1024)
|
||||
}
|
||||
|
||||
@Test func capacityExactPowerOfTwoUnchanged() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 256)
|
||||
#expect(ring.capacity == 256)
|
||||
}
|
||||
|
||||
@Test func availableToReadStartsAtZero() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 128)
|
||||
#expect(ring.availableToRead == 0)
|
||||
#expect(ring.availableToWrite == 128)
|
||||
}
|
||||
|
||||
@Test func writeThenReadRoundTrip() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 2, capacity: 128)
|
||||
let inL: [Float] = (0..<32).map { Float($0) }
|
||||
let inR: [Float] = (0..<32).map { Float(100 + $0) }
|
||||
ring.write(from: [inL, inR], count: 32)
|
||||
#expect(ring.availableToRead == 32)
|
||||
|
||||
var outL: [Float] = [Float](repeating: 0, count: 32)
|
||||
var outR: [Float] = [Float](repeating: 0, count: 32)
|
||||
outL.withUnsafeMutableBufferPointer { lBuf in
|
||||
outR.withUnsafeMutableBufferPointer { rBuf in
|
||||
guard let lBase: UnsafeMutablePointer<Float> = lBuf.baseAddress, let rBase: UnsafeMutablePointer<Float> = rBuf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 2)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = lBase
|
||||
ptrs[1] = rBase
|
||||
ring.read(into: ptrs, channelCount: 2, count: 32)
|
||||
}
|
||||
}
|
||||
#expect(outL == inL)
|
||||
#expect(outR == inR)
|
||||
#expect(ring.availableToRead == 0)
|
||||
}
|
||||
|
||||
@Test func writeAndReadWrapAround() {
|
||||
// capacity = 16; write 12, read 12 (advance indices), then write 12 (wraps).
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 16)
|
||||
let first: [Float] = (0..<12).map { Float($0) }
|
||||
ring.write(from: [first], count: 12)
|
||||
|
||||
var sink: [Float] = [Float](repeating: 0, count: 12)
|
||||
sink.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 12)
|
||||
}
|
||||
#expect(sink == first)
|
||||
|
||||
let second: [Float] = (100..<112).map { Float($0) }
|
||||
ring.write(from: [second], count: 12)
|
||||
var sink2: [Float] = [Float](repeating: 0, count: 12)
|
||||
sink2.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 12)
|
||||
}
|
||||
#expect(sink2 == second)
|
||||
}
|
||||
|
||||
@Test func resetClearsState() {
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 16)
|
||||
let data: [Float] = [1, 2, 3, 4]
|
||||
ring.write(from: [data], count: 4)
|
||||
#expect(ring.availableToRead == 4)
|
||||
ring.reset()
|
||||
#expect(ring.availableToRead == 0)
|
||||
#expect(ring.availableToWrite == 16)
|
||||
}
|
||||
|
||||
@Test func interleavedReadWritePreservesOrderingOverManyCycles() {
|
||||
// capacity = 32. Push N=7 samples then pull N=7, many times; values must
|
||||
// round-trip with stable ordering even though the indices wrap repeatedly.
|
||||
let ring: AUv3RingBuffer = AUv3RingBuffer(channelCount: 1, capacity: 32)
|
||||
var nextValue: Float = 0
|
||||
for cycle: Int in 0..<50 {
|
||||
let chunk: [Float] = (0..<7).map { _ in
|
||||
let v: Float = nextValue; nextValue += 1; return v
|
||||
}
|
||||
ring.write(from: [chunk], count: 7)
|
||||
var sink: [Float] = [Float](repeating: -1, count: 7)
|
||||
sink.withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else {
|
||||
Issue.record("nil baseAddress on owned [Float] storage")
|
||||
return
|
||||
}
|
||||
let ptrs: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(capacity: 1)
|
||||
defer { ptrs.deallocate() }
|
||||
ptrs[0] = base
|
||||
ring.read(into: ptrs, channelCount: 1, count: 7)
|
||||
}
|
||||
#expect(sink == chunk, "cycle \(cycle) mismatch: \(sink) vs \(chunk)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// LyrebirdAUParameterMappingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import AudioToolbox
|
||||
import AVFoundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Fixtures
|
||||
|
||||
private class ParamSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.5
|
||||
@LiveParam var modIndex: Double = 1.25
|
||||
override func build() {
|
||||
output(bus: 0, source: 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
private final class EmptySynth: SynthesizerBase {
|
||||
override func build() {
|
||||
output(bus: 0, source: 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
private final class InheritedParamSynth: ParamSynth {
|
||||
@LiveParam var detune: Double = 0.0
|
||||
}
|
||||
|
||||
// MARK: - Tests
|
||||
|
||||
@Suite("LyrebirdAUParameterMapping discovery") struct LyrebirdAUParameterDiscoveryTests {
|
||||
|
||||
@Test func discoversAllLiveParamsInDeclarationOrder() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries.count == 3)
|
||||
#expect(entries[0].name == "freq")
|
||||
#expect(entries[1].name == "amp")
|
||||
#expect(entries[2].name == "modIndex")
|
||||
#expect(entries[0].address == 0)
|
||||
#expect(entries[1].address == 1)
|
||||
#expect(entries[2].address == 2)
|
||||
}
|
||||
|
||||
@Test func discoversInitialValuesFromWrappers() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries[0].node.value == 440.0)
|
||||
#expect(entries[1].node.value == 0.5)
|
||||
#expect(entries[2].node.value == 1.25)
|
||||
}
|
||||
|
||||
@Test func emptySynthProducesEmptyEntries() {
|
||||
let synth: EmptySynth = EmptySynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
#expect(entries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func subclassParamsFollowBaseClassParams() {
|
||||
let synth: InheritedParamSynth = InheritedParamSynth()
|
||||
let entries: [LyrebirdAUParameterEntry] = LyrebirdAUParameterMapping.discoverLiveParameters(of: synth)
|
||||
// Mirror walks oldest-superclass first, so ParamSynth's three come before
|
||||
// the subclass's detune.
|
||||
let names: [String] = entries.map { $0.name }
|
||||
#expect(names == ["freq", "amp", "modIndex", "detune"])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUParameterMapping tree") struct LyrebirdAUParameterTreeTests {
|
||||
|
||||
@Test func buildsOneAUParameterPerSlot() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (tree, nodes) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let params: [AUParameter] = tree.allParameters
|
||||
#expect(params.count == 3)
|
||||
#expect(nodes.count == 3)
|
||||
let names: [String] = params.map { $0.identifier }
|
||||
#expect(names == ["freq", "amp", "modIndex"])
|
||||
}
|
||||
|
||||
@Test func paramValueSeededFromCurrentScalar() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
synth.freq = 1234.5 // overwrite default
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
#expect(freq?.value == AUValue(1234.5))
|
||||
}
|
||||
|
||||
@Test func metadataAppliesMinMaxUnitDisplayName() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let metadata: [String: LyrebirdAUParameterInfo] = [
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
|
||||
"amp": .init(min: 0, max: 1, unit: .linearGain),
|
||||
]
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(
|
||||
for: synth, metadata: metadata)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
let amp: AUParameter? = tree.parameter(withAddress: 1)
|
||||
#expect(freq?.minValue == 20)
|
||||
#expect(freq?.maxValue == 8000)
|
||||
#expect(freq?.unit == .hertz)
|
||||
#expect(freq?.displayName == "Frequency")
|
||||
#expect(amp?.minValue == 0)
|
||||
#expect(amp?.maxValue == 1)
|
||||
#expect(amp?.unit == .linearGain)
|
||||
}
|
||||
|
||||
@Test func defaultMetadataAppliesPermissiveBounds() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
#expect(freq?.minValue == AUValue(-lyrebirdAUParameterDefaultBound))
|
||||
#expect(freq?.maxValue == AUValue( lyrebirdAUParameterDefaultBound))
|
||||
#expect(freq?.unit == .generic)
|
||||
}
|
||||
|
||||
@Test func seededValueClampedToMetadataRange() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
synth.freq = 99_999.0 // way above max
|
||||
let metadata: [String: LyrebirdAUParameterInfo] = [
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz),
|
||||
]
|
||||
let (tree, _) = LyrebirdAUParameterMapping.buildParameterTree(
|
||||
for: synth, metadata: metadata)
|
||||
let freq: AUParameter? = tree.parameter(withAddress: 0)
|
||||
// AUParameter.value setter clamps writes, so the seeded value should be 8000.
|
||||
#expect(freq?.value == 8000)
|
||||
}
|
||||
|
||||
@Test func nodesDictionaryPointsToOriginalParameterNode() {
|
||||
let synth: ParamSynth = ParamSynth()
|
||||
let (_, nodes) = LyrebirdAUParameterMapping.buildParameterTree(for: synth)
|
||||
// Write through the node — synth.freq should update atomically.
|
||||
nodes[0]?._writeAtomicValue(2000.0)
|
||||
#expect(synth.freq == 2000.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// LyrebirdAUPresetRegistryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - Fixture preset-codable generator
|
||||
|
||||
private final class FixturePresetGen: GeneratorBase, AudioGenerator, LyrebirdAUPresetCodable {
|
||||
|
||||
static let presetTypeID: String = "test.fixturePresetGen"
|
||||
|
||||
private let _amp: Double
|
||||
private let _freq: Double
|
||||
|
||||
init(amp: Double, freq: Double) {
|
||||
self._amp = amp
|
||||
self._freq = freq
|
||||
super.init()
|
||||
}
|
||||
|
||||
var presetEncodedParameters: [String: AUValue] {
|
||||
["amp": AUValue(_amp), "freq": AUValue(_freq)]
|
||||
}
|
||||
|
||||
static func presetMake(from parameters: [String: AUValue]) -> any Generator {
|
||||
FixturePresetGen(
|
||||
amp: Double(parameters["amp"] ?? 0),
|
||||
freq: Double(parameters["freq"] ?? 0)
|
||||
)
|
||||
}
|
||||
|
||||
func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
precondition(count <= _result[0].count)
|
||||
for i: Int in 0..<count { _result[0][i] = _amp }
|
||||
return _result
|
||||
}
|
||||
|
||||
func floatValue(graph: SynthGraph) -> Double { _amp }
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUPresetSourceRegistry") struct LyrebirdAUPresetRegistryTests {
|
||||
|
||||
@Test func registerAndMakeRoundTrip() {
|
||||
defer { LyrebirdAUPresetSourceRegistry.unregister(typeID: FixturePresetGen.presetTypeID) }
|
||||
LyrebirdAUPresetSourceRegistry.register(FixturePresetGen.self)
|
||||
let descriptor: LyrebirdAUPresetSourceDescriptor = LyrebirdAUPresetSourceDescriptor(
|
||||
typeID: FixturePresetGen.presetTypeID,
|
||||
parameters: ["amp": 0.5, "freq": 440]
|
||||
)
|
||||
let made: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor)
|
||||
guard let typed: FixturePresetGen = made as? FixturePresetGen else {
|
||||
Issue.record("made-generator is not FixturePresetGen — got \(type(of: made))")
|
||||
return
|
||||
}
|
||||
#expect(typed.presetEncodedParameters["amp"] == AUValue(0.5))
|
||||
#expect(typed.presetEncodedParameters["freq"] == AUValue(440))
|
||||
}
|
||||
|
||||
@Test func unknownTypeIDReturnsNil() {
|
||||
let descriptor: LyrebirdAUPresetSourceDescriptor = LyrebirdAUPresetSourceDescriptor(typeID: "test.unknown")
|
||||
let made: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor)
|
||||
#expect(made == nil)
|
||||
}
|
||||
|
||||
@Test func unregisterRemovesType() {
|
||||
LyrebirdAUPresetSourceRegistry.register(FixturePresetGen.self)
|
||||
#expect(LyrebirdAUPresetSourceRegistry.registeredTypeIDs.contains(FixturePresetGen.presetTypeID))
|
||||
LyrebirdAUPresetSourceRegistry.unregister(typeID: FixturePresetGen.presetTypeID)
|
||||
#expect(!LyrebirdAUPresetSourceRegistry.registeredTypeIDs.contains(FixturePresetGen.presetTypeID))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// 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) }
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAUVoicePoolBinding") struct LyrebirdAUVoicePoolBindingTests {
|
||||
|
||||
@Test func noteOnAllocatesVoiceAndConfigures() throws {
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
let pool: VoicePool<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 4,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = 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<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 2,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
var noteOffCount: Int = 0
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = 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<TestVoice> = try VoicePool<TestVoice>(
|
||||
voiceCount: 2,
|
||||
group: engine.rootGroup,
|
||||
engine: engine,
|
||||
factory: { TestVoice() }
|
||||
)
|
||||
let binding: LyrebirdAUVoicePoolBinding<TestVoice> = 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 }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// LyrebirdAudioUnitEffectTests.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
|
||||
|
||||
private final class PassthroughSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let left: AUInput.Audio = AUInput.Audio(channel: 0)
|
||||
let right: AUInput.Audio = AUInput.Audio(channel: 1)
|
||||
output(bus: 0, source: left)
|
||||
output(bus: 1, source: right)
|
||||
}
|
||||
}
|
||||
|
||||
private final class PassthroughEffectAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase {
|
||||
PassthroughSynth()
|
||||
}
|
||||
public override class var lyrebirdInputChannels: Int { 2 }
|
||||
public override class var lyrebirdOutputChannels: Int { 2 }
|
||||
}
|
||||
|
||||
private func makeEffectDescription() -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_Effect,
|
||||
componentSubType: 0x4C425046, // 'LBPF'
|
||||
componentManufacturer: 0x524C5A53, // 'RLZS'
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit effect") struct LyrebirdAudioUnitEffectTests {
|
||||
|
||||
@Test func effectAUDeclaresInputAndOutputBuses() throws {
|
||||
let au: PassthroughEffectAU = try PassthroughEffectAU(componentDescription: makeEffectDescription())
|
||||
#expect(au.outputBusses.count == 1)
|
||||
#expect(au.inputBusses.count == 1)
|
||||
let inFormat: AVAudioFormat = au.inputBusses[0].format
|
||||
#expect(inFormat.channelCount == 2)
|
||||
}
|
||||
|
||||
@Test func effectAUEngineHasInputChannels() throws {
|
||||
let au: PassthroughEffectAU = try PassthroughEffectAU(componentDescription: makeEffectDescription())
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numInputChannels == 2)
|
||||
#expect(engine.numOutputChannels == 2)
|
||||
}
|
||||
|
||||
@Test func instrumentAUEngineHasNoInputChannels() throws {
|
||||
// Sanity check the default — instrument AUs must not allocate input buses.
|
||||
final class StubSynth: SynthesizerBase {
|
||||
override func build() { output(bus: 0, source: 0.0) }
|
||||
}
|
||||
final class StubInstrumentAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { StubSynth() }
|
||||
}
|
||||
let desc: AudioComponentDescription = AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: 0x53545542,
|
||||
componentManufacturer: 0x524C5A53,
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
let au: StubInstrumentAU = try StubInstrumentAU(componentDescription: desc)
|
||||
try au.allocateRenderResources()
|
||||
defer { au.deallocateRenderResources() }
|
||||
let engine: SynthesisEngine = try #require(au.engine)
|
||||
#expect(engine.numInputChannels == 0)
|
||||
#expect(au.inputBusses.count == 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// LyrebirdAudioUnitMIDITests.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
|
||||
|
||||
@Suite("LyrebirdAudioUnit MIDI dispatch") struct LyrebirdAudioUnitMIDITests {
|
||||
|
||||
@Test func dispatchHandlesNilHeadGracefully() {
|
||||
var received: [MIDIMessage] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: nil) { msg, _ in
|
||||
received.append(msg)
|
||||
}
|
||||
#expect(received.isEmpty)
|
||||
}
|
||||
|
||||
@Test func dispatchSkipsCallWhenHandlerNil() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x90, data1: 60, data2: 100)
|
||||
defer { event.deallocate() }
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event, handler: nil)
|
||||
// No assertion needed — just verifies no crash.
|
||||
}
|
||||
|
||||
@Test func dispatchParsesNoteOnEvent() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x91, data1: 60, data2: 100)
|
||||
defer { event.deallocate() }
|
||||
var received: [MIDIMessage] = []
|
||||
var sampleTimes: [AUEventSampleTime] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event) { msg, time in
|
||||
received.append(msg)
|
||||
sampleTimes.append(time)
|
||||
}
|
||||
#expect(received.count == 1)
|
||||
if case .noteOn(let channel, let note, let velocity) = received[0] {
|
||||
#expect(channel == 1)
|
||||
#expect(note == 60)
|
||||
#expect(velocity == 100)
|
||||
} else {
|
||||
Issue.record("Expected .noteOn, got \(received[0])")
|
||||
}
|
||||
#expect(sampleTimes == [0])
|
||||
}
|
||||
|
||||
@Test func dispatchParsesNoteOffEvent() {
|
||||
let event: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x80, data1: 64, data2: 0)
|
||||
defer { event.deallocate() }
|
||||
var received: [MIDIMessage] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: event) { msg, _ in
|
||||
received.append(msg)
|
||||
}
|
||||
#expect(received.count == 1)
|
||||
if case .noteOff(_, let note, _) = received[0] {
|
||||
#expect(note == 64)
|
||||
} else {
|
||||
Issue.record("Expected .noteOff, got \(received[0])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func dispatchWalksChainOfEvents() {
|
||||
// Chain: noteOn → noteOff. Link via head.next pointer.
|
||||
let e1: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x90, data1: 60, data2: 80, sampleTime: 0)
|
||||
let e2: UnsafePointer<AURenderEvent> = makeMIDIRenderEvent(status: 0x80, data1: 60, data2: 0, sampleTime: 128)
|
||||
defer { e1.deallocate(); e2.deallocate() }
|
||||
// Patch e1.head.next to point at e2.
|
||||
let mutablePtr: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>(mutating: e1)
|
||||
mutablePtr.pointee.head.next = UnsafeMutablePointer<AURenderEvent>(mutating: e2)
|
||||
|
||||
var received: [MIDIMessage] = []
|
||||
var sampleTimes: [AUEventSampleTime] = []
|
||||
LyrebirdAudioUnit._dispatchMIDIEvents(eventsHead: e1) { msg, time in
|
||||
received.append(msg)
|
||||
sampleTimes.append(time)
|
||||
}
|
||||
#expect(received.count == 2)
|
||||
#expect(sampleTimes == [0, 128])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Builds a single AURenderEvent on the heap with a MIDI payload. Caller owns
|
||||
/// the returned pointer and must `deallocate()` it when done.
|
||||
private func makeMIDIRenderEvent(
|
||||
status: UInt8,
|
||||
data1: UInt8,
|
||||
data2: UInt8,
|
||||
sampleTime: AUEventSampleTime = 0
|
||||
) -> UnsafePointer<AURenderEvent> {
|
||||
let ptr: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>.allocate(capacity: 1)
|
||||
var event: AURenderEvent = AURenderEvent()
|
||||
event.head.next = nil
|
||||
event.head.eventSampleTime = sampleTime
|
||||
event.head.eventType = .MIDI
|
||||
event.head.reserved = 0
|
||||
event.MIDI.eventType = .MIDI
|
||||
event.MIDI.reserved = 0
|
||||
event.MIDI.length = 3
|
||||
event.MIDI.cable = 0
|
||||
event.MIDI.data = (status, data1, data2)
|
||||
ptr.initialize(to: event)
|
||||
return UnsafePointer(ptr)
|
||||
}
|
||||
|
||||
private extension UnsafePointer where Pointee == AURenderEvent {
|
||||
func deallocate() {
|
||||
let mut: UnsafeMutablePointer<AURenderEvent> = UnsafeMutablePointer<AURenderEvent>(mutating: self)
|
||||
mut.deinitialize(count: 1)
|
||||
mut.deallocate()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
// 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..<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)")
|
||||
}
|
||||
}
|
||||
|
||||
@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 {
|
||||
// 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()
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// LyrebirdAudioUnitPresetTests.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
|
||||
|
||||
private final class PresetSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440
|
||||
@LiveParam var amp: Double = 0.5
|
||||
override func build() { output(bus: 0, source: $freq * $amp) }
|
||||
}
|
||||
|
||||
private final class PresetAU: LyrebirdAudioUnit {
|
||||
public override class func makeSynthesizer() -> SynthesizerBase { PresetSynth() }
|
||||
public override class func factoryPresetsForLyrebird() -> [LyrebirdAUFactoryPreset] {
|
||||
[
|
||||
.init(name: "Bright", scalarValues: ["freq": 880, "amp": 0.8]),
|
||||
.init(name: "Quiet", scalarValues: ["freq": 220, "amp": 0.1]),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private func makeDesc() -> AudioComponentDescription {
|
||||
AudioComponentDescription(
|
||||
componentType: kAudioUnitType_MusicDevice,
|
||||
componentSubType: 0x50525345,
|
||||
componentManufacturer: 0x524C5A53,
|
||||
componentFlags: 0,
|
||||
componentFlagsMask: 0
|
||||
)
|
||||
}
|
||||
|
||||
@Suite("LyrebirdAudioUnit factory presets") struct LyrebirdAudioUnitFactoryPresetsTests {
|
||||
|
||||
@Test func factoryPresetsExposeAllNames() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let presets: [AUAudioUnitPreset] = try #require(au.factoryPresets)
|
||||
#expect(presets.map(\.name) == ["Bright", "Quiet"])
|
||||
#expect(presets.map(\.number) == [0, 1])
|
||||
}
|
||||
|
||||
@Test func selectingCurrentPresetAppliesScalars() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
let p0: AUAudioUnitPreset? = au.factoryPresets?.first
|
||||
au.currentPreset = p0
|
||||
// Preset scalars are AUValue (Float) — round-trip through Double will
|
||||
// pick up a small precision delta, so tolerance is applied.
|
||||
#expect(synth.freq == 880)
|
||||
#expect(abs(synth.amp - 0.8) < 1e-6)
|
||||
|
||||
let p1: AUAudioUnitPreset? = au.factoryPresets?.last
|
||||
au.currentPreset = p1
|
||||
#expect(synth.freq == 220)
|
||||
#expect(abs(synth.amp - 0.1) < 1e-6)
|
||||
}
|
||||
|
||||
@Test func currentPresetSetterIsIdempotent() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let p0: AUAudioUnitPreset? = au.factoryPresets?.first
|
||||
au.currentPreset = p0
|
||||
au.currentPreset = p0
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
#expect(synth.freq == 880)
|
||||
}
|
||||
|
||||
@Test func nilCurrentPresetIsNoop() throws {
|
||||
let au: PresetAU = try PresetAU(componentDescription: makeDesc())
|
||||
let synth: PresetSynth = try #require(au.synthesizer as? PresetSynth)
|
||||
synth.freq = 1234
|
||||
au.currentPreset = nil
|
||||
// Nil should not overwrite the user-set scalar.
|
||||
#expect(synth.freq == 1234)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// 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 {
|
||||
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
|
||||
|
||||
@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
|
||||
|
||||
@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 {
|
||||
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<AudioBufferList>.alignment
|
||||
)
|
||||
defer { raw.deallocate() }
|
||||
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] = -999 }
|
||||
storage.append(p)
|
||||
listPtr[c] = AudioBuffer(
|
||||
mNumberChannels: 1,
|
||||
mDataByteSize: UInt32(frames * MemoryLayout<Float>.size),
|
||||
mData: UnsafeMutableRawPointer(p)
|
||||
)
|
||||
}
|
||||
defer { for p: UnsafeMutablePointer<Float> 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
|
||||
|
||||
@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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user