Files
Lyrebird/Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

827 lines
38 KiB
Swift

// CoreAudioDriver.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
#if canImport(AudioToolbox)
import CoreAudio
import AudioToolbox
import Synchronization
/// Errors thrown by `CoreAudioDriver` during setup, start, or sample-rate negotiation.
public enum CoreAudioError: Error {
/// No HALOutput (`kAudioUnitSubType_HALOutput`) Audio Component was found on this system.
case componentNotFound
/// `AudioComponentInstanceNew` failed with the given OS status code.
case instantiationFailed(OSStatus)
/// Enabling I/O on the AUHAL unit failed with the given OS status code.
case enableIOFailed(OSStatus)
/// Setting the audio stream format failed with the given OS status code.
case streamFormatFailed(OSStatus)
/// Setting `kAudioUnitProperty_MaximumFramesPerSlice` failed with the given OS status code.
case maxFramesFailed(OSStatus)
/// Installing the render callback failed with the given OS status code.
case callbackInstallFailed(OSStatus)
/// `AudioUnitInitialize` failed with the given OS status code.
case initFailed(OSStatus)
/// `AudioOutputUnitStart` failed with the given OS status code.
case startFailed(OSStatus)
/// Creating a private aggregate device to unify separate input and output hardware failed.
case aggregateDeviceCreationFailed(OSStatus)
/// The engine's requested sample rate differs from the hardware device's nominal rate
/// and `CoreAudioDriverOptions.matchDeviceSampleRate` is `false`.
case sampleRateMismatch(requested: Double, deviceRate: Double)
/// Failed to query a HAL property used during device selection or rate negotiation.
case deviceSetupFailed(String)
}
/// Backwards-compatibility alias used internally by `CoreAudioDriver` setup helpers.
internal typealias CoreAudioDriverError = CoreAudioError
/// Configuration options for `CoreAudioDriver`.
public struct CoreAudioDriverOptions {
/// When `true`, the driver sets `kAudioDevicePropertyNominalSampleRate` on the
/// selected device to match `engine.sampleRate` instead of throwing
/// `CoreAudioError.sampleRateMismatch` when the rates differ.
public var matchDeviceSampleRate: Bool
public init(matchDeviceSampleRate: Bool = false) {
self.matchDeviceSampleRate = matchDeviceSampleRate
}
}
/// A real-time Core Audio driver that connects a `SynthesisEngine` to hardware I/O.
///
/// `CoreAudioDriver` wraps an AUHAL (`kAudioUnitSubType_HALOutput`) audio unit configured
/// for full-duplex operation. All I/O buffers are pre-allocated during `setup(engine:)`
/// so the render callback never allocates on the RT thread.
///
/// **Typical usage**:
/// ```swift
/// let driver = CoreAudioDriver()
/// let engine = SynthesisEngine(
/// blockSize: 512, sampleRate: 44100,
/// numOutputChannels: 2, numInputChannels: 0,
/// driver: driver
/// )
/// try engine.start()
/// // … audio running …
/// engine.stop()
/// ```
///
/// **Device selection** — when input channels are requested and the default input and output
/// devices differ, `CoreAudioDriver` attempts (in order): using the output device if it has
/// sufficient input channels, using the input device if it has sufficient output channels,
/// finding a built-in duplex device, and finally creating a private aggregate device.
///
/// Set `options.matchDeviceSampleRate = true` before calling `setup(engine:)` to allow the
/// driver to set the hardware device's nominal sample rate rather than throwing
/// `CoreAudioError.sampleRateMismatch` when rates disagree.
public final class CoreAudioDriver: AudioDriver {
private static let sampleRateEpsilon: Double = 0.01
private var outputUnit: AudioComponentInstance?
// Pre-allocated AudioBufferList for AudioUnitRender on element 1.
// Allocated once in setup(); never touched in render() after that.
private var inputABL: UnsafeMutableAudioBufferListPointer?
// Raw per-channel backing buffers for the ABL. Heap-allocated in setup() with stable
// addresses that never move — the ABL's mData pointers are wired to these once and
// stay valid for the driver's lifetime. Using raw pointers instead of [[Float]] avoids
// the Swift exclusivity violation that arises when multiple withUnsafeMutableBufferPointer
// closures are open simultaneously on elements of the same Swift array.
private var rawInputPtrs: [UnsafeMutablePointer<Float>] = []
// Pre-allocated [[Float]] passed to engine.processBlock each render.
// After AudioUnitRender fills rawInputPtrs, data is memcpy'd here — no heap allocation.
private var inputStagingBuffers: [[Float]] = []
// Unretained reference set during setup() — engine lifetime must exceed driver lifetime.
private var engineRef: Unmanaged<SynthesisEngine>?
private var blockSize: Int = 0
private let _isInitialized: Atomic<Bool> = Atomic<Bool>(false)
private var aggregateDeviceID: AudioDeviceID = AudioDeviceID(kAudioObjectUnknown)
private var coreAudioPluginID: AudioObjectID = AudioObjectID(kAudioObjectUnknown)
/// Options controlling driver behaviour. Must be set before calling `setup(engine:)`.
public var options: CoreAudioDriverOptions = .init()
/// The nominal sample rate reported by the selected hardware device, set during `setup(engine:)`.
/// `nil` if setup has not been called or the device rate could not be queried.
public private(set) var deviceSampleRate: Double?
public init() {
// Force RT-thread-identity TLS key initialisation from this non-RT
// call site so the first render callback's `markCurrentThreadAsRT()`
// is a single pthread_setspecific, not a `pthread_key_create` on
// the RT thread.
RTThreadIdentity.warmUp()
}
public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize }
deinit {
_isInitialized.store(false, ordering: .releasing)
if let unit: AudioComponentInstance = outputUnit {
AudioOutputUnitStop(unit)
AudioUnitUninitialize(unit)
AudioComponentInstanceDispose(unit)
}
destroyAggregateDevice()
if let abl: UnsafeMutableAudioBufferListPointer = inputABL {
UnsafeMutableRawPointer(abl.unsafeMutablePointer).deallocate()
}
for ptr: UnsafeMutablePointer<Float> in rawInputPtrs {
ptr.deallocate()
}
}
public func setup(engine: SynthesisEngine) throws {
engineRef = Unmanaged.passUnretained(engine)
blockSize = engine.blockSize
// Pre-allocate stable raw backing buffers — one per input channel.
// The ABL's mData pointers are wired to these in the loop below and never changed.
if engine.numInputChannels > 0 {
let abl: UnsafeMutableAudioBufferListPointer = AudioBufferList.allocate(maximumBuffers: engine.numInputChannels)
abl.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(engine.numInputChannels)
for ch: Int in 0..<engine.numInputChannels {
let ptr: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: engine.blockSize)
ptr.initialize(repeating: 0, count: engine.blockSize)
rawInputPtrs.append(ptr)
// Wire mData once — never touched again in render().
abl[ch] = AudioBuffer(
mNumberChannels: 1,
mDataByteSize: UInt32(engine.blockSize) * lyrebirdBytesPerSample,
mData: UnsafeMutableRawPointer(ptr)
)
}
inputABL = abl
// Pre-allocate the [[Float]] shadow for processBlock.
inputStagingBuffers = [[Float]](
repeating: [Float](repeating: 0, count: engine.blockSize),
count: engine.numInputChannels
)
}
// 1. Find the AUHAL component (HALOutput supports full duplex; DefaultOutput does not)
var desc: AudioComponentDescription = AudioComponentDescription(
componentType: kAudioUnitType_Output,
componentSubType: kAudioUnitSubType_HALOutput,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0
)
guard let component: AudioComponent = AudioComponentFindNext(nil, &desc) else {
throw CoreAudioError.componentNotFound
}
// 2. Instantiate the audio unit
var unit: AudioComponentInstance?
var status: OSStatus = AudioComponentInstanceNew(component, &unit)
guard status == noErr, let unit: AudioComponentInstance else {
throw CoreAudioError.instantiationFailed(status)
}
outputUnit = unit
// 3. Determine the correct device to use BEFORE any configuration
//
// CRITICAL: AUHAL requires input and output to use the SAME device!
// We must identify and set this device BEFORE enabling I/O or setting formats.
let deviceToUse: AudioDeviceID = try _selectDevice(engine: engine)
// Set the device BEFORE enabling I/O or setting formats
if deviceToUse != kAudioObjectUnknown {
var mutableDevice: AudioDeviceID = deviceToUse
status = AudioUnitSetProperty(
unit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global,
0,
&mutableDevice,
UInt32(MemoryLayout<AudioDeviceID>.size)
)
guard status == noErr else { throw CoreAudioError.enableIOFailed(status) }
}
// Query the device's nominal sample rate. If it differs from engine.sampleRate,
// either set it (matchDeviceSampleRate: true) or throw (default).
if deviceToUse != AudioDeviceID(kAudioObjectUnknown),
let queriedRate: Double = queryNominalSampleRate(for: deviceToUse) {
deviceSampleRate = queriedRate
try CoreAudioDriver._validateSampleRates(
requested: engine.sampleRate,
deviceRate: queriedRate,
options: options
)
if options.matchDeviceSampleRate && abs(queriedRate - engine.sampleRate) > CoreAudioDriver.sampleRateEpsilon{
let setStatus: OSStatus = setNominalSampleRate(engine.sampleRate, for: deviceToUse)
if setStatus != noErr {
// Kernel rejected the rate change (busy device, hog mode, locked by
// another client). Re-query the device's actual rate and re-validate
// — if the device kept the old rate and matchDeviceSampleRate cannot
// change it, the engine sample rate / device sample rate mismatch has
// to surface as a hard error rather than silently rendering at the
// wrong rate.
let actualRate: Double = queryNominalSampleRate(for: deviceToUse) ?? queriedRate
deviceSampleRate = actualRate
try CoreAudioDriver._validateSampleRates(
requested: engine.sampleRate,
deviceRate: actualRate,
options: CoreAudioDriverOptions(matchDeviceSampleRate: false)
)
}
}
}
// 4. Enable output on element 0 and configure input on element 1
var enableOutput: UInt32 = 1
status = AudioUnitSetProperty(
unit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output,
0,
&enableOutput,
UInt32(MemoryLayout<UInt32>.size)
)
guard status == noErr else { throw CoreAudioError.enableIOFailed(status) }
if engine.numInputChannels > 0 {
var enableInput: UInt32 = 1
status = AudioUnitSetProperty(
unit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input,
1,
&enableInput,
UInt32(MemoryLayout<UInt32>.size)
)
guard status == noErr else { throw CoreAudioError.enableIOFailed(status) }
} else {
// Explicitly disable input on element 1 when not needed.
// AUHAL's default input state is ambiguous across hardware configurations;
// being explicit here prevents the HAL from attempting to open the input
// device and avoids additional sequencing noise during startup.
var disableInput: UInt32 = 0
_ = AudioUnitSetProperty(
unit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input,
1,
&disableInput,
UInt32(MemoryLayout<UInt32>.size)
)
}
// 5. Set stream formats (non-interleaved 32-bit float) on input and output
try _configureStreamFormats(unit: unit, engine: engine)
// 6. Cap the maximum frames per slice to our block size
var maxFrames: UInt32 = UInt32(engine.blockSize)
status = AudioUnitSetProperty(
unit,
kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global,
0,
&maxFrames,
UInt32(MemoryLayout<UInt32>.size)
)
guard status == noErr else { throw CoreAudioError.maxFramesFailed(status) }
// 7. Install render callback
var callbackStruct: AURenderCallbackStruct = AURenderCallbackStruct(
inputProc: lyrebirdRenderCallback,
inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()
)
status = AudioUnitSetProperty(
unit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
0,
&callbackStruct,
UInt32(MemoryLayout<AURenderCallbackStruct>.size)
)
guard status == noErr else { throw CoreAudioError.callbackInstallFailed(status) }
}
// MARK: - setup helpers
/// Resolves which `AudioDeviceID` to use for both input and output.
///
/// AUHAL requires a single device for full-duplex operation. The 5-way decision tree
/// below picks the best available option without any user-facing configuration:
/// 1. Same device already selected by the OS for both in/out — use it directly.
/// 2. Default output device has sufficient input channels — use it.
/// 3. Default input device has sufficient output channels — use it.
/// 4. Find a built-in duplex device via transport type (locale-independent).
/// 5. Create a private aggregate device combining default output + default input.
private func _selectDevice(engine: SynthesisEngine) throws -> AudioDeviceID {
let devicePropertySize: UInt32 = UInt32(MemoryLayout<AudioDeviceID>.size)
if engine.numInputChannels > 0 {
var defaultInputDevice: AudioDeviceID = AudioDeviceID(0)
var defaultOutputDevice: AudioDeviceID = AudioDeviceID(0)
var inputDeviceSize: UInt32 = devicePropertySize
var outputDeviceSize: UInt32 = devicePropertySize
var inputDeviceAddr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var outputDeviceAddr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let inputStatus: OSStatus = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&inputDeviceAddr, 0, nil,
&inputDeviceSize, &defaultInputDevice
)
guard inputStatus == noErr else {
throw CoreAudioDriverError.deviceSetupFailed(
"Failed to query default input device: OSStatus \(inputStatus)"
)
}
let outputStatus: OSStatus = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&outputDeviceAddr, 0, nil,
&outputDeviceSize, &defaultOutputDevice
)
guard outputStatus == noErr else {
throw CoreAudioDriverError.deviceSetupFailed(
"Failed to query default output device: OSStatus \(outputStatus)"
)
}
if defaultInputDevice == defaultOutputDevice {
return defaultInputDevice
}
let outputDeviceInputCh: Int = deviceChannelCount(
defaultOutputDevice, scope: kAudioDevicePropertyScopeInput)
let inputDeviceOutputCh: Int = deviceChannelCount(
defaultInputDevice, scope: kAudioDevicePropertyScopeOutput)
if outputDeviceInputCh >= engine.numInputChannels {
return defaultOutputDevice
} else if inputDeviceOutputCh >= engine.numOutputChannels {
return defaultInputDevice
} else if let builtIn: AudioDeviceID = findBuiltInDuplexDevice(
numInputChannels: engine.numInputChannels,
numOutputChannels: engine.numOutputChannels
) {
return builtIn
} else {
return try makeAggregateDevice(
outputDeviceID: defaultOutputDevice,
inputDeviceID: defaultInputDevice
)
}
} else {
// Output only — use default output device
var deviceToUse: AudioDeviceID = AudioDeviceID(0)
var defaultDeviceAddr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var size: UInt32 = devicePropertySize
let status: OSStatus = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&defaultDeviceAddr, 0, nil,
&size, &deviceToUse
)
guard status == noErr else {
throw CoreAudioDriverError.deviceSetupFailed(
"Failed to query default output device: OSStatus \(status)"
)
}
return deviceToUse
}
}
/// Applies non-interleaved 32-bit float `AudioStreamBasicDescription` to the AUHAL unit
/// for both output (element 0 input scope) and, when input channels are present,
/// input (element 1 output scope).
private func _configureStreamFormats(unit: AudioUnit, engine: SynthesisEngine) throws {
// Output stream format (non-interleaved 32-bit float)
var outputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: engine.sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved,
mBytesPerPacket: lyrebirdBytesPerSample,
mFramesPerPacket: 1,
mBytesPerFrame: lyrebirdBytesPerSample,
mChannelsPerFrame: UInt32(engine.numOutputChannels),
mBitsPerChannel: lyrebirdBitsPerSample,
mReserved: 0
)
var status: OSStatus = AudioUnitSetProperty(
unit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&outputFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
)
guard status == noErr else { throw CoreAudioError.streamFormatFailed(status) }
// Input stream format on element 1
if engine.numInputChannels > 0 {
var inputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: engine.sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved,
mBytesPerPacket: lyrebirdBytesPerSample,
mFramesPerPacket: 1,
mBytesPerFrame: lyrebirdBytesPerSample,
mChannelsPerFrame: UInt32(engine.numInputChannels),
mBitsPerChannel: lyrebirdBitsPerSample,
mReserved: 0
)
status = AudioUnitSetProperty(
unit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output,
1,
&inputFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
)
guard status == noErr else { throw CoreAudioError.streamFormatFailed(status) }
}
}
public func start() throws {
guard let unit: AudioComponentInstance = outputUnit else { return }
var status: OSStatus = AudioUnitInitialize(unit)
guard status == noErr else { throw CoreAudioError.initFailed(status) }
status = AudioOutputUnitStart(unit)
guard status == noErr else { throw CoreAudioError.startFailed(status) }
// Mark initialized only after AudioOutputUnitStart returns, so callbacks that fire
// during HAL startup don't attempt AudioUnitRender on an input element that hasn't
// fully started yet.
_isInitialized.store(true, ordering: .releasing)
}
public func stop() {
guard let unit: AudioComponentInstance = outputUnit else { return }
_isInitialized.store(false, ordering: .releasing)
AudioOutputUnitStop(unit)
AudioUnitUninitialize(unit)
AudioComponentInstanceDispose(unit)
destroyAggregateDevice()
outputUnit = nil
// Tear down input-side state symmetric with setup(): setup() appends to
// rawInputPtrs and replaces inputABL each call, so leaving stale state here
// grows rawInputPtrs past inputABL.mNumberBuffers on the next start() and
// crashes render() at the `for ch in 0..<rawInputPtrs.count` loop.
if let abl: UnsafeMutableAudioBufferListPointer = inputABL {
UnsafeMutableRawPointer(abl.unsafeMutablePointer).deallocate()
inputABL = nil
}
for ptr: UnsafeMutablePointer<Float> in rawInputPtrs { ptr.deallocate() }
rawInputPtrs.removeAll(keepingCapacity: false)
inputStagingBuffers.removeAll(keepingCapacity: false)
}
// Called from the render callback — must not allocate.
fileprivate func render(
actionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
timeStamp: UnsafePointer<AudioTimeStamp>,
busNumber: UInt32,
numFrames: UInt32,
ioData: UnsafeMutablePointer<AudioBufferList>?
) -> OSStatus {
// Mark this thread as the RT render thread so DEBUG asserts in
// non-RT-safe APIs (e.g. `ValueComputable.compute`) can trap misuse.
// Idempotent + single TLS read in steady state.
RTThreadIdentity.markCurrentThreadAsRT()
// Ensure subnormal values are flushed to zero on this thread.
// FTZ is thread-local state; calling this unconditionally here is safe and cheap
// (single fesetenv instruction), and re-arms the register if the audio I/O thread
// is ever recycled by the OS.
enableFlushToZero()
guard let engine: SynthesisEngine = engineRef?.takeUnretainedValue() else { return noErr }
let frameCount: Int = Int(numFrames)
// Read hardware input via AudioUnitRender on element 1.
// The ABL's mData pointers were wired to rawInputPtrs in setup() — no pointer
// manipulation needed here. No withUnsafeMutableBufferPointer closures, no
// Swift exclusivity conflict.
//
// CRITICAL: AudioUnitRender can only be called AFTER AudioUnitInitialize() completes.
// Guard against early calls during the initialization/startup sequence.
if !rawInputPtrs.isEmpty, let unit: AudioComponentInstance = outputUnit, let abl: UnsafeMutableAudioBufferListPointer = inputABL,
_isInitialized.load(ordering: .acquiring) {
// Update byte sizes in case numFrames < blockSize (e.g. last block).
let byteSize: UInt32 = UInt32(frameCount) * lyrebirdBytesPerSample
for ch: Int in 0..<rawInputPtrs.count {
abl[ch].mDataByteSize = byteSize
}
var inputFlags: AudioUnitRenderActionFlags = AudioUnitRenderActionFlags(rawValue: 0)
_ = AudioUnitRender(unit, &inputFlags, timeStamp, 1, numFrames,
abl.unsafeMutablePointer)
// Copy raw buffer data into the pre-allocated [[Float]] staging array for
// processBlock. memcpy — no heap allocation.
for (ch, rawPtr) in rawInputPtrs.enumerated() {
guard ch < inputStagingBuffers.count else { break }
guard frameCount <= inputStagingBuffers[ch].count else { break }
inputStagingBuffers[ch].withUnsafeMutableBufferPointer { dst in
guard let base: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
memcpy(base, rawPtr, frameCount * MemoryLayout<Float>.size)
}
}
}
// Process one block — updates audioBuses in place.
engine.processBlock(inputSamples: inputStagingBuffers)
// Copy output buses to the hardware AudioBufferList.
guard let bufferList: UnsafeMutablePointer<AudioBufferList> = ioData else { return noErr }
let outputABL: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(bufferList)
for (ch, buffer) in outputABL.enumerated() {
guard ch < engine.numOutputChannels else { break }
guard let dest: UnsafeMutablePointer<Float> = buffer.mData?.bindMemory(to: Float.self, capacity: frameCount) else { continue }
engine.audioBuses[ch].withUnsafeBufferPointer { src in
guard let base: UnsafePointer<Float> = src.baseAddress else { return }
dest.initialize(from: base, count: min(frameCount, src.count))
}
}
return noErr
}
// MARK: - Sample rate helpers
private func queryNominalSampleRate(for deviceID: AudioDeviceID) -> Double? {
var rate: Float64 = 0
var size: UInt32 = UInt32(MemoryLayout<Float64>.size)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyNominalSampleRate,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
guard AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, &rate) == noErr else {
return nil
}
return rate
}
/// Sets the device's `kAudioDevicePropertyNominalSampleRate` and returns the resulting
/// `OSStatus`. A non-`noErr` status indicates the kernel rejected the rate change
/// (busy device, hog mode, locked by another client). Callers should surface or log.
@discardableResult
private func setNominalSampleRate(
_ rate: Double,
for deviceID: AudioDeviceID
) -> OSStatus {
var newRate: Double = rate
let size: UInt32 = UInt32(MemoryLayout<Float64>.size)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyNominalSampleRate,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
return AudioObjectSetPropertyData(deviceID, &addr, 0, nil, size, &newRate)
}
/// Validates that `requested` and `deviceRate` agree (within floating-point rounding).
/// - When they differ and `options.matchDeviceSampleRate` is `false`: throws
/// `CoreAudioError.sampleRateMismatch`.
/// - When they differ and `options.matchDeviceSampleRate` is `true`: returns normally;
/// the caller is responsible for setting the device property.
/// Internal so unit tests can exercise mismatch logic without hardware.
static func _validateSampleRates(
requested: Double,
deviceRate: Double,
options: CoreAudioDriverOptions
) throws {
guard abs(requested - deviceRate) > CoreAudioDriver.sampleRateEpsilon else { return }
guard options.matchDeviceSampleRate else {
throw CoreAudioError.sampleRateMismatch(requested: requested, deviceRate: deviceRate)
}
}
// MARK: - Device helpers
private func deviceChannelCount(
_ deviceID: AudioDeviceID,
scope: AudioObjectPropertyScope
) -> Int {
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamConfiguration,
mScope: scope,
mElement: kAudioObjectPropertyElementMain
)
var size: UInt32 = 0
guard AudioObjectGetPropertyDataSize(deviceID, &addr, 0, nil, &size) == noErr,
size > 0 else { return 0 }
let bufferPtr: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(
byteCount: Int(size),
alignment: MemoryLayout<AudioBufferList>.alignment
)
defer { bufferPtr.deallocate() }
guard AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, bufferPtr) == noErr
else { return 0 }
let bl: AudioBufferList = bufferPtr.assumingMemoryBound(to: AudioBufferList.self).pointee
var channels: Int = 0
withUnsafePointer(to: bl.mBuffers) { ptr in
for i: Int in 0..<Int(bl.mNumberBuffers) {
let buf: AudioBuffer = UnsafeRawPointer(ptr)
.advanced(by: i * MemoryLayout<AudioBuffer>.stride)
.assumingMemoryBound(to: AudioBuffer.self).pointee
channels += Int(buf.mNumberChannels)
}
}
return channels
}
/// Queries the device's transport type. Returns `0` (`kAudioDeviceTransportTypeUnknown`)
/// if the property read fails — callers compare against `kAudioDeviceTransportTypeBuiltIn`,
/// so a failed read simply causes the device not to be classified as built-in (the safe
/// fallback for `findBuiltInDuplexDevice`).
private func deviceTransportType(_ deviceID: AudioDeviceID) -> UInt32 {
var transportType: UInt32 = 0
var size: UInt32 = UInt32(MemoryLayout<UInt32>.size)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyTransportType,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let status: OSStatus = AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, &transportType)
return status == noErr ? transportType : 0
}
private func findBuiltInDuplexDevice(
numInputChannels: Int,
numOutputChannels: Int
) -> AudioDeviceID? {
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var size: UInt32 = 0
guard AudioObjectGetPropertyDataSize(
AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size) == noErr,
size > 0 else { return nil }
let deviceCount: Int = Int(size) / MemoryLayout<AudioDeviceID>.size
var devices: [AudioDeviceID] = [AudioDeviceID](repeating: 0, count: deviceCount)
guard AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &devices) == noErr
else { return nil }
for deviceID: AudioDeviceID in devices {
guard deviceTransportType(deviceID) == kAudioDeviceTransportTypeBuiltIn else { continue }
let inputCh: Int = deviceChannelCount(deviceID, scope: kAudioDevicePropertyScopeInput)
let outputCh: Int = deviceChannelCount(deviceID, scope: kAudioDevicePropertyScopeOutput)
if inputCh >= numInputChannels && outputCh >= numOutputChannels {
return deviceID
}
}
return nil
}
private func deviceUID(_ deviceID: AudioDeviceID) throws -> String {
var uid: Unmanaged<CFString>? = nil
var size: UInt32 = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyDeviceUID,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var status: OSStatus = noErr
withUnsafeMutablePointer(to: &uid) { ptr in
status = AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, ptr)
}
guard status == noErr else { throw CoreAudioError.aggregateDeviceCreationFailed(status) }
return uid.map { $0.takeRetainedValue() as String } ?? ""
}
private func findCoreAudioPluginID() -> AudioObjectID {
var bundleID: CFString = "com.apple.audio.CoreAudio" as CFString
var pluginID: AudioObjectID = AudioObjectID(kAudioObjectUnknown)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyPlugInForBundleID,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
withUnsafeMutablePointer(to: &bundleID) { bundlePtr in
withUnsafeMutablePointer(to: &pluginID) { pluginPtr in
var translation: AudioValueTranslation = AudioValueTranslation(
mInputData: UnsafeMutableRawPointer(bundlePtr),
mInputDataSize: UInt32(MemoryLayout<CFString>.size),
mOutputData: UnsafeMutableRawPointer(pluginPtr),
mOutputDataSize: UInt32(MemoryLayout<AudioObjectID>.size)
)
var size: UInt32 = UInt32(MemoryLayout<AudioValueTranslation>.size)
AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &translation)
}
}
return pluginID
}
private func makeAggregateDevice(
outputDeviceID: AudioDeviceID,
inputDeviceID: AudioDeviceID
) throws -> AudioDeviceID {
coreAudioPluginID = findCoreAudioPluginID()
guard coreAudioPluginID != kAudioObjectUnknown else {
throw CoreAudioError.aggregateDeviceCreationFailed(noErr)
}
let outputUID: String = try deviceUID(outputDeviceID)
let inputUID: String = try deviceUID(inputDeviceID)
// Output device is master — drives the clock
let subDeviceList: [CFDictionary] = [
[kAudioSubDeviceUIDKey: outputUID] as CFDictionary,
[kAudioSubDeviceUIDKey: inputUID] as CFDictionary,
]
let aggDesc: [String: Any] = [
kAudioAggregateDeviceNameKey: "LyrebirdAggregate",
kAudioAggregateDeviceUIDKey: "com.lyrebird.aggregate.\(UUID().uuidString)",
kAudioAggregateDeviceSubDeviceListKey: subDeviceList,
kAudioAggregateDeviceMainSubDeviceKey: outputUID,
kAudioAggregateDeviceIsPrivateKey: 1, // auto-destroyed when plugin releases it
kAudioAggregateDeviceIsStackedKey: 0,
]
var newDeviceID: AudioDeviceID = AudioDeviceID(kAudioObjectUnknown)
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioPlugInCreateAggregateDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
let qualifier: CFDictionary = aggDesc as CFDictionary
var size: UInt32 = UInt32(MemoryLayout<AudioDeviceID>.size)
var status: OSStatus = noErr
withUnsafePointer(to: qualifier) { qualPtr in
status = AudioObjectGetPropertyData(
coreAudioPluginID, &addr,
UInt32(MemoryLayout<CFDictionary>.size), qualPtr,
&size, &newDeviceID
)
}
guard status == noErr else { throw CoreAudioError.aggregateDeviceCreationFailed(status) }
aggregateDeviceID = newDeviceID
return newDeviceID
}
private func destroyAggregateDevice() {
guard aggregateDeviceID != AudioDeviceID(kAudioObjectUnknown),
coreAudioPluginID != AudioObjectID(kAudioObjectUnknown) else { return }
var addr: AudioObjectPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioPlugInDestroyAggregateDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain
)
var deviceID: AudioDeviceID = aggregateDeviceID
let size: UInt32 = UInt32(MemoryLayout<AudioDeviceID>.size)
AudioObjectSetPropertyData(coreAudioPluginID, &addr, 0, nil, size, &deviceID)
aggregateDeviceID = AudioDeviceID(kAudioObjectUnknown)
}
}
// MARK: - C render callback (must be a free function for @convention(c))
private func lyrebirdRenderCallback(
inRefCon: UnsafeMutableRawPointer,
ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>,
inTimeStamp: UnsafePointer<AudioTimeStamp>,
inBusNumber: UInt32,
inNumberFrames: UInt32,
ioData: UnsafeMutablePointer<AudioBufferList>?
) -> OSStatus {
let driver: CoreAudioDriver = Unmanaged<CoreAudioDriver>.fromOpaque(inRefCon).takeUnretainedValue()
return driver.render(
actionFlags: ioActionFlags,
timeStamp: inTimeStamp,
busNumber: inBusNumber,
numFrames: inNumberFrames,
ioData: ioData
)
}
#endif
#endif